BlueGit

ict rusty-teams

feat(channels): per-channel notifications, tab bar with embedded websites, Shared tab

| Before | After |
|---|---|
| App-local "followed" channels decide alerts | Teams' per-channel setting: banner and activity, activity only, off, include thread replies (right-click > Notifications), synced; bell icons on rows |
| No tabs | Tab bar: Posts, Shared, the channel's tabs in saved order, overflow menu |
| - | Website tabs embedded on Windows (WebView2, "Open in browser"), browser on Linux; app tabs open their Teams web link (Graph tab webUrl) |
| No files view | Shared tab like Teams: In library (breadcrumb, upload, drag and drop, new folder, open in SharePoint) and In messages (files and links from posts) |

- Replies in threads you started or replied to still notify when a channel is Off, like Teams.
- Fix: file resolve used $select with @microsoft.graph.downloadUrl, which Graph drops; chat file cards and library downloads now get the URL (library reuses the listing URL for 50 min).
- Store migrations 0015 (channel tabs) and 0016 (channel notifications).
- WebView2 embedding is not yet run on Windows; on any embed failure the tab opens in the browser.

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-09 · 7 weeks ago

Hash
9c8b7dc3720131ee870c7a03471e1158fd1e4af4
Parent
6fee847d
61 files changed +5112 −242
README.md +1 −0
@@ -35,6 +35,7 @@
35 35 **Chats and channels**
36 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 - Channel tabs and the Shared tab (library and files from posts), per-channel notifications
38 39 - Chat menu: pin, move to folder, mark as unread, mute, hide, leave
39 40 - Read receipts, typing indicator with faces, presence, unread jump
40 41 - Own status, status message and work location from the avatar menu; profile cards with org chart
@@ -35,6 +35,7 @@
35**Chats and channels**
35**Chats and channels**
36- Teams pin order, chat folders, hidden teams, Muted and Meeting chats sections
36- Teams pin order, chat folders, hidden teams, Muted and Meeting chats sections
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
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- Channel tabs and the Shared tab (library and files from posts), per-channel notifications
38- Chat menu: pin, move to folder, mark as unread, mute, hide, leave
39- Chat menu: pin, move to folder, mark as unread, mute, hide, leave
39- Read receipts, typing indicator with faces, presence, unread jump
40- Read receipts, typing indicator with faces, presence, unread jump
40- Own status, status message and work location from the avatar menu; profile cards with org chart
41- Own status, status message and work location from the avatar menu; profile cards with org chart
ROADMAP.md +5 −5
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 83 %** (72 done, 1 partial, 14 missing of 87). Partial counts half.
5 **Parity: 87 %** (75 done, 1 partial, 11 missing of 87). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -13,7 +13,7 @@ Feature parity with the Microsoft Teams desktop client.
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 |
16 | [Channels](#channels) | 57 % | 4 | 0 | 3 |
16 | [Channels](#channels) | 100 % | 7 | 0 | 0 |
17 17 | [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
18 18 | [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |
19 19 | [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
@@ -114,9 +114,9 @@ Feature parity with the Microsoft Teams desktop client.
114 114 | Posts feed, open a conversation, reply | Done | Newest activity on top, inline reply in the card |
115 115 | New post with subject | Done | Subject is stored with the message |
116 116 | Post cards like Teams | Done | One card per post: root and the last 3 replies |
117 | Follow a channel, per-channel notifications | Missing | |
118 | Channel tabs: tab bar, website and app tabs | Missing | Plan: each tab's Teams Web page in a WebView2 |
119 | Files tab | Missing | Plan: native, the channel's SharePoint folder via Graph |
117 | Follow a channel, per-channel notifications | Done | Right-click > Notifications: banner and activity, activity only, off, include thread replies; synced with Teams; bell icons in the sidebar |
118 | Channel tabs: tab bar, website and app tabs | Done | Posts, Shared, then the channel's tabs with overflow; website tabs embedded on Windows (WebView2), browser on Linux; app tabs open in Teams web |
119 | Files tab | Done | "Shared" like Teams: In library (folders, upload, drag and drop, new folder, open in SharePoint) and In messages (files and links from posts) |
120 120
121 121 ## Notifications
122 122
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 83 %** (72 done, 1 partial, 14 missing of 87). Partial counts half.
5**Parity: 87 %** (75 done, 1 partial, 11 missing of 87). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -13,7 +13,7 @@ Feature parity with the Microsoft Teams desktop client.
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 |
16| [Channels](#channels) | 57 % | 4 | 0 | 3 |
16| [Channels](#channels) | 100 % | 7 | 0 | 0 |
17| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
17| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
18| [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |
18| [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
@@ -114,9 +114,9 @@ Feature parity with the Microsoft Teams desktop client.
114| Posts feed, open a conversation, reply | Done | Newest activity on top, inline reply in the card |
114| Posts feed, open a conversation, reply | Done | Newest activity on top, inline reply in the card |
115| New post with subject | Done | Subject is stored with the message |
115| New post with subject | Done | Subject is stored with the message |
116| Post cards like Teams | Done | One card per post: root and the last 3 replies |
116| Post cards like Teams | Done | One card per post: root and the last 3 replies |
117| Follow a channel, per-channel notifications | Missing | |
117| Follow a channel, per-channel notifications | Done | Right-click > Notifications: banner and activity, activity only, off, include thread replies; synced with Teams; bell icons in the sidebar |
118| Channel tabs: tab bar, website and app tabs | Missing | Plan: each tab's Teams Web page in a WebView2 |
118| Channel tabs: tab bar, website and app tabs | Done | Posts, Shared, then the channel's tabs with overflow; website tabs embedded on Windows (WebView2), browser on Linux; app tabs open in Teams web |
119| Files tab | Missing | Plan: native, the channel's SharePoint folder via Graph |
119| Files tab | Done | "Shared" like Teams: In library (folders, upload, drag and drop, new folder, open in SharePoint) and In messages (files and links from posts) |
120
120
121## Notifications
121## Notifications
122
122
crates/app/src/activity/service.rs +0 −1
@@ -144,7 +144,6 @@ impl ActivityCenter {
144 144 let found = self.tracker.collect(
145 145 &state.store,
146 146 &state.sidebar,
147 &state.followed_channels,
148 147 my_user_id.as_deref(),
149 148 conversation_id,
150 149 );
@@ -144,7 +144,6 @@ impl ActivityCenter {
144 let found = self.tracker.collect(
144 let found = self.tracker.collect(
145 &state.store,
145 &state.store,
146 &state.sidebar,
146 &state.sidebar,
147 &state.followed_channels,
148 my_user_id.as_deref(),
147 my_user_id.as_deref(),
149 conversation_id,
148 conversation_id,
150 );
149 );
crates/app/src/app_state.rs +1 −12
@@ -17,7 +17,6 @@ use crate::data::{self, Directory};
17 17 use crate::local_previews::{LocalPreview, load_local_previews};
18 18 use crate::message_actions::{ForwardSource, SavedSet};
19 19 use crate::notice::Notice;
20 use crate::notify;
21 20 use crate::profile_state::{ProfileCache, ProfileRequest};
22 21 use crate::typing::TypingState;
23 22
@@ -81,7 +80,6 @@ pub struct AppState {
81 80 pub directory: Directory,
82 81 pub collapsed: HashSet<String>,
83 82 pub expanded_lists: HashSet<String>,
84 pub followed_channels: HashSet<String>,
85 83 pub start_on_channels: bool,
86 84 pub pending_jump: Option<(String, String)>,
87 85 pub cards: CardState,
@@ -165,7 +163,6 @@ impl AppState {
165 163 directory: Directory::default(),
166 164 collapsed: HashSet::new(),
167 165 expanded_lists: HashSet::new(),
168 followed_channels: HashSet::new(),
169 166 start_on_channels: false,
170 167 pending_jump: None,
171 168 cards: CardState::default(),
@@ -192,7 +189,6 @@ impl AppState {
192 189 };
193 190 state.local_previews = load_local_previews(&state.store);
194 191 state.collapsed = state.load_collapsed();
195 state.followed_channels = notify::load_followed_channels(&state.store);
196 192 if !mode.demo {
197 193 state.directory.load_cached_presence(&state.store);
198 194 state.reload_directory();
@@ -215,14 +211,6 @@ impl AppState {
215 211 .unwrap_or_default()
216 212 }
217 213
218 pub fn toggle_followed_channel(&mut self, channel_id: &str, cx: &mut Context<Self>) {
219 if !self.followed_channels.remove(channel_id) {
220 self.followed_channels.insert(channel_id.to_owned());
221 }
222 notify::save_followed_channels(&self.store, &self.followed_channels);
223 cx.notify();
224 }
225
226 214 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
227 215 let now_collapsed = self.collapsed.insert(section_id.to_owned());
228 216 if !now_collapsed {
@@ -812,6 +800,7 @@ mod tests {
812 800 }],
813 801 hidden: false,
814 802 hidden_channel_ids: Vec::new(),
803 notifications: Default::default(),
815 804 }],
816 805 }
817 806 }
@@ -17,7 +17,6 @@ use crate::data::{self, Directory};
17use crate::local_previews::{LocalPreview, load_local_previews};
17use crate::local_previews::{LocalPreview, load_local_previews};
18use crate::message_actions::{ForwardSource, SavedSet};
18use crate::message_actions::{ForwardSource, SavedSet};
19use crate::notice::Notice;
19use crate::notice::Notice;
20use crate::notify;
21use crate::profile_state::{ProfileCache, ProfileRequest};
20use crate::profile_state::{ProfileCache, ProfileRequest};
22use crate::typing::TypingState;
21use crate::typing::TypingState;
23
22
@@ -81,7 +80,6 @@ pub struct AppState {
81 pub directory: Directory,
80 pub directory: Directory,
82 pub collapsed: HashSet<String>,
81 pub collapsed: HashSet<String>,
83 pub expanded_lists: HashSet<String>,
82 pub expanded_lists: HashSet<String>,
84 pub followed_channels: HashSet<String>,
85 pub start_on_channels: bool,
83 pub start_on_channels: bool,
86 pub pending_jump: Option<(String, String)>,
84 pub pending_jump: Option<(String, String)>,
87 pub cards: CardState,
85 pub cards: CardState,
@@ -165,7 +163,6 @@ impl AppState {
165 directory: Directory::default(),
163 directory: Directory::default(),
166 collapsed: HashSet::new(),
164 collapsed: HashSet::new(),
167 expanded_lists: HashSet::new(),
165 expanded_lists: HashSet::new(),
168 followed_channels: HashSet::new(),
169 start_on_channels: false,
166 start_on_channels: false,
170 pending_jump: None,
167 pending_jump: None,
171 cards: CardState::default(),
168 cards: CardState::default(),
@@ -192,7 +189,6 @@ impl AppState {
192 };
189 };
193 state.local_previews = load_local_previews(&state.store);
190 state.local_previews = load_local_previews(&state.store);
194 state.collapsed = state.load_collapsed();
191 state.collapsed = state.load_collapsed();
195 state.followed_channels = notify::load_followed_channels(&state.store);
196 if !mode.demo {
192 if !mode.demo {
197 state.directory.load_cached_presence(&state.store);
193 state.directory.load_cached_presence(&state.store);
198 state.reload_directory();
194 state.reload_directory();
@@ -215,14 +211,6 @@ impl AppState {
215 .unwrap_or_default()
211 .unwrap_or_default()
216 }
212 }
217
213
218 pub fn toggle_followed_channel(&mut self, channel_id: &str, cx: &mut Context<Self>) {
219 if !self.followed_channels.remove(channel_id) {
220 self.followed_channels.insert(channel_id.to_owned());
221 }
222 notify::save_followed_channels(&self.store, &self.followed_channels);
223 cx.notify();
224 }
225
226 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
214 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
227 let now_collapsed = self.collapsed.insert(section_id.to_owned());
215 let now_collapsed = self.collapsed.insert(section_id.to_owned());
228 if !now_collapsed {
216 if !now_collapsed {
@@ -812,6 +800,7 @@ mod tests {
812 }],
800 }],
813 hidden: false,
801 hidden: false,
814 hidden_channel_ids: Vec::new(),
802 hidden_channel_ids: Vec::new(),
803 notifications: Default::default(),
815 }],
804 }],
816 }
805 }
817 }
806 }
crates/app/src/channel_files.rs added +449 −0
@@ -0,0 +1,449 @@
1 use std::collections::HashMap;
2 use std::time::{Duration, Instant};
3
4 use chrono::{DateTime, FixedOffset, NaiveDate, Utc};
5 use store::MessageRecord;
6 use teams_core::{
7 DriveEntry, DriveFolder, FileCard, LibraryFile, files, preview_text, public_links,
8 };
9
10 use crate::format;
11
12 const WEEK_DAYS: i64 = 6;
13 const EXCERPT_WORDS: usize = 6;
14 const DOWNLOAD_URL_LIFETIME: Duration = Duration::from_secs(50 * 60);
15
16 #[derive(Debug, Clone, PartialEq, Eq)]
17 pub enum DownloadSource {
18 Share,
19 Library(LibraryFile),
20 }
21
22 pub fn library_file(entry: &DriveEntry, listed_at: Option<Instant>, now: Instant) -> LibraryFile {
23 let fresh = listed_at
24 .is_some_and(|listed_at| now.saturating_duration_since(listed_at) < DOWNLOAD_URL_LIFETIME);
25 LibraryFile {
26 drive_id: entry.drive_id.clone(),
27 item_id: entry.id.clone(),
28 name: entry.name.clone(),
29 size: entry.size,
30 cached_url: entry.download_url.clone().filter(|_| fresh),
31 }
32 }
33
34 #[derive(Debug, Clone, PartialEq, Eq)]
35 pub struct Crumb {
36 pub name: String,
37 pub folder: DriveFolder,
38 pub web_url: String,
39 }
40
41 #[derive(Debug, Clone, PartialEq, Eq)]
42 pub struct LibraryPath {
43 crumbs: Vec<Crumb>,
44 }
45
46 impl LibraryPath {
47 pub fn new(root: Crumb) -> Self {
48 LibraryPath { crumbs: vec![root] }
49 }
50
51 pub fn crumbs(&self) -> &[Crumb] {
52 &self.crumbs
53 }
54
55 pub fn current(&self) -> &DriveFolder {
56 &self.crumbs[self.crumbs.len() - 1].folder
57 }
58
59 pub fn current_web_url(&self) -> &str {
60 &self.crumbs[self.crumbs.len() - 1].web_url
61 }
62
63 pub fn enter(&mut self, entry: &DriveEntry) {
64 self.crumbs.push(Crumb {
65 name: entry.name.clone(),
66 folder: entry.folder(),
67 web_url: entry.web_url.clone(),
68 });
69 }
70
71 pub fn go_to(&mut self, index: usize) {
72 self.crumbs.truncate(index + 1);
73 }
74 }
75
76 pub fn count_label(child_count: u64) -> String {
77 match child_count {
78 1 => "1 item".to_owned(),
79 count => format!("{count} items"),
80 }
81 }
82
83 pub fn size_label(entry: &DriveEntry) -> String {
84 match entry.child_count {
85 Some(count) => count_label(count),
86 None => format::file_size_label(entry.size),
87 }
88 }
89
90 pub fn sorted_entries(mut entries: Vec<DriveEntry>) -> Vec<DriveEntry> {
91 entries.sort_by_cached_key(|entry| (!entry.is_folder(), entry.name.to_lowercase()));
92 entries
93 }
94
95 pub fn file_card(entry: &DriveEntry) -> FileCard {
96 FileCard {
97 kind: teams_core::FileKind::from_name(&entry.name),
98 name: entry.name.clone(),
99 content_type: None,
100 size: Some(entry.size),
101 open_url: entry.web_url.clone(),
102 }
103 }
104
105 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
106 pub enum MessageFilter {
107 All,
108 Files,
109 Links,
110 }
111
112 #[derive(Debug, Clone, PartialEq, Eq)]
113 pub enum SharedContent {
114 File(FileCard),
115 Link(String),
116 }
117
118 #[derive(Debug, Clone, PartialEq, Eq)]
119 pub struct SharedItem {
120 pub content: SharedContent,
121 pub author: String,
122 pub post_label: String,
123 pub message_id: String,
124 pub created_at: DateTime<Utc>,
125 }
126
127 impl SharedItem {
128 pub fn name(&self) -> &str {
129 match &self.content {
130 SharedContent::File(card) => &card.name,
131 SharedContent::Link(url) => url,
132 }
133 }
134
135 fn matches(&self, filter: MessageFilter) -> bool {
136 matches!(
137 (filter, &self.content),
138 (MessageFilter::All, _)
139 | (MessageFilter::Files, SharedContent::File(_))
140 | (MessageFilter::Links, SharedContent::Link(_))
141 )
142 }
143 }
144
145 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
146 pub enum SharedGroup {
147 ThisWeek,
148 Earlier,
149 }
150
151 impl SharedGroup {
152 pub fn label(self) -> &'static str {
153 match self {
154 SharedGroup::ThisWeek => "This week",
155 SharedGroup::Earlier => "Earlier",
156 }
157 }
158 }
159
160 fn post_label(root: Option<&MessageRecord>) -> String {
161 let Some(root) = root else {
162 return String::new();
163 };
164 if let Some(subject) = root
165 .subject
166 .as_deref()
167 .filter(|subject| !subject.is_empty())
168 {
169 return subject.to_owned();
170 }
171 let text = preview_text(&root.body_html).unwrap_or_default();
172 let words: Vec<&str> = text.split_whitespace().collect();
173 let shown = words[..words.len().min(EXCERPT_WORDS)].join(" ");
174 if words.len() > EXCERPT_WORDS {
175 format!("{shown} ...")
176 } else {
177 shown
178 }
179 }
180
181 pub fn shared_items(records: &[MessageRecord]) -> Vec<SharedItem> {
182 let roots: HashMap<&str, &MessageRecord> = records
183 .iter()
184 .filter(|record| record.reply_to_id.is_none())
185 .map(|record| (record.message_id.as_str(), record))
186 .collect();
187 let mut items = Vec::new();
188 for record in records.iter().filter(|record| !record.deleted) {
189 let root = match record.reply_to_id.as_deref() {
190 Some(root_id) => roots.get(root_id).copied(),
191 None => Some(record),
192 };
193 let label = post_label(root);
194 let author = record.sender_name.clone().unwrap_or_default();
195 let contents = files(record)
196 .into_iter()
197 .map(SharedContent::File)
198 .chain(public_links(record).into_iter().map(SharedContent::Link));
199 items.extend(contents.map(|content| SharedItem {
200 content,
201 author: author.clone(),
202 post_label: label.clone(),
203 message_id: record.message_id.clone(),
204 created_at: record.created_at,
205 }));
206 }
207 items.sort_by_key(|item| std::cmp::Reverse(item.created_at));
208 items
209 }
210
211 pub fn group_of(created_at: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> SharedGroup {
212 let day = created_at.with_timezone(&offset).date_naive();
213 if (today - day).num_days() <= WEEK_DAYS {
214 SharedGroup::ThisWeek
215 } else {
216 SharedGroup::Earlier
217 }
218 }
219
220 pub fn grouped_items(
221 items: &[SharedItem],
222 filter: MessageFilter,
223 today: NaiveDate,
224 offset: FixedOffset,
225 ) -> Vec<(SharedGroup, Vec<usize>)> {
226 let mut groups: Vec<(SharedGroup, Vec<usize>)> = Vec::new();
227 for (index, item) in items
228 .iter()
229 .enumerate()
230 .filter(|(_, item)| item.matches(filter))
231 {
232 let group = group_of(item.created_at, today, offset);
233 match groups.iter_mut().find(|(known, _)| *known == group) {
234 Some((_, members)) => members.push(index),
235 None => groups.push((group, vec![index])),
236 }
237 }
238 groups.sort_by_key(|(group, _)| *group as u8);
239 groups
240 }
241
242 #[cfg(test)]
243 mod tests {
244 use chrono::TimeZone;
245
246 use super::*;
247
248 fn folder(id: &str) -> DriveFolder {
249 DriveFolder {
250 drive_id: "drive".to_owned(),
251 item_id: id.to_owned(),
252 }
253 }
254
255 fn entry(name: &str, child_count: Option<u64>, size: u64) -> DriveEntry {
256 DriveEntry {
257 drive_id: "drive".to_owned(),
258 id: format!("id-{name}"),
259 name: name.to_owned(),
260 web_url: format!("https://x/{name}"),
261 size,
262 modified_at: None,
263 modified_by: None,
264 child_count,
265 download_url: None,
266 }
267 }
268
269 fn record(id: &str, reply_to: Option<&str>, days_ago: i64, html: &str) -> MessageRecord {
270 MessageRecord {
271 conversation_id: "channel".to_owned(),
272 message_id: id.to_owned(),
273 reply_to_id: reply_to.map(str::to_owned),
274 sender_id: None,
275 sender_name: Some("Mara".to_owned()),
276 created_at: Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap()
277 - chrono::Duration::days(days_ago),
278 edited_at: None,
279 deleted: false,
280 body_html: html.to_owned(),
281 attachments_json: "[]".to_owned(),
282 reactions_json: "[]".to_owned(),
283 mentions_json: "[]".to_owned(),
284 sender_application_id: None,
285 links_json: "[]".to_owned(),
286 subject: None,
287 }
288 }
289
290 fn with_file(mut record: MessageRecord, name: &str) -> MessageRecord {
291 record.attachments_json = format!(
292 r#"[{{"content_type":"reference","name":"{name}","url":"https://x/{name}","text":null,"size":10}}]"#
293 );
294 record
295 }
296
297 fn today() -> (NaiveDate, FixedOffset) {
298 let offset = FixedOffset::east_opt(0).unwrap();
299 (NaiveDate::from_ymd_opt(2026, 10, 9).unwrap(), offset)
300 }
301
302 #[test]
303 fn a_listed_download_url_is_used_until_it_is_about_to_expire() {
304 let mut listed = entry("a.pdf", None, 5);
305 listed.download_url = Some("https://dl.example/a".to_owned());
306 let start = Instant::now();
307 let url = |age_minutes: u64| {
308 library_file(
309 &listed,
310 Some(start),
311 start + Duration::from_secs(age_minutes * 60),
312 )
313 .cached_url
314 };
315 assert_eq!(url(10).as_deref(), Some("https://dl.example/a"));
316 assert_eq!(url(49).as_deref(), Some("https://dl.example/a"));
317 assert_eq!(url(51), None);
318 assert_eq!(library_file(&listed, None, start).cached_url, None);
319 let without = entry("b.pdf", None, 5);
320 assert_eq!(library_file(&without, Some(start), start).cached_url, None);
321 }
322
323 #[test]
324 fn breadcrumb_path_grows_and_shrinks() {
325 let mut path = LibraryPath::new(Crumb {
326 name: "Channel".to_owned(),
327 folder: folder("root"),
328 web_url: "https://x/root".to_owned(),
329 });
330 path.enter(&entry("Specs", Some(2), 0));
331 path.enter(&entry("2026", Some(0), 0));
332 let names: Vec<&str> = path
333 .crumbs()
334 .iter()
335 .map(|crumb| crumb.name.as_str())
336 .collect();
337 assert_eq!(names, ["Channel", "Specs", "2026"]);
338 assert_eq!(path.current().item_id, "id-2026");
339 path.go_to(1);
340 assert_eq!(path.current().item_id, "id-Specs");
341 path.go_to(0);
342 assert_eq!(path.current(), &folder("root"));
343 assert_eq!(path.current_web_url(), "https://x/root");
344 }
345
346 #[test]
347 fn sizes_and_item_counts_read_like_teams() {
348 assert_eq!(size_label(&entry("a", Some(0), 0)), "0 items");
349 assert_eq!(size_label(&entry("a", Some(1), 0)), "1 item");
350 assert_eq!(size_label(&entry("a", Some(12), 0)), "12 items");
351 assert_eq!(size_label(&entry("a.pdf", None, 48_213)), "47 KB");
352 }
353
354 #[test]
355 fn folders_sort_before_files_by_name() {
356 let sorted = sorted_entries(vec![
357 entry("b.pdf", None, 1),
358 entry("Zeta", Some(0), 0),
359 entry("a.pdf", None, 1),
360 entry("alpha", Some(0), 0),
361 ]);
362 let names: Vec<&str> = sorted.iter().map(|entry| entry.name.as_str()).collect();
363 assert_eq!(names, ["alpha", "Zeta", "a.pdf", "b.pdf"]);
364 }
365
366 #[test]
367 fn messages_group_into_this_week_and_earlier() {
368 let records = vec![
369 with_file(record("old", None, 20, "<p>Old plan</p>"), "Old.pdf"),
370 with_file(record("new", None, 1, "<p>New plan</p>"), "New.xlsx"),
371 record(
372 "link",
373 None,
374 2,
375 "<p><a href=\"https://a.example/x\">x</a></p>",
376 ),
377 ];
378 let items = shared_items(&records);
379 let (day, offset) = today();
380 let groups = grouped_items(&items, MessageFilter::All, day, offset);
381 assert_eq!(groups.len(), 2);
382 assert_eq!(groups[0].0, SharedGroup::ThisWeek);
383 let week: Vec<&str> = groups[0]
384 .1
385 .iter()
386 .map(|index| items[*index].name())
387 .collect();
388 assert_eq!(week, ["New.xlsx", "https://a.example/x"]);
389 assert_eq!(groups[1].0, SharedGroup::Earlier);
390 assert_eq!(items[groups[1].1[0]].name(), "Old.pdf");
391 }
392
393 #[test]
394 fn filter_chips_split_files_from_links() {
395 let records = vec![
396 with_file(record("a", None, 1, "<p>Plan</p>"), "Plan.pdf"),
397 record("b", None, 1, "<p><a href=\"https://a.example\">a</a></p>"),
398 ];
399 let items = shared_items(&records);
400 let (day, offset) = today();
401 let count = |filter| -> usize {
402 grouped_items(&items, filter, day, offset)
403 .iter()
404 .map(|(_, members)| members.len())
405 .sum()
406 };
407 assert_eq!(count(MessageFilter::All), 2);
408 assert_eq!(count(MessageFilter::Files), 1);
409 assert_eq!(count(MessageFilter::Links), 1);
410 }
411
412 #[test]
413 fn replies_name_their_post_by_subject_or_first_words() {
414 let mut root = record(
415 "root",
416 None,
417 1,
418 "<p>One two three four five six seven eight</p>",
419 );
420 let reply = with_file(record("reply", Some("root"), 1, "<p>See file</p>"), "A.pdf");
421 let subject_root = {
422 let mut other = record("other", None, 1, "<p>Body</p>");
423 other.subject = Some("Release 42".to_owned());
424 other
425 };
426 let other_reply = with_file(record("r2", Some("other"), 1, "<p>x</p>"), "B.pdf");
427 root.sender_name = Some("Tobias".to_owned());
428 let items = shared_items(&[root, reply, subject_root, other_reply]);
429 let label_of = |name: &str| {
430 items
431 .iter()
432 .find(|item| item.name() == name)
433 .map(|item| item.post_label.clone())
434 };
435 assert_eq!(
436 label_of("A.pdf").as_deref(),
437 Some("One two three four five six ...")
438 );
439 assert_eq!(label_of("B.pdf").as_deref(), Some("Release 42"));
440 assert_eq!(
441 items
442 .iter()
443 .find(|item| item.name() == "A.pdf")
444 .unwrap()
445 .message_id,
446 "reply"
447 );
448 }
449 }
@@ -0,0 +1,449 @@
1use std::collections::HashMap;
2use std::time::{Duration, Instant};
3
4use chrono::{DateTime, FixedOffset, NaiveDate, Utc};
5use store::MessageRecord;
6use teams_core::{
7 DriveEntry, DriveFolder, FileCard, LibraryFile, files, preview_text, public_links,
8};
9
10use crate::format;
11
12const WEEK_DAYS: i64 = 6;
13const EXCERPT_WORDS: usize = 6;
14const DOWNLOAD_URL_LIFETIME: Duration = Duration::from_secs(50 * 60);
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum DownloadSource {
18 Share,
19 Library(LibraryFile),
20}
21
22pub fn library_file(entry: &DriveEntry, listed_at: Option<Instant>, now: Instant) -> LibraryFile {
23 let fresh = listed_at
24 .is_some_and(|listed_at| now.saturating_duration_since(listed_at) < DOWNLOAD_URL_LIFETIME);
25 LibraryFile {
26 drive_id: entry.drive_id.clone(),
27 item_id: entry.id.clone(),
28 name: entry.name.clone(),
29 size: entry.size,
30 cached_url: entry.download_url.clone().filter(|_| fresh),
31 }
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct Crumb {
36 pub name: String,
37 pub folder: DriveFolder,
38 pub web_url: String,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct LibraryPath {
43 crumbs: Vec<Crumb>,
44}
45
46impl LibraryPath {
47 pub fn new(root: Crumb) -> Self {
48 LibraryPath { crumbs: vec![root] }
49 }
50
51 pub fn crumbs(&self) -> &[Crumb] {
52 &self.crumbs
53 }
54
55 pub fn current(&self) -> &DriveFolder {
56 &self.crumbs[self.crumbs.len() - 1].folder
57 }
58
59 pub fn current_web_url(&self) -> &str {
60 &self.crumbs[self.crumbs.len() - 1].web_url
61 }
62
63 pub fn enter(&mut self, entry: &DriveEntry) {
64 self.crumbs.push(Crumb {
65 name: entry.name.clone(),
66 folder: entry.folder(),
67 web_url: entry.web_url.clone(),
68 });
69 }
70
71 pub fn go_to(&mut self, index: usize) {
72 self.crumbs.truncate(index + 1);
73 }
74}
75
76pub fn count_label(child_count: u64) -> String {
77 match child_count {
78 1 => "1 item".to_owned(),
79 count => format!("{count} items"),
80 }
81}
82
83pub fn size_label(entry: &DriveEntry) -> String {
84 match entry.child_count {
85 Some(count) => count_label(count),
86 None => format::file_size_label(entry.size),
87 }
88}
89
90pub fn sorted_entries(mut entries: Vec<DriveEntry>) -> Vec<DriveEntry> {
91 entries.sort_by_cached_key(|entry| (!entry.is_folder(), entry.name.to_lowercase()));
92 entries
93}
94
95pub fn file_card(entry: &DriveEntry) -> FileCard {
96 FileCard {
97 kind: teams_core::FileKind::from_name(&entry.name),
98 name: entry.name.clone(),
99 content_type: None,
100 size: Some(entry.size),
101 open_url: entry.web_url.clone(),
102 }
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum MessageFilter {
107 All,
108 Files,
109 Links,
110}
111
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub enum SharedContent {
114 File(FileCard),
115 Link(String),
116}
117
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub struct SharedItem {
120 pub content: SharedContent,
121 pub author: String,
122 pub post_label: String,
123 pub message_id: String,
124 pub created_at: DateTime<Utc>,
125}
126
127impl SharedItem {
128 pub fn name(&self) -> &str {
129 match &self.content {
130 SharedContent::File(card) => &card.name,
131 SharedContent::Link(url) => url,
132 }
133 }
134
135 fn matches(&self, filter: MessageFilter) -> bool {
136 matches!(
137 (filter, &self.content),
138 (MessageFilter::All, _)
139 | (MessageFilter::Files, SharedContent::File(_))
140 | (MessageFilter::Links, SharedContent::Link(_))
141 )
142 }
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub enum SharedGroup {
147 ThisWeek,
148 Earlier,
149}
150
151impl SharedGroup {
152 pub fn label(self) -> &'static str {
153 match self {
154 SharedGroup::ThisWeek => "This week",
155 SharedGroup::Earlier => "Earlier",
156 }
157 }
158}
159
160fn post_label(root: Option<&MessageRecord>) -> String {
161 let Some(root) = root else {
162 return String::new();
163 };
164 if let Some(subject) = root
165 .subject
166 .as_deref()
167 .filter(|subject| !subject.is_empty())
168 {
169 return subject.to_owned();
170 }
171 let text = preview_text(&root.body_html).unwrap_or_default();
172 let words: Vec<&str> = text.split_whitespace().collect();
173 let shown = words[..words.len().min(EXCERPT_WORDS)].join(" ");
174 if words.len() > EXCERPT_WORDS {
175 format!("{shown} ...")
176 } else {
177 shown
178 }
179}
180
181pub fn shared_items(records: &[MessageRecord]) -> Vec<SharedItem> {
182 let roots: HashMap<&str, &MessageRecord> = records
183 .iter()
184 .filter(|record| record.reply_to_id.is_none())
185 .map(|record| (record.message_id.as_str(), record))
186 .collect();
187 let mut items = Vec::new();
188 for record in records.iter().filter(|record| !record.deleted) {
189 let root = match record.reply_to_id.as_deref() {
190 Some(root_id) => roots.get(root_id).copied(),
191 None => Some(record),
192 };
193 let label = post_label(root);
194 let author = record.sender_name.clone().unwrap_or_default();
195 let contents = files(record)
196 .into_iter()
197 .map(SharedContent::File)
198 .chain(public_links(record).into_iter().map(SharedContent::Link));
199 items.extend(contents.map(|content| SharedItem {
200 content,
201 author: author.clone(),
202 post_label: label.clone(),
203 message_id: record.message_id.clone(),
204 created_at: record.created_at,
205 }));
206 }
207 items.sort_by_key(|item| std::cmp::Reverse(item.created_at));
208 items
209}
210
211pub fn group_of(created_at: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> SharedGroup {
212 let day = created_at.with_timezone(&offset).date_naive();
213 if (today - day).num_days() <= WEEK_DAYS {
214 SharedGroup::ThisWeek
215 } else {
216 SharedGroup::Earlier
217 }
218}
219
220pub fn grouped_items(
221 items: &[SharedItem],
222 filter: MessageFilter,
223 today: NaiveDate,
224 offset: FixedOffset,
225) -> Vec<(SharedGroup, Vec<usize>)> {
226 let mut groups: Vec<(SharedGroup, Vec<usize>)> = Vec::new();
227 for (index, item) in items
228 .iter()
229 .enumerate()
230 .filter(|(_, item)| item.matches(filter))
231 {
232 let group = group_of(item.created_at, today, offset);
233 match groups.iter_mut().find(|(known, _)| *known == group) {
234 Some((_, members)) => members.push(index),
235 None => groups.push((group, vec![index])),
236 }
237 }
238 groups.sort_by_key(|(group, _)| *group as u8);
239 groups
240}
241
242#[cfg(test)]
243mod tests {
244 use chrono::TimeZone;
245
246 use super::*;
247
248 fn folder(id: &str) -> DriveFolder {
249 DriveFolder {
250 drive_id: "drive".to_owned(),
251 item_id: id.to_owned(),
252 }
253 }
254
255 fn entry(name: &str, child_count: Option<u64>, size: u64) -> DriveEntry {
256 DriveEntry {
257 drive_id: "drive".to_owned(),
258 id: format!("id-{name}"),
259 name: name.to_owned(),
260 web_url: format!("https://x/{name}"),
261 size,
262 modified_at: None,
263 modified_by: None,
264 child_count,
265 download_url: None,
266 }
267 }
268
269 fn record(id: &str, reply_to: Option<&str>, days_ago: i64, html: &str) -> MessageRecord {
270 MessageRecord {
271 conversation_id: "channel".to_owned(),
272 message_id: id.to_owned(),
273 reply_to_id: reply_to.map(str::to_owned),
274 sender_id: None,
275 sender_name: Some("Mara".to_owned()),
276 created_at: Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap()
277 - chrono::Duration::days(days_ago),
278 edited_at: None,
279 deleted: false,
280 body_html: html.to_owned(),
281 attachments_json: "[]".to_owned(),
282 reactions_json: "[]".to_owned(),
283 mentions_json: "[]".to_owned(),
284 sender_application_id: None,
285 links_json: "[]".to_owned(),
286 subject: None,
287 }
288 }
289
290 fn with_file(mut record: MessageRecord, name: &str) -> MessageRecord {
291 record.attachments_json = format!(
292 r#"[{{"content_type":"reference","name":"{name}","url":"https://x/{name}","text":null,"size":10}}]"#
293 );
294 record
295 }
296
297 fn today() -> (NaiveDate, FixedOffset) {
298 let offset = FixedOffset::east_opt(0).unwrap();
299 (NaiveDate::from_ymd_opt(2026, 10, 9).unwrap(), offset)
300 }
301
302 #[test]
303 fn a_listed_download_url_is_used_until_it_is_about_to_expire() {
304 let mut listed = entry("a.pdf", None, 5);
305 listed.download_url = Some("https://dl.example/a".to_owned());
306 let start = Instant::now();
307 let url = |age_minutes: u64| {
308 library_file(
309 &listed,
310 Some(start),
311 start + Duration::from_secs(age_minutes * 60),
312 )
313 .cached_url
314 };
315 assert_eq!(url(10).as_deref(), Some("https://dl.example/a"));
316 assert_eq!(url(49).as_deref(), Some("https://dl.example/a"));
317 assert_eq!(url(51), None);
318 assert_eq!(library_file(&listed, None, start).cached_url, None);
319 let without = entry("b.pdf", None, 5);
320 assert_eq!(library_file(&without, Some(start), start).cached_url, None);
321 }
322
323 #[test]
324 fn breadcrumb_path_grows_and_shrinks() {
325 let mut path = LibraryPath::new(Crumb {
326 name: "Channel".to_owned(),
327 folder: folder("root"),
328 web_url: "https://x/root".to_owned(),
329 });
330 path.enter(&entry("Specs", Some(2), 0));
331 path.enter(&entry("2026", Some(0), 0));
332 let names: Vec<&str> = path
333 .crumbs()
334 .iter()
335 .map(|crumb| crumb.name.as_str())
336 .collect();
337 assert_eq!(names, ["Channel", "Specs", "2026"]);
338 assert_eq!(path.current().item_id, "id-2026");
339 path.go_to(1);
340 assert_eq!(path.current().item_id, "id-Specs");
341 path.go_to(0);
342 assert_eq!(path.current(), &folder("root"));
343 assert_eq!(path.current_web_url(), "https://x/root");
344 }
345
346 #[test]
347 fn sizes_and_item_counts_read_like_teams() {
348 assert_eq!(size_label(&entry("a", Some(0), 0)), "0 items");
349 assert_eq!(size_label(&entry("a", Some(1), 0)), "1 item");
350 assert_eq!(size_label(&entry("a", Some(12), 0)), "12 items");
351 assert_eq!(size_label(&entry("a.pdf", None, 48_213)), "47 KB");
352 }
353
354 #[test]
355 fn folders_sort_before_files_by_name() {
356 let sorted = sorted_entries(vec![
357 entry("b.pdf", None, 1),
358 entry("Zeta", Some(0), 0),
359 entry("a.pdf", None, 1),
360 entry("alpha", Some(0), 0),
361 ]);
362 let names: Vec<&str> = sorted.iter().map(|entry| entry.name.as_str()).collect();
363 assert_eq!(names, ["alpha", "Zeta", "a.pdf", "b.pdf"]);
364 }
365
366 #[test]
367 fn messages_group_into_this_week_and_earlier() {
368 let records = vec![
369 with_file(record("old", None, 20, "<p>Old plan</p>"), "Old.pdf"),
370 with_file(record("new", None, 1, "<p>New plan</p>"), "New.xlsx"),
371 record(
372 "link",
373 None,
374 2,
375 "<p><a href=\"https://a.example/x\">x</a></p>",
376 ),
377 ];
378 let items = shared_items(&records);
379 let (day, offset) = today();
380 let groups = grouped_items(&items, MessageFilter::All, day, offset);
381 assert_eq!(groups.len(), 2);
382 assert_eq!(groups[0].0, SharedGroup::ThisWeek);
383 let week: Vec<&str> = groups[0]
384 .1
385 .iter()
386 .map(|index| items[*index].name())
387 .collect();
388 assert_eq!(week, ["New.xlsx", "https://a.example/x"]);
389 assert_eq!(groups[1].0, SharedGroup::Earlier);
390 assert_eq!(items[groups[1].1[0]].name(), "Old.pdf");
391 }
392
393 #[test]
394 fn filter_chips_split_files_from_links() {
395 let records = vec![
396 with_file(record("a", None, 1, "<p>Plan</p>"), "Plan.pdf"),
397 record("b", None, 1, "<p><a href=\"https://a.example\">a</a></p>"),
398 ];
399 let items = shared_items(&records);
400 let (day, offset) = today();
401 let count = |filter| -> usize {
402 grouped_items(&items, filter, day, offset)
403 .iter()
404 .map(|(_, members)| members.len())
405 .sum()
406 };
407 assert_eq!(count(MessageFilter::All), 2);
408 assert_eq!(count(MessageFilter::Files), 1);
409 assert_eq!(count(MessageFilter::Links), 1);
410 }
411
412 #[test]
413 fn replies_name_their_post_by_subject_or_first_words() {
414 let mut root = record(
415 "root",
416 None,
417 1,
418 "<p>One two three four five six seven eight</p>",
419 );
420 let reply = with_file(record("reply", Some("root"), 1, "<p>See file</p>"), "A.pdf");
421 let subject_root = {
422 let mut other = record("other", None, 1, "<p>Body</p>");
423 other.subject = Some("Release 42".to_owned());
424 other
425 };
426 let other_reply = with_file(record("r2", Some("other"), 1, "<p>x</p>"), "B.pdf");
427 root.sender_name = Some("Tobias".to_owned());
428 let items = shared_items(&[root, reply, subject_root, other_reply]);
429 let label_of = |name: &str| {
430 items
431 .iter()
432 .find(|item| item.name() == name)
433 .map(|item| item.post_label.clone())
434 };
435 assert_eq!(
436 label_of("A.pdf").as_deref(),
437 Some("One two three four five six ...")
438 );
439 assert_eq!(label_of("B.pdf").as_deref(), Some("Release 42"));
440 assert_eq!(
441 items
442 .iter()
443 .find(|item| item.name() == "A.pdf")
444 .unwrap()
445 .message_id,
446 "reply"
447 );
448 }
449}
crates/app/src/chat_actions.rs +50 −1
@@ -2,7 +2,7 @@ use std::future::Future;
2 2
3 3 use chrono::{DateTime, Duration, Local, Offset, Utc};
4 4 use gpui_kit::*;
5 use store::ChatRecord;
5 use store::{ChannelNotifications, ChatRecord};
6 6
7 7 use crate::app_state::{AppState, Selection, chat_title};
8 8 use crate::notice::{NoticeAction, short_error, truncated};
@@ -93,6 +93,55 @@ impl AppState {
93 93 );
94 94 }
95 95
96 pub fn set_channel_notifications(
97 &mut self,
98 channel_id: &str,
99 notifications: ChannelNotifications,
100 cx: &mut Context<Self>,
101 ) {
102 let Some(previous) = self.channel_notifications(channel_id) else {
103 return;
104 };
105 if previous == notifications {
106 return;
107 }
108 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
109 return;
110 };
111 let _ = self
112 .store
113 .set_channel_notifications(channel_id, notifications);
114 self.reload_sidebar(cx);
115 let Some(engine) = engine_or_demo else {
116 return;
117 };
118 let owned_id = channel_id.to_owned();
119 let revert_id = owned_id.clone();
120 self.run_chat_action(
121 "Change notifications",
122 async move {
123 engine
124 .set_channel_notifications(&owned_id, notifications)
125 .await
126 },
127 move |state, cx| {
128 let _ = state.store.set_channel_notifications(&revert_id, previous);
129 state.reload_sidebar(cx);
130 },
131 |_, _| {},
132 cx,
133 );
134 }
135
136 pub fn channel_notifications(&self, channel_id: &str) -> Option<ChannelNotifications> {
137 self.sidebar.teams.iter().find_map(|team| {
138 team.channels
139 .iter()
140 .any(|channel| channel.id == channel_id)
141 .then(|| team.channel_notifications(channel_id))
142 })
143 }
144
96 145 pub fn hide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {
97 146 let Some(chat) = self.chat_record(chat_id) else {
98 147 return;
@@ -2,7 +2,7 @@ use std::future::Future;
2
2
3use chrono::{DateTime, Duration, Local, Offset, Utc};
3use chrono::{DateTime, Duration, Local, Offset, Utc};
4use gpui_kit::*;
4use gpui_kit::*;
5use store::ChatRecord;
5use store::{ChannelNotifications, ChatRecord};
6
6
7use crate::app_state::{AppState, Selection, chat_title};
7use crate::app_state::{AppState, Selection, chat_title};
8use crate::notice::{NoticeAction, short_error, truncated};
8use crate::notice::{NoticeAction, short_error, truncated};
@@ -93,6 +93,55 @@ impl AppState {
93 );
93 );
94 }
94 }
95
95
96 pub fn set_channel_notifications(
97 &mut self,
98 channel_id: &str,
99 notifications: ChannelNotifications,
100 cx: &mut Context<Self>,
101 ) {
102 let Some(previous) = self.channel_notifications(channel_id) else {
103 return;
104 };
105 if previous == notifications {
106 return;
107 }
108 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
109 return;
110 };
111 let _ = self
112 .store
113 .set_channel_notifications(channel_id, notifications);
114 self.reload_sidebar(cx);
115 let Some(engine) = engine_or_demo else {
116 return;
117 };
118 let owned_id = channel_id.to_owned();
119 let revert_id = owned_id.clone();
120 self.run_chat_action(
121 "Change notifications",
122 async move {
123 engine
124 .set_channel_notifications(&owned_id, notifications)
125 .await
126 },
127 move |state, cx| {
128 let _ = state.store.set_channel_notifications(&revert_id, previous);
129 state.reload_sidebar(cx);
130 },
131 |_, _| {},
132 cx,
133 );
134 }
135
136 pub fn channel_notifications(&self, channel_id: &str) -> Option<ChannelNotifications> {
137 self.sidebar.teams.iter().find_map(|team| {
138 team.channels
139 .iter()
140 .any(|channel| channel.id == channel_id)
141 .then(|| team.channel_notifications(channel_id))
142 })
143 }
144
96 pub fn hide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {
145 pub fn hide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {
97 let Some(chat) = self.chat_record(chat_id) else {
146 let Some(chat) = self.chat_record(chat_id) else {
98 return;
147 return;
crates/app/src/demo.rs +156 −2
@@ -5,8 +5,8 @@ use std::time::Instant;
5 5 use chrono::{DateTime, Duration, Local, TimeZone, Utc};
6 6 use gpui_kit::Image;
7 7 use store::{
8 ChannelLayoutRecord, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store,
9 TeamLayoutRecord, TeamRecord,
8 ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
9 ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
10 10 };
11 11 use teams_core::{
12 12 CardActionOutcome, ChatApp, ChatSection, Gif, LinkPreview, MentionCandidate, PersonCandidate,
@@ -127,6 +127,20 @@ const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [
127 127 const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
128 128 const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
129 129 const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
130 const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [
131 (
132 "demo-channel-1-1",
133 ChannelNotificationLevel::BannerAndFeed,
134 false,
135 ),
136 (
137 "demo-channel-1-2",
138 ChannelNotificationLevel::BannerAndFeed,
139 true,
140 ),
141 ("demo-channel-1-3", ChannelNotificationLevel::Off, false),
142 ("demo-channel-2-2", ChannelNotificationLevel::Off, false),
143 ];
130 144
131 145 const UNREAD_CHAT: &str = "demo-chat-atlas";
132 146 const RELEASE_CHAT: &str = "demo-chat-release";
@@ -1415,6 +1429,64 @@ fn unread_messages() -> Vec<MessageRecord> {
1415 1429 .collect()
1416 1430 }
1417 1431
1432 const DEMO_EXTRA_TABS_CHANNEL: &str = "demo-channel-1-2";
1433 const DEMO_EXTRA_TABS: [&str; 6] = [
1434 "Incident dashboard",
1435 "Postmortems",
1436 "Escalation policy",
1437 "Status page",
1438 "Vendor contacts",
1439 "On-call calendar",
1440 ];
1441
1442 fn demo_tab(
1443 channel_id: &str,
1444 name: &str,
1445 definition_id: &str,
1446 open_url: Option<&str>,
1447 ) -> ChannelTabRecord {
1448 ChannelTabRecord {
1449 tab_id: format!("{channel_id}-{}", name.to_lowercase().replace(' ', "-")),
1450 name: name.to_owned(),
1451 definition_id: definition_id.to_owned(),
1452 open_url: open_url.map(str::to_owned),
1453 }
1454 }
1455
1456 fn demo_channel_tabs(channel_id: &str) -> Vec<ChannelTabRecord> {
1457 let mut tabs = vec![
1458 demo_tab(
1459 channel_id,
1460 "Runbook",
1461 "com.microsoft.teamspace.tab.web",
1462 Some("https://wiki.example.com/display/TEAM/Runbook"),
1463 ),
1464 demo_tab(
1465 channel_id,
1466 "Sprint board",
1467 "com.microsoft.teamspace.tab.planner",
1468 None,
1469 ),
1470 demo_tab(
1471 channel_id,
1472 "Team notes",
1473 "0d820ecd-def2-4297-adad-78056cde7c78",
1474 Some("https://onenote.example.com/notes"),
1475 ),
1476 ];
1477 if channel_id == DEMO_EXTRA_TABS_CHANNEL {
1478 tabs.extend(DEMO_EXTRA_TABS.iter().map(|name| {
1479 demo_tab(
1480 channel_id,
1481 name,
1482 "com.microsoft.teamspace.tab.web",
1483 Some("https://wiki.example.com/display/TEAM/Page"),
1484 )
1485 }));
1486 }
1487 tabs
1488 }
1489
1418 1490 fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
1419 1491 DEMO_TEAM_ORDER
1420 1492 .iter()
@@ -1428,6 +1500,15 @@ fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
1428 1500 channel_id: channel.id.clone(),
1429 1501 general: channel.name == "General",
1430 1502 hidden: channel.id == DEMO_HIDDEN_CHANNEL,
1503 tabs: demo_channel_tabs(&channel.id),
1504 notifications: DEMO_CHANNEL_NOTIFICATIONS
1505 .iter()
1506 .find(|(id, _, _)| *id == channel.id)
1507 .map(|(_, level, include_replies)| ChannelNotifications {
1508 level: *level,
1509 include_replies: *include_replies,
1510 })
1511 .unwrap_or_default(),
1431 1512 })
1432 1513 .collect(),
1433 1514 })
@@ -1545,9 +1626,82 @@ fn channel_messages() -> Vec<MessageRecord> {
1545 1626 ),
1546 1627 ];
1547 1628 records.extend(rollout_replies);
1629 records.extend(shared_channel_messages(channel, mara, tobias));
1548 1630 records
1549 1631 }
1550 1632
1633 fn shared_channel_messages(
1634 channel: &str,
1635 mara: (&str, &str),
1636 tobias: (&str, &str),
1637 ) -> Vec<MessageRecord> {
1638 let priya = (PRIYA_ID, "Priya Nair");
1639 let jonas = (JONAS_ID, "Jonas Ortega");
1640 let reference = |name: &str, size: u64| {
1641 format!(
1642 r#"{{"content_type":"reference","name":"{name}","url":"https://demo.sharepoint.example/sites/demo/{name}","text":null,"size":{size}}}"#
1643 )
1644 };
1645 vec![
1646 with_attachments(
1647 with_subject(
1648 message(
1649 channel,
1650 "t5",
1651 None,
1652 priya,
1653 at(1, 14, 5),
1654 "<p>Roadmap deck and checklist for Q4 are attached.</p>",
1655 "[]",
1656 false,
1657 ),
1658 "Q4 planning files",
1659 ),
1660 &format!(
1661 "[{},{}]",
1662 reference("Roadmap-Q4.pptx", 3_412_000),
1663 reference("Release-Checklist-Q4.xlsx", 48_213)
1664 ),
1665 ),
1666 message(
1667 channel,
1668 "t5r1",
1669 Some("t5"),
1670 jonas,
1671 at(1, 14, 30),
1672 "<p>Rollback steps are here: <a href=\"https://docs.example.org/runbooks/rollback\">https://docs.example.org/runbooks/rollback</a></p>",
1673 "[]",
1674 false,
1675 ),
1676 with_attachments(
1677 message(
1678 channel,
1679 "t6",
1680 None,
1681 mara,
1682 at(12, 10, 0),
1683 "<p>Postmortem draft for the September outage. Status page: <a href=\"https://status.example.com/incidents/2026-09\">https://status.example.com/incidents/2026-09</a></p>",
1684 "[]",
1685 false,
1686 ),
1687 &format!("[{}]", reference("Postmortem-Draft.docx", 91_400)),
1688 ),
1689 with_attachments(
1690 message(
1691 channel,
1692 "t7",
1693 None,
1694 tobias,
1695 at(20, 9, 0),
1696 "<p>Rollout plan for the new export, please review.</p>",
1697 "[]",
1698 false,
1699 ),
1700 &format!("[{}]", reference("Rollout-Plan.pdf", 2_306_867)),
1701 ),
1702 ]
1703 }
1704
1551 1705 fn crc32(bytes: &[u8]) -> u32 {
1552 1706 let mut crc = 0xffff_ffffu32;
1553 1707 for byte in bytes {
@@ -5,8 +5,8 @@ use std::time::Instant;
5use chrono::{DateTime, Duration, Local, TimeZone, Utc};
5use chrono::{DateTime, Duration, Local, TimeZone, Utc};
6use gpui_kit::Image;
6use gpui_kit::Image;
7use store::{
7use store::{
8 ChannelLayoutRecord, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store,
8 ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
9 TeamLayoutRecord, TeamRecord,
9 ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
10};
10};
11use teams_core::{
11use teams_core::{
12 CardActionOutcome, ChatApp, ChatSection, Gif, LinkPreview, MentionCandidate, PersonCandidate,
12 CardActionOutcome, ChatApp, ChatSection, Gif, LinkPreview, MentionCandidate, PersonCandidate,
@@ -127,6 +127,20 @@ const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [
127const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
127const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
128const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
128const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
129const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
129const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
130const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [
131 (
132 "demo-channel-1-1",
133 ChannelNotificationLevel::BannerAndFeed,
134 false,
135 ),
136 (
137 "demo-channel-1-2",
138 ChannelNotificationLevel::BannerAndFeed,
139 true,
140 ),
141 ("demo-channel-1-3", ChannelNotificationLevel::Off, false),
142 ("demo-channel-2-2", ChannelNotificationLevel::Off, false),
143];
130
144
131const UNREAD_CHAT: &str = "demo-chat-atlas";
145const UNREAD_CHAT: &str = "demo-chat-atlas";
132const RELEASE_CHAT: &str = "demo-chat-release";
146const RELEASE_CHAT: &str = "demo-chat-release";
@@ -1415,6 +1429,64 @@ fn unread_messages() -> Vec<MessageRecord> {
1415 .collect()
1429 .collect()
1416}
1430}
1417
1431
1432const DEMO_EXTRA_TABS_CHANNEL: &str = "demo-channel-1-2";
1433const DEMO_EXTRA_TABS: [&str; 6] = [
1434 "Incident dashboard",
1435 "Postmortems",
1436 "Escalation policy",
1437 "Status page",
1438 "Vendor contacts",
1439 "On-call calendar",
1440];
1441
1442fn demo_tab(
1443 channel_id: &str,
1444 name: &str,
1445 definition_id: &str,
1446 open_url: Option<&str>,
1447) -> ChannelTabRecord {
1448 ChannelTabRecord {
1449 tab_id: format!("{channel_id}-{}", name.to_lowercase().replace(' ', "-")),
1450 name: name.to_owned(),
1451 definition_id: definition_id.to_owned(),
1452 open_url: open_url.map(str::to_owned),
1453 }
1454}
1455
1456fn demo_channel_tabs(channel_id: &str) -> Vec<ChannelTabRecord> {
1457 let mut tabs = vec![
1458 demo_tab(
1459 channel_id,
1460 "Runbook",
1461 "com.microsoft.teamspace.tab.web",
1462 Some("https://wiki.example.com/display/TEAM/Runbook"),
1463 ),
1464 demo_tab(
1465 channel_id,
1466 "Sprint board",
1467 "com.microsoft.teamspace.tab.planner",
1468 None,
1469 ),
1470 demo_tab(
1471 channel_id,
1472 "Team notes",
1473 "0d820ecd-def2-4297-adad-78056cde7c78",
1474 Some("https://onenote.example.com/notes"),
1475 ),
1476 ];
1477 if channel_id == DEMO_EXTRA_TABS_CHANNEL {
1478 tabs.extend(DEMO_EXTRA_TABS.iter().map(|name| {
1479 demo_tab(
1480 channel_id,
1481 name,
1482 "com.microsoft.teamspace.tab.web",
1483 Some("https://wiki.example.com/display/TEAM/Page"),
1484 )
1485 }));
1486 }
1487 tabs
1488}
1489
1418fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
1490fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
1419 DEMO_TEAM_ORDER
1491 DEMO_TEAM_ORDER
1420 .iter()
1492 .iter()
@@ -1428,6 +1500,15 @@ fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
1428 channel_id: channel.id.clone(),
1500 channel_id: channel.id.clone(),
1429 general: channel.name == "General",
1501 general: channel.name == "General",
1430 hidden: channel.id == DEMO_HIDDEN_CHANNEL,
1502 hidden: channel.id == DEMO_HIDDEN_CHANNEL,
1503 tabs: demo_channel_tabs(&channel.id),
1504 notifications: DEMO_CHANNEL_NOTIFICATIONS
1505 .iter()
1506 .find(|(id, _, _)| *id == channel.id)
1507 .map(|(_, level, include_replies)| ChannelNotifications {
1508 level: *level,
1509 include_replies: *include_replies,
1510 })
1511 .unwrap_or_default(),
1431 })
1512 })
1432 .collect(),
1513 .collect(),
1433 })
1514 })
@@ -1545,9 +1626,82 @@ fn channel_messages() -> Vec<MessageRecord> {
1545 ),
1626 ),
1546 ];
1627 ];
1547 records.extend(rollout_replies);
1628 records.extend(rollout_replies);
1629 records.extend(shared_channel_messages(channel, mara, tobias));
1548 records
1630 records
1549}
1631}
1550
1632
1633fn shared_channel_messages(
1634 channel: &str,
1635 mara: (&str, &str),
1636 tobias: (&str, &str),
1637) -> Vec<MessageRecord> {
1638 let priya = (PRIYA_ID, "Priya Nair");
1639 let jonas = (JONAS_ID, "Jonas Ortega");
1640 let reference = |name: &str, size: u64| {
1641 format!(
1642 r#"{{"content_type":"reference","name":"{name}","url":"https://demo.sharepoint.example/sites/demo/{name}","text":null,"size":{size}}}"#
1643 )
1644 };
1645 vec![
1646 with_attachments(
1647 with_subject(
1648 message(
1649 channel,
1650 "t5",
1651 None,
1652 priya,
1653 at(1, 14, 5),
1654 "<p>Roadmap deck and checklist for Q4 are attached.</p>",
1655 "[]",
1656 false,
1657 ),
1658 "Q4 planning files",
1659 ),
1660 &format!(
1661 "[{},{}]",
1662 reference("Roadmap-Q4.pptx", 3_412_000),
1663 reference("Release-Checklist-Q4.xlsx", 48_213)
1664 ),
1665 ),
1666 message(
1667 channel,
1668 "t5r1",
1669 Some("t5"),
1670 jonas,
1671 at(1, 14, 30),
1672 "<p>Rollback steps are here: <a href=\"https://docs.example.org/runbooks/rollback\">https://docs.example.org/runbooks/rollback</a></p>",
1673 "[]",
1674 false,
1675 ),
1676 with_attachments(
1677 message(
1678 channel,
1679 "t6",
1680 None,
1681 mara,
1682 at(12, 10, 0),
1683 "<p>Postmortem draft for the September outage. Status page: <a href=\"https://status.example.com/incidents/2026-09\">https://status.example.com/incidents/2026-09</a></p>",
1684 "[]",
1685 false,
1686 ),
1687 &format!("[{}]", reference("Postmortem-Draft.docx", 91_400)),
1688 ),
1689 with_attachments(
1690 message(
1691 channel,
1692 "t7",
1693 None,
1694 tobias,
1695 at(20, 9, 0),
1696 "<p>Rollout plan for the new export, please review.</p>",
1697 "[]",
1698 false,
1699 ),
1700 &format!("[{}]", reference("Rollout-Plan.pdf", 2_306_867)),
1701 ),
1702 ]
1703}
1704
1551fn crc32(bytes: &[u8]) -> u32 {
1705fn crc32(bytes: &[u8]) -> u32 {
1552 let mut crc = 0xffff_ffffu32;
1706 let mut crc = 0xffff_ffffu32;
1553 for byte in bytes {
1707 for byte in bytes {
crates/app/src/demo_library.rs added +173 −0
@@ -0,0 +1,173 @@
1 use std::collections::HashMap;
2
3 use chrono::{Duration, Utc};
4 use teams_core::DriveEntry;
5
6 const DEMO_SITE: &str = "https://demo.sharepoint.example/sites/demo";
7 const AUTHORS: [&str; 4] = [
8 "Mara Lindqvist",
9 "Jonas Ortega",
10 "Priya Nair",
11 "Tobias Klein",
12 ];
13 const ROOT_FILES: [(&str, u64); 5] = [
14 ("Roadmap-Q4.pptx", 3_412_000),
15 ("Release-Checklist-Q4.xlsx", 48_213),
16 ("Rollout-Plan.pdf", 2_306_867),
17 ("Postmortem-Draft.docx", 91_400),
18 ("Screenshots.zip", 12_880_000),
19 ];
20 const SPEC_FILES: [(&str, u64); 2] = [("API-Design.pdf", 812_000), ("Data-model.xlsx", 64_300)];
21 const NOTE_FILES: [(&str, u64); 2] = [
22 ("Weekly-sync-notes.docx", 38_900),
23 ("Retro-2026-10.pdf", 205_000),
24 ];
25 const YEAR_FILES: [(&str, u64); 1] = [("Settings-spec-v3.docx", 120_500)];
26
27 #[derive(Default)]
28 pub struct DemoLibrary {
29 children: HashMap<String, Vec<DriveEntry>>,
30 next_id: u64,
31 }
32
33 impl DemoLibrary {
34 pub fn root(&mut self, channel_id: &str, channel_name: &str) -> DriveEntry {
35 let root_id = format!("{channel_id}-root");
36 if !self.children.contains_key(&root_id) {
37 self.fill(&root_id);
38 }
39 self.entry(&root_id, channel_name, Some(0), 0)
40 }
41
42 pub fn children(&self, folder_id: &str) -> Vec<DriveEntry> {
43 self.children
44 .get(folder_id)
45 .map(|entries| {
46 entries
47 .iter()
48 .map(|entry| DriveEntry {
49 child_count: entry.child_count.map(|_| {
50 self.children
51 .get(&entry.id)
52 .map_or(0, |inner| inner.len() as u64)
53 }),
54 ..entry.clone()
55 })
56 .collect()
57 })
58 .unwrap_or_default()
59 }
60
61 pub fn create_folder(&mut self, parent_id: &str, name: &str) -> DriveEntry {
62 let mut name = name.to_owned();
63 let taken = |library: &Self, name: &str| {
64 library.children.get(parent_id).is_some_and(|entries| {
65 entries
66 .iter()
67 .any(|entry| entry.name.eq_ignore_ascii_case(name))
68 })
69 };
70 let base = name.clone();
71 let mut number = 1;
72 while taken(self, &name) {
73 number += 1;
74 name = format!("{base} {number}");
75 }
76 let id = self.new_id(parent_id);
77 let entry = self.entry(&id, &name, Some(0), 0);
78 self.children
79 .entry(parent_id.to_owned())
80 .or_default()
81 .push(entry.clone());
82 self.children.insert(id, Vec::new());
83 entry
84 }
85
86 pub fn add_file(&mut self, parent_id: &str, name: &str, size: u64) -> DriveEntry {
87 let id = self.new_id(parent_id);
88 let entry = self.entry(&id, name, None, size);
89 self.children
90 .entry(parent_id.to_owned())
91 .or_default()
92 .push(entry.clone());
93 entry
94 }
95
96 fn new_id(&mut self, parent_id: &str) -> String {
97 self.next_id += 1;
98 format!("{parent_id}-{}", self.next_id)
99 }
100
101 fn entry(&self, id: &str, name: &str, child_count: Option<u64>, size: u64) -> DriveEntry {
102 let age = Duration::hours(3 + (id.len() as i64 * 37) % 400);
103 DriveEntry {
104 drive_id: "demo-drive".to_owned(),
105 id: id.to_owned(),
106 name: name.to_owned(),
107 web_url: format!("{DEMO_SITE}/{id}/{name}"),
108 size,
109 modified_at: Some(Utc::now() - age),
110 modified_by: Some(AUTHORS[id.len() % AUTHORS.len()].to_owned()),
111 child_count,
112 download_url: None,
113 }
114 }
115
116 fn fill(&mut self, root_id: &str) {
117 let specs = format!("{root_id}-specs");
118 let notes = format!("{root_id}-notes");
119 let year = format!("{specs}-2026");
120 let spec_folder = self.entry(&specs, "Specs", Some(0), 0);
121 let note_folder = self.entry(&notes, "Meeting notes", Some(0), 0);
122 let year_folder = self.entry(&year, "2026", Some(0), 0);
123 let files = |library: &Self, parent: &str, list: &[(&str, u64)]| -> Vec<DriveEntry> {
124 list.iter()
125 .map(|(name, size)| library.entry(&format!("{parent}-{name}"), name, None, *size))
126 .collect()
127 };
128 let mut root = vec![spec_folder, note_folder];
129 root.extend(files(self, root_id, &ROOT_FILES));
130 let mut spec_children = vec![year_folder];
131 spec_children.extend(files(self, &specs, &SPEC_FILES));
132 let note_children = files(self, &notes, &NOTE_FILES);
133 let year_children = files(self, &year, &YEAR_FILES);
134 self.children.insert(root_id.to_owned(), root);
135 self.children.insert(specs, spec_children);
136 self.children.insert(notes, note_children);
137 self.children.insert(year, year_children);
138 }
139 }
140
141 #[cfg(test)]
142 mod tests {
143 use super::*;
144
145 #[test]
146 fn the_demo_library_has_folders_files_and_a_nested_folder() {
147 let mut library = DemoLibrary::default();
148 let root = library.root("demo-channel-1-1", "General");
149 let entries = library.children(&root.id);
150 assert_eq!(entries.iter().filter(|entry| entry.is_folder()).count(), 2);
151 assert_eq!(entries.iter().filter(|entry| !entry.is_folder()).count(), 5);
152 let specs = entries.iter().find(|entry| entry.name == "Specs").unwrap();
153 assert_eq!(specs.child_count, Some(3));
154 let inner = library.children(&specs.id);
155 assert!(
156 inner
157 .iter()
158 .any(|entry| entry.is_folder() && entry.child_count == Some(1))
159 );
160 }
161
162 #[test]
163 fn new_folders_get_a_free_name_and_uploads_show_up() {
164 let mut library = DemoLibrary::default();
165 let root = library.root("demo-channel-1-1", "General");
166 let first = library.create_folder(&root.id, "Specs");
167 assert_eq!(first.name, "Specs 2");
168 library.add_file(&first.id, "a.pdf", 10);
169 let listed = library.children(&root.id);
170 let created = listed.iter().find(|entry| entry.id == first.id).unwrap();
171 assert_eq!(created.child_count, Some(1));
172 }
173 }
@@ -0,0 +1,173 @@
1use std::collections::HashMap;
2
3use chrono::{Duration, Utc};
4use teams_core::DriveEntry;
5
6const DEMO_SITE: &str = "https://demo.sharepoint.example/sites/demo";
7const AUTHORS: [&str; 4] = [
8 "Mara Lindqvist",
9 "Jonas Ortega",
10 "Priya Nair",
11 "Tobias Klein",
12];
13const ROOT_FILES: [(&str, u64); 5] = [
14 ("Roadmap-Q4.pptx", 3_412_000),
15 ("Release-Checklist-Q4.xlsx", 48_213),
16 ("Rollout-Plan.pdf", 2_306_867),
17 ("Postmortem-Draft.docx", 91_400),
18 ("Screenshots.zip", 12_880_000),
19];
20const SPEC_FILES: [(&str, u64); 2] = [("API-Design.pdf", 812_000), ("Data-model.xlsx", 64_300)];
21const NOTE_FILES: [(&str, u64); 2] = [
22 ("Weekly-sync-notes.docx", 38_900),
23 ("Retro-2026-10.pdf", 205_000),
24];
25const YEAR_FILES: [(&str, u64); 1] = [("Settings-spec-v3.docx", 120_500)];
26
27#[derive(Default)]
28pub struct DemoLibrary {
29 children: HashMap<String, Vec<DriveEntry>>,
30 next_id: u64,
31}
32
33impl DemoLibrary {
34 pub fn root(&mut self, channel_id: &str, channel_name: &str) -> DriveEntry {
35 let root_id = format!("{channel_id}-root");
36 if !self.children.contains_key(&root_id) {
37 self.fill(&root_id);
38 }
39 self.entry(&root_id, channel_name, Some(0), 0)
40 }
41
42 pub fn children(&self, folder_id: &str) -> Vec<DriveEntry> {
43 self.children
44 .get(folder_id)
45 .map(|entries| {
46 entries
47 .iter()
48 .map(|entry| DriveEntry {
49 child_count: entry.child_count.map(|_| {
50 self.children
51 .get(&entry.id)
52 .map_or(0, |inner| inner.len() as u64)
53 }),
54 ..entry.clone()
55 })
56 .collect()
57 })
58 .unwrap_or_default()
59 }
60
61 pub fn create_folder(&mut self, parent_id: &str, name: &str) -> DriveEntry {
62 let mut name = name.to_owned();
63 let taken = |library: &Self, name: &str| {
64 library.children.get(parent_id).is_some_and(|entries| {
65 entries
66 .iter()
67 .any(|entry| entry.name.eq_ignore_ascii_case(name))
68 })
69 };
70 let base = name.clone();
71 let mut number = 1;
72 while taken(self, &name) {
73 number += 1;
74 name = format!("{base} {number}");
75 }
76 let id = self.new_id(parent_id);
77 let entry = self.entry(&id, &name, Some(0), 0);
78 self.children
79 .entry(parent_id.to_owned())
80 .or_default()
81 .push(entry.clone());
82 self.children.insert(id, Vec::new());
83 entry
84 }
85
86 pub fn add_file(&mut self, parent_id: &str, name: &str, size: u64) -> DriveEntry {
87 let id = self.new_id(parent_id);
88 let entry = self.entry(&id, name, None, size);
89 self.children
90 .entry(parent_id.to_owned())
91 .or_default()
92 .push(entry.clone());
93 entry
94 }
95
96 fn new_id(&mut self, parent_id: &str) -> String {
97 self.next_id += 1;
98 format!("{parent_id}-{}", self.next_id)
99 }
100
101 fn entry(&self, id: &str, name: &str, child_count: Option<u64>, size: u64) -> DriveEntry {
102 let age = Duration::hours(3 + (id.len() as i64 * 37) % 400);
103 DriveEntry {
104 drive_id: "demo-drive".to_owned(),
105 id: id.to_owned(),
106 name: name.to_owned(),
107 web_url: format!("{DEMO_SITE}/{id}/{name}"),
108 size,
109 modified_at: Some(Utc::now() - age),
110 modified_by: Some(AUTHORS[id.len() % AUTHORS.len()].to_owned()),
111 child_count,
112 download_url: None,
113 }
114 }
115
116 fn fill(&mut self, root_id: &str) {
117 let specs = format!("{root_id}-specs");
118 let notes = format!("{root_id}-notes");
119 let year = format!("{specs}-2026");
120 let spec_folder = self.entry(&specs, "Specs", Some(0), 0);
121 let note_folder = self.entry(&notes, "Meeting notes", Some(0), 0);
122 let year_folder = self.entry(&year, "2026", Some(0), 0);
123 let files = |library: &Self, parent: &str, list: &[(&str, u64)]| -> Vec<DriveEntry> {
124 list.iter()
125 .map(|(name, size)| library.entry(&format!("{parent}-{name}"), name, None, *size))
126 .collect()
127 };
128 let mut root = vec![spec_folder, note_folder];
129 root.extend(files(self, root_id, &ROOT_FILES));
130 let mut spec_children = vec![year_folder];
131 spec_children.extend(files(self, &specs, &SPEC_FILES));
132 let note_children = files(self, &notes, &NOTE_FILES);
133 let year_children = files(self, &year, &YEAR_FILES);
134 self.children.insert(root_id.to_owned(), root);
135 self.children.insert(specs, spec_children);
136 self.children.insert(notes, note_children);
137 self.children.insert(year, year_children);
138 }
139}
140
141#[cfg(test)]
142mod tests {
143 use super::*;
144
145 #[test]
146 fn the_demo_library_has_folders_files_and_a_nested_folder() {
147 let mut library = DemoLibrary::default();
148 let root = library.root("demo-channel-1-1", "General");
149 let entries = library.children(&root.id);
150 assert_eq!(entries.iter().filter(|entry| entry.is_folder()).count(), 2);
151 assert_eq!(entries.iter().filter(|entry| !entry.is_folder()).count(), 5);
152 let specs = entries.iter().find(|entry| entry.name == "Specs").unwrap();
153 assert_eq!(specs.child_count, Some(3));
154 let inner = library.children(&specs.id);
155 assert!(
156 inner
157 .iter()
158 .any(|entry| entry.is_folder() && entry.child_count == Some(1))
159 );
160 }
161
162 #[test]
163 fn new_folders_get_a_free_name_and_uploads_show_up() {
164 let mut library = DemoLibrary::default();
165 let root = library.root("demo-channel-1-1", "General");
166 let first = library.create_folder(&root.id, "Specs");
167 assert_eq!(first.name, "Specs 2");
168 library.add_file(&first.id, "a.pdf", 10);
169 let listed = library.children(&root.id);
170 let created = listed.iter().find(|entry| entry.id == first.id).unwrap();
171 assert_eq!(created.child_count, Some(1));
172 }
173}
crates/app/src/embedded_web.rs added +216 −0
@@ -0,0 +1,216 @@
1 use gpui_kit::component::{
2 button::{Button, ButtonVariants as _},
3 h_flex, v_flex,
4 };
5 use gpui_kit::*;
6 use tokio::sync::mpsc::UnboundedReceiver;
7
8 use crate::theme;
9
10 #[cfg(windows)]
11 mod native_windows;
12 #[cfg(windows)]
13 use native_windows as native;
14 #[cfg(not(windows))]
15 mod native_stub;
16 #[cfg(not(windows))]
17 use native_stub as native;
18
19 pub use native::{Native, NativeEvent, available};
20
21 const BAR_HEIGHT: f32 = 28.;
22 const BAR_TEXT_SIZE: f32 = 11.5;
23 const OPEN_LABEL: &str = "Open in browser \u{2197}";
24
25 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26 pub struct Overlays {
27 pub panels: bool,
28 pub tab_menu: bool,
29 }
30
31 impl Global for Overlays {}
32
33 impl Overlays {
34 pub fn read(cx: &App) -> Self {
35 cx.try_global::<Overlays>().copied().unwrap_or_default()
36 }
37
38 pub fn update(cx: &mut App, change: impl FnOnce(&mut Overlays)) {
39 let mut next = Overlays::read(cx);
40 change(&mut next);
41 if next != Overlays::read(cx) {
42 cx.set_global(next);
43 }
44 }
45
46 pub fn any(self) -> bool {
47 self.panels || self.tab_menu
48 }
49 }
50
51 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
52 pub struct Visibility {
53 pub overlays: Overlays,
54 pub has_area: bool,
55 }
56
57 pub fn embed_visible(visibility: Visibility) -> bool {
58 visibility.has_area && !visibility.overlays.any()
59 }
60
61 pub fn url_bar_text(url: &str) -> String {
62 let shown = url.strip_prefix("https://").unwrap_or(url);
63 shown.strip_suffix('/').unwrap_or(shown).to_owned()
64 }
65
66 pub enum EmbeddedWebEvent {
67 Closed { start_url: String },
68 }
69
70 pub struct EmbeddedWeb {
71 tab_id: String,
72 start_url: String,
73 url: String,
74 native: Native,
75 _events: Task<()>,
76 }
77
78 impl EventEmitter<EmbeddedWebEvent> for EmbeddedWeb {}
79
80 impl EmbeddedWeb {
81 pub fn new(
82 tab_id: String,
83 start_url: String,
84 native: Native,
85 mut events: UnboundedReceiver<NativeEvent>,
86 cx: &mut Context<Self>,
87 ) -> Self {
88 let task = cx.spawn(async move |this, cx| {
89 while let Some(event) = events.recv().await {
90 let handled = this.update(cx, |this, cx| this.on_event(event, cx));
91 if handled.is_err() {
92 break;
93 }
94 }
95 });
96 EmbeddedWeb {
97 tab_id,
98 url: start_url.clone(),
99 start_url,
100 native,
101 _events: task,
102 }
103 }
104
105 pub fn tab_id(&self) -> &str {
106 &self.tab_id
107 }
108
109 fn on_event(&mut self, event: NativeEvent, cx: &mut Context<Self>) {
110 match event {
111 NativeEvent::Navigated(url) => {
112 self.url = url;
113 cx.notify();
114 }
115 NativeEvent::NewWindow(url) => cx.open_url(&url),
116 NativeEvent::Closed => cx.emit(EmbeddedWebEvent::Closed {
117 start_url: self.start_url.clone(),
118 }),
119 }
120 }
121 }
122
123 impl Drop for EmbeddedWeb {
124 fn drop(&mut self) {
125 self.native.close();
126 }
127 }
128
129 impl Render for EmbeddedWeb {
130 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
131 let native = self.native.clone();
132 let open_url = self.url.clone();
133 v_flex()
134 .size_full()
135 .child(
136 h_flex()
137 .h(px(BAR_HEIGHT))
138 .flex_none()
139 .w_full()
140 .px(px(12.))
141 .gap(px(8.))
142 .items_center()
143 .border_b_1()
144 .border_color(theme::border())
145 .child(
146 div()
147 .flex_1()
148 .min_w_0()
149 .overflow_hidden()
150 .text_ellipsis()
151 .whitespace_nowrap()
152 .text_size(px(BAR_TEXT_SIZE))
153 .text_color(theme::text_muted())
154 .child(url_bar_text(&self.url)),
155 )
156 .child(
157 Button::new("embedded-web-open")
158 .ghost()
159 .compact()
160 .label(OPEN_LABEL)
161 .on_click(move |_, _, cx| cx.open_url(&open_url)),
162 ),
163 )
164 .child(
165 div()
166 .flex_1()
167 .min_h_0()
168 .w_full()
169 .bg(theme::background())
170 .child(
171 canvas(
172 move |bounds, window, cx| {
173 let visible = embed_visible(Visibility {
174 overlays: Overlays::read(cx),
175 has_area: bounds.size.width > px(0.)
176 && bounds.size.height > px(0.),
177 });
178 native.place(bounds, window.scale_factor(), visible);
179 },
180 |_, _, _, _| {},
181 )
182 .size_full(),
183 ),
184 )
185 }
186 }
187
188 #[cfg(test)]
189 mod tests {
190 use super::{Overlays, Visibility, embed_visible, url_bar_text};
191
192 fn visibility(panels: bool, tab_menu: bool, has_area: bool) -> Visibility {
193 Visibility {
194 overlays: Overlays { panels, tab_menu },
195 has_area,
196 }
197 }
198
199 #[test]
200 fn the_page_shows_only_without_overlays_and_with_room() {
201 assert!(embed_visible(visibility(false, false, true)));
202 assert!(!embed_visible(visibility(true, false, true)));
203 assert!(!embed_visible(visibility(false, true, true)));
204 assert!(!embed_visible(visibility(false, false, false)));
205 }
206
207 #[test]
208 fn the_url_bar_drops_the_scheme_and_a_trailing_slash() {
209 assert_eq!(url_bar_text("https://docs.example/"), "docs.example");
210 assert_eq!(
211 url_bar_text("https://docs.example/a/b?c=1"),
212 "docs.example/a/b?c=1"
213 );
214 assert_eq!(url_bar_text("http://plain.example"), "http://plain.example");
215 }
216 }
@@ -0,0 +1,216 @@
1use gpui_kit::component::{
2 button::{Button, ButtonVariants as _},
3 h_flex, v_flex,
4};
5use gpui_kit::*;
6use tokio::sync::mpsc::UnboundedReceiver;
7
8use crate::theme;
9
10#[cfg(windows)]
11mod native_windows;
12#[cfg(windows)]
13use native_windows as native;
14#[cfg(not(windows))]
15mod native_stub;
16#[cfg(not(windows))]
17use native_stub as native;
18
19pub use native::{Native, NativeEvent, available};
20
21const BAR_HEIGHT: f32 = 28.;
22const BAR_TEXT_SIZE: f32 = 11.5;
23const OPEN_LABEL: &str = "Open in browser \u{2197}";
24
25#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26pub struct Overlays {
27 pub panels: bool,
28 pub tab_menu: bool,
29}
30
31impl Global for Overlays {}
32
33impl Overlays {
34 pub fn read(cx: &App) -> Self {
35 cx.try_global::<Overlays>().copied().unwrap_or_default()
36 }
37
38 pub fn update(cx: &mut App, change: impl FnOnce(&mut Overlays)) {
39 let mut next = Overlays::read(cx);
40 change(&mut next);
41 if next != Overlays::read(cx) {
42 cx.set_global(next);
43 }
44 }
45
46 pub fn any(self) -> bool {
47 self.panels || self.tab_menu
48 }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct Visibility {
53 pub overlays: Overlays,
54 pub has_area: bool,
55}
56
57pub fn embed_visible(visibility: Visibility) -> bool {
58 visibility.has_area && !visibility.overlays.any()
59}
60
61pub fn url_bar_text(url: &str) -> String {
62 let shown = url.strip_prefix("https://").unwrap_or(url);
63 shown.strip_suffix('/').unwrap_or(shown).to_owned()
64}
65
66pub enum EmbeddedWebEvent {
67 Closed { start_url: String },
68}
69
70pub struct EmbeddedWeb {
71 tab_id: String,
72 start_url: String,
73 url: String,
74 native: Native,
75 _events: Task<()>,
76}
77
78impl EventEmitter<EmbeddedWebEvent> for EmbeddedWeb {}
79
80impl EmbeddedWeb {
81 pub fn new(
82 tab_id: String,
83 start_url: String,
84 native: Native,
85 mut events: UnboundedReceiver<NativeEvent>,
86 cx: &mut Context<Self>,
87 ) -> Self {
88 let task = cx.spawn(async move |this, cx| {
89 while let Some(event) = events.recv().await {
90 let handled = this.update(cx, |this, cx| this.on_event(event, cx));
91 if handled.is_err() {
92 break;
93 }
94 }
95 });
96 EmbeddedWeb {
97 tab_id,
98 url: start_url.clone(),
99 start_url,
100 native,
101 _events: task,
102 }
103 }
104
105 pub fn tab_id(&self) -> &str {
106 &self.tab_id
107 }
108
109 fn on_event(&mut self, event: NativeEvent, cx: &mut Context<Self>) {
110 match event {
111 NativeEvent::Navigated(url) => {
112 self.url = url;
113 cx.notify();
114 }
115 NativeEvent::NewWindow(url) => cx.open_url(&url),
116 NativeEvent::Closed => cx.emit(EmbeddedWebEvent::Closed {
117 start_url: self.start_url.clone(),
118 }),
119 }
120 }
121}
122
123impl Drop for EmbeddedWeb {
124 fn drop(&mut self) {
125 self.native.close();
126 }
127}
128
129impl Render for EmbeddedWeb {
130 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
131 let native = self.native.clone();
132 let open_url = self.url.clone();
133 v_flex()
134 .size_full()
135 .child(
136 h_flex()
137 .h(px(BAR_HEIGHT))
138 .flex_none()
139 .w_full()
140 .px(px(12.))
141 .gap(px(8.))
142 .items_center()
143 .border_b_1()
144 .border_color(theme::border())
145 .child(
146 div()
147 .flex_1()
148 .min_w_0()
149 .overflow_hidden()
150 .text_ellipsis()
151 .whitespace_nowrap()
152 .text_size(px(BAR_TEXT_SIZE))
153 .text_color(theme::text_muted())
154 .child(url_bar_text(&self.url)),
155 )
156 .child(
157 Button::new("embedded-web-open")
158 .ghost()
159 .compact()
160 .label(OPEN_LABEL)
161 .on_click(move |_, _, cx| cx.open_url(&open_url)),
162 ),
163 )
164 .child(
165 div()
166 .flex_1()
167 .min_h_0()
168 .w_full()
169 .bg(theme::background())
170 .child(
171 canvas(
172 move |bounds, window, cx| {
173 let visible = embed_visible(Visibility {
174 overlays: Overlays::read(cx),
175 has_area: bounds.size.width > px(0.)
176 && bounds.size.height > px(0.),
177 });
178 native.place(bounds, window.scale_factor(), visible);
179 },
180 |_, _, _, _| {},
181 )
182 .size_full(),
183 ),
184 )
185 }
186}
187
188#[cfg(test)]
189mod tests {
190 use super::{Overlays, Visibility, embed_visible, url_bar_text};
191
192 fn visibility(panels: bool, tab_menu: bool, has_area: bool) -> Visibility {
193 Visibility {
194 overlays: Overlays { panels, tab_menu },
195 has_area,
196 }
197 }
198
199 #[test]
200 fn the_page_shows_only_without_overlays_and_with_room() {
201 assert!(embed_visible(visibility(false, false, true)));
202 assert!(!embed_visible(visibility(true, false, true)));
203 assert!(!embed_visible(visibility(false, true, true)));
204 assert!(!embed_visible(visibility(false, false, false)));
205 }
206
207 #[test]
208 fn the_url_bar_drops_the_scheme_and_a_trailing_slash() {
209 assert_eq!(url_bar_text("https://docs.example/"), "docs.example");
210 assert_eq!(
211 url_bar_text("https://docs.example/a/b?c=1"),
212 "docs.example/a/b?c=1"
213 );
214 assert_eq!(url_bar_text("http://plain.example"), "http://plain.example");
215 }
216}
crates/app/src/embedded_web/native_stub.rs added +27 −0
@@ -0,0 +1,27 @@
1 #![allow(dead_code)]
2
3 use gpui_kit::*;
4 use tokio::sync::mpsc::UnboundedReceiver;
5
6 pub enum NativeEvent {
7 Navigated(String),
8 NewWindow(String),
9 Closed,
10 }
11
12 pub fn available() -> bool {
13 false
14 }
15
16 #[derive(Clone)]
17 pub struct Native;
18
19 impl Native {
20 pub fn open(_url: &str, _window: &Window) -> Option<(Native, UnboundedReceiver<NativeEvent>)> {
21 None
22 }
23
24 pub fn place(&self, _bounds: Bounds<Pixels>, _scale: f32, _visible: bool) {}
25
26 pub fn close(&self) {}
27 }
@@ -0,0 +1,27 @@
1#![allow(dead_code)]
2
3use gpui_kit::*;
4use tokio::sync::mpsc::UnboundedReceiver;
5
6pub enum NativeEvent {
7 Navigated(String),
8 NewWindow(String),
9 Closed,
10}
11
12pub fn available() -> bool {
13 false
14}
15
16#[derive(Clone)]
17pub struct Native;
18
19impl Native {
20 pub fn open(_url: &str, _window: &Window) -> Option<(Native, UnboundedReceiver<NativeEvent>)> {
21 None
22 }
23
24 pub fn place(&self, _bounds: Bounds<Pixels>, _scale: f32, _visible: bool) {}
25
26 pub fn close(&self) {}
27}
crates/app/src/embedded_web/native_windows.rs added +60 −0
@@ -0,0 +1,60 @@
1 use std::cell::Cell;
2 use std::rc::Rc;
3
4 use gpui_kit::*;
5 use tokio::sync::mpsc::UnboundedReceiver;
6 use webview::{EmbedBounds, EmbedHandle, EmbedSpec};
7
8 use crate::{notify, task_dialog, theme};
9
10 pub use webview::EmbedEvent as NativeEvent;
11
12 pub fn available() -> bool {
13 task_dialog::host().is_some()
14 }
15
16 #[derive(Clone)]
17 pub struct Native {
18 handle: EmbedHandle,
19 placed: Rc<Cell<Option<(EmbedBounds, bool)>>>,
20 }
21
22 impl Native {
23 pub fn open(url: &str, window: &Window) -> Option<(Native, UnboundedReceiver<NativeEvent>)> {
24 let host = task_dialog::host()?;
25 let parent = notify::native_handle(window)?;
26 let (handle, events) = host.open_embed(EmbedSpec {
27 parent,
28 url: url.to_owned(),
29 background: theme::BACKGROUND,
30 });
31 let native = Native {
32 handle,
33 placed: Rc::new(Cell::new(None)),
34 };
35 Some((native, events))
36 }
37
38 pub fn place(&self, bounds: Bounds<Pixels>, scale: f32, visible: bool) {
39 let physical = |value: Pixels| (f32::from(value) * scale).round() as i32;
40 let placement = (
41 EmbedBounds {
42 x: physical(bounds.origin.x),
43 y: physical(bounds.origin.y),
44 width: physical(bounds.size.width),
45 height: physical(bounds.size.height),
46 },
47 visible,
48 );
49 if self.placed.get() == Some(placement) {
50 return;
51 }
52 self.placed.set(Some(placement));
53 self.handle.set_bounds(placement.0);
54 self.handle.set_visible(placement.1);
55 }
56
57 pub fn close(&self) {
58 self.handle.close();
59 }
60 }
@@ -0,0 +1,60 @@
1use std::cell::Cell;
2use std::rc::Rc;
3
4use gpui_kit::*;
5use tokio::sync::mpsc::UnboundedReceiver;
6use webview::{EmbedBounds, EmbedHandle, EmbedSpec};
7
8use crate::{notify, task_dialog, theme};
9
10pub use webview::EmbedEvent as NativeEvent;
11
12pub fn available() -> bool {
13 task_dialog::host().is_some()
14}
15
16#[derive(Clone)]
17pub struct Native {
18 handle: EmbedHandle,
19 placed: Rc<Cell<Option<(EmbedBounds, bool)>>>,
20}
21
22impl Native {
23 pub fn open(url: &str, window: &Window) -> Option<(Native, UnboundedReceiver<NativeEvent>)> {
24 let host = task_dialog::host()?;
25 let parent = notify::native_handle(window)?;
26 let (handle, events) = host.open_embed(EmbedSpec {
27 parent,
28 url: url.to_owned(),
29 background: theme::BACKGROUND,
30 });
31 let native = Native {
32 handle,
33 placed: Rc::new(Cell::new(None)),
34 };
35 Some((native, events))
36 }
37
38 pub fn place(&self, bounds: Bounds<Pixels>, scale: f32, visible: bool) {
39 let physical = |value: Pixels| (f32::from(value) * scale).round() as i32;
40 let placement = (
41 EmbedBounds {
42 x: physical(bounds.origin.x),
43 y: physical(bounds.origin.y),
44 width: physical(bounds.size.width),
45 height: physical(bounds.size.height),
46 },
47 visible,
48 );
49 if self.placed.get() == Some(placement) {
50 return;
51 }
52 self.placed.set(Some(placement));
53 self.handle.set_bounds(placement.0);
54 self.handle.set_visible(placement.1);
55 }
56
57 pub fn close(&self) {
58 self.handle.close();
59 }
60}
crates/app/src/main.rs +3 −0
@@ -14,14 +14,17 @@ mod chat_actions;
14 14 mod crash_log;
15 15 mod card_refresh;
16 16 mod card_state;
17 mod channel_files;
17 18 mod data;
18 19 mod demo;
19 20 mod demo_cards;
20 21 mod demo_chart_cards;
21 22 mod demo_gifs;
22 23 mod demo_input_cards;
24 mod demo_library;
23 25 mod demo_profiles;
24 26 mod downloads;
27 mod embedded_web;
25 28 mod emoji;
26 29 mod format;
27 30 mod frame_log;
@@ -14,14 +14,17 @@ mod chat_actions;
14mod crash_log;
14mod crash_log;
15mod card_refresh;
15mod card_refresh;
16mod card_state;
16mod card_state;
17mod channel_files;
17mod data;
18mod data;
18mod demo;
19mod demo;
19mod demo_cards;
20mod demo_cards;
20mod demo_chart_cards;
21mod demo_chart_cards;
21mod demo_gifs;
22mod demo_gifs;
22mod demo_input_cards;
23mod demo_input_cards;
24mod demo_library;
23mod demo_profiles;
25mod demo_profiles;
24mod downloads;
26mod downloads;
27mod embedded_web;
25mod emoji;
28mod emoji;
26mod format;
29mod format;
27mod frame_log;
30mod frame_log;
crates/app/src/notify/center.rs +1 −1
@@ -199,7 +199,6 @@ impl NotificationCenter {
199 199 let found = self.tracker.collect(
200 200 &state.store,
201 201 &state.sidebar,
202 &state.followed_channels,
203 202 my_user_id.as_deref(),
204 203 conversation_id,
205 204 );
@@ -975,6 +974,7 @@ mod tests {
975 974 }],
976 975 hidden: false,
977 976 hidden_channel_ids: Vec::new(),
977 notifications: Default::default(),
978 978 }],
979 979 }
980 980 }
@@ -199,7 +199,6 @@ impl NotificationCenter {
199 let found = self.tracker.collect(
199 let found = self.tracker.collect(
200 &state.store,
200 &state.store,
201 &state.sidebar,
201 &state.sidebar,
202 &state.followed_channels,
203 my_user_id.as_deref(),
202 my_user_id.as_deref(),
204 conversation_id,
203 conversation_id,
205 );
204 );
@@ -975,6 +974,7 @@ mod tests {
975 }],
974 }],
976 hidden: false,
975 hidden: false,
977 hidden_channel_ids: Vec::new(),
976 hidden_channel_ids: Vec::new(),
977 notifications: Default::default(),
978 }],
978 }],
979 }
979 }
980 }
980 }
crates/app/src/notify/followed.rs deleted +0 −50
@@ -1,50 +0,0 @@
1 use std::collections::HashSet;
2
3 use store::Store;
4
5 const META_KEY: &str = "notifications.followed_channels";
6
7 pub fn load(store: &Store) -> HashSet<String> {
8 store
9 .meta(META_KEY)
10 .ok()
11 .flatten()
12 .map(|text| parse(&text))
13 .unwrap_or_default()
14 }
15
16 pub fn save(store: &Store, channel_ids: &HashSet<String>) {
17 let _ = store.set_meta(META_KEY, &serialize(channel_ids));
18 }
19
20 fn serialize(channel_ids: &HashSet<String>) -> String {
21 let mut ids: Vec<&str> = channel_ids.iter().map(String::as_str).collect();
22 ids.sort_unstable();
23 ids.join("\n")
24 }
25
26 fn parse(text: &str) -> HashSet<String> {
27 text.lines()
28 .filter(|id| !id.is_empty())
29 .map(str::to_owned)
30 .collect()
31 }
32
33 #[cfg(test)]
34 mod tests {
35 use super::*;
36
37 #[test]
38 fn persists_in_store() {
39 let store = Store::open_in_memory().unwrap();
40 assert!(load(&store).is_empty());
41 let followed: HashSet<String> = ["19:a@thread.tacv2", "19:b@thread.tacv2"]
42 .into_iter()
43 .map(str::to_owned)
44 .collect();
45 save(&store, &followed);
46 assert_eq!(load(&store), followed);
47 save(&store, &HashSet::new());
48 assert!(load(&store).is_empty());
49 }
50 }
@@ -1,50 +0,0 @@
1use std::collections::HashSet;
2
3use store::Store;
4
5const META_KEY: &str = "notifications.followed_channels";
6
7pub fn load(store: &Store) -> HashSet<String> {
8 store
9 .meta(META_KEY)
10 .ok()
11 .flatten()
12 .map(|text| parse(&text))
13 .unwrap_or_default()
14}
15
16pub fn save(store: &Store, channel_ids: &HashSet<String>) {
17 let _ = store.set_meta(META_KEY, &serialize(channel_ids));
18}
19
20fn serialize(channel_ids: &HashSet<String>) -> String {
21 let mut ids: Vec<&str> = channel_ids.iter().map(String::as_str).collect();
22 ids.sort_unstable();
23 ids.join("\n")
24}
25
26fn parse(text: &str) -> HashSet<String> {
27 text.lines()
28 .filter(|id| !id.is_empty())
29 .map(str::to_owned)
30 .collect()
31}
32
33#[cfg(test)]
34mod tests {
35 use super::*;
36
37 #[test]
38 fn persists_in_store() {
39 let store = Store::open_in_memory().unwrap();
40 assert!(load(&store).is_empty());
41 let followed: HashSet<String> = ["19:a@thread.tacv2", "19:b@thread.tacv2"]
42 .into_iter()
43 .map(str::to_owned)
44 .collect();
45 save(&store, &followed);
46 assert_eq!(load(&store), followed);
47 save(&store, &HashSet::new());
48 assert!(load(&store).is_empty());
49 }
50}
crates/app/src/notify/incoming.rs +70 −42
@@ -1,7 +1,7 @@
1 use std::collections::{HashMap, HashSet};
1 use std::collections::HashMap;
2 2
3 3 use chrono::{DateTime, Utc};
4 use store::{MessageRecord, Sidebar, Store};
4 use store::{ChannelNotifications, MessageRecord, Sidebar, Store};
5 5
6 6 use super::rules::{ChannelSignals, ChatKind, Incoming, Preview};
7 7 use crate::app_state::chat_title;
@@ -26,14 +26,13 @@ impl IncomingTracker {
26 26 &mut self,
27 27 store: &Store,
28 28 sidebar: &Sidebar,
29 followed: &HashSet<String>,
30 29 my_user_id: Option<&str>,
31 30 conversation_id: &str,
32 31 ) -> Vec<Incoming> {
33 32 let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {
34 33 return Vec::new();
35 34 };
36 self.fresh(records, store, sidebar, followed, my_user_id)
35 self.fresh(records, store, sidebar, my_user_id)
37 36 }
38 37
39 38 fn fresh(
@@ -41,7 +40,6 @@ impl IncomingTracker {
41 40 records: Vec<MessageRecord>,
42 41 store: &Store,
43 42 sidebar: &Sidebar,
44 followed: &HashSet<String>,
45 43 my_user_id: Option<&str>,
46 44 ) -> Vec<Incoming> {
47 45 let mut incoming = Vec::new();
@@ -60,7 +58,7 @@ impl IncomingTracker {
60 58 if record.deleted || is_own(&record, my_user_id) {
61 59 continue;
62 60 }
63 if let Some(entry) = build_incoming(&record, store, sidebar, followed, my_user_id) {
61 if let Some(entry) = build_incoming(&record, store, sidebar, my_user_id) {
64 62 incoming.push(entry);
65 63 }
66 64 }
@@ -76,12 +74,11 @@ pub fn build_incoming(
76 74 record: &MessageRecord,
77 75 store: &Store,
78 76 sidebar: &Sidebar,
79 followed: &HashSet<String>,
80 77 my_user_id: Option<&str>,
81 78 ) -> Option<Incoming> {
82 79 let (kind, chat_name) = chat_context(sidebar, &record.conversation_id)?;
83 80 let signals = match kind {
84 ChatKind::Channel { .. } => channel_signals(record, store, sidebar, followed, my_user_id),
81 ChatKind::Channel { .. } => channel_signals(record, store, sidebar, my_user_id),
85 82 _ => ChannelSignals::default(),
86 83 };
87 84 Some(Incoming {
@@ -137,7 +134,6 @@ fn channel_signals(
137 134 record: &MessageRecord,
138 135 store: &Store,
139 136 sidebar: &Sidebar,
140 followed: &HashSet<String>,
141 137 my_user_id: Option<&str>,
142 138 ) -> ChannelSignals {
143 139 let in_my_thread = match (record.reply_to_id.as_deref(), my_user_id) {
@@ -152,10 +148,24 @@ fn channel_signals(
152 148 .any(|mention| mention.group),
153 149 in_my_thread,
154 150 hidden: channel_hidden(sidebar, &record.conversation_id),
155 followed: followed.contains(&record.conversation_id),
151 is_reply: record.reply_to_id.is_some(),
152 notifications: channel_notifications(sidebar, &record.conversation_id),
156 153 }
157 154 }
158 155
156 fn channel_notifications(sidebar: &Sidebar, conversation_id: &str) -> ChannelNotifications {
157 sidebar
158 .teams
159 .iter()
160 .find(|team| {
161 team.channels
162 .iter()
163 .any(|channel| channel.id == conversation_id)
164 })
165 .map(|team| team.channel_notifications(conversation_id))
166 .unwrap_or_default()
167 }
168
159 169 fn channel_hidden(sidebar: &Sidebar, conversation_id: &str) -> bool {
160 170 sidebar.teams.iter().any(|team| {
161 171 team.channels
@@ -194,7 +204,9 @@ pub fn preview_of(record: &MessageRecord) -> Preview {
194 204 #[cfg(test)]
195 205 mod tests {
196 206 use chrono::Duration;
197 use store::{ChannelRecord, ChatRecord, MemberRecord, SidebarTeam, TeamRecord};
207 use store::{
208 ChannelNotificationLevel, ChannelRecord, ChatRecord, MemberRecord, SidebarTeam, TeamRecord,
209 };
198 210
199 211 use super::*;
200 212
@@ -255,12 +267,12 @@ mod tests {
255 267 .iter()
256 268 .map(|id| (*id).to_owned())
257 269 .collect(),
270 notifications: HashMap::new(),
258 271 }
259 272 }
260 273
261 fn collect_one(message: MessageRecord, store: &Store, followed: &[&str]) -> Incoming {
262 let followed: HashSet<String> = followed.iter().map(|id| (*id).to_owned()).collect();
263 build_incoming(&message, store, &sidebar(), &followed, Some("me")).unwrap()
274 fn collect_one(message: MessageRecord, store: &Store) -> Incoming {
275 build_incoming(&message, store, &sidebar(), Some("me")).unwrap()
264 276 }
265 277
266 278 fn record(conversation: &str, sender: &str, at: DateTime<Utc>, html: &str) -> MessageRecord {
@@ -289,9 +301,8 @@ mod tests {
289 301 quiet.chats[1].muted = true;
290 302 let message = record("group", "u1", Utc::now(), "hi");
291 303 let store = Store::open_in_memory().unwrap();
292 let build = |sidebar: &Sidebar| {
293 build_incoming(&message, &store, sidebar, &HashSet::new(), Some("me")).unwrap()
294 };
304 let build =
305 |sidebar: &Sidebar| build_incoming(&message, &store, sidebar, Some("me")).unwrap();
295 306 assert!(build(&quiet).muted);
296 307 assert!(!build(&sidebar()).muted);
297 308 }
@@ -306,7 +317,6 @@ mod tests {
306 317 vec![old, new],
307 318 &Store::open_in_memory().unwrap(),
308 319 &sidebar(),
309 &HashSet::new(),
310 320 Some("me"),
311 321 );
312 322 assert_eq!(found.len(), 1);
@@ -319,12 +329,12 @@ mod tests {
319 329 let mut tracker = IncomingTracker::new(start);
320 330 let message = record("direct", "u1", start + Duration::seconds(5), "neu");
321 331 let store = Store::open_in_memory().unwrap();
322 let (sidebar, followed) = (sidebar(), HashSet::new());
323 let first = tracker.fresh(vec![message.clone()], &store, &sidebar, &followed, None);
332 let sidebar = sidebar();
333 let first = tracker.fresh(vec![message.clone()], &store, &sidebar, None);
324 334 assert_eq!(first.len(), 1);
325 335 assert!(
326 336 tracker
327 .fresh(vec![message], &store, &sidebar, &followed, None)
337 .fresh(vec![message], &store, &sidebar, None)
328 338 .is_empty()
329 339 );
330 340 }
@@ -335,7 +345,7 @@ mod tests {
335 345 let mut tracker = IncomingTracker::new(start);
336 346 let own = record("direct", "me", start + Duration::seconds(5), "ich");
337 347 let store = Store::open_in_memory().unwrap();
338 let found = tracker.fresh(vec![own], &store, &sidebar(), &HashSet::new(), Some("me"));
348 let found = tracker.fresh(vec![own], &store, &sidebar(), Some("me"));
339 349 assert!(found.is_empty());
340 350 }
341 351
@@ -349,14 +359,13 @@ mod tests {
349 359 "<at>Me</at> hi",
350 360 );
351 361 message.mentions_json = r#"[{"user_id":"me","name":"Me"}]"#.into();
352 let found = collect_one(message.clone(), &Store::open_in_memory().unwrap(), &[]);
362 let found = collect_one(message.clone(), &Store::open_in_memory().unwrap());
353 363 assert!(found.mentions_me);
354 364 assert_eq!(found.kind, ChatKind::Group { member_count: 5 });
355 365 let other = build_incoming(
356 366 &message,
357 367 &Store::open_in_memory().unwrap(),
358 368 &sidebar(),
359 &HashSet::new(),
360 369 Some("other"),
361 370 );
362 371 assert!(!other.unwrap().mentions_me);
@@ -370,7 +379,6 @@ mod tests {
370 379 &message,
371 380 &Store::open_in_memory().unwrap(),
372 381 &sidebar(),
373 &HashSet::new(),
374 382 None
375 383 )
376 384 .is_none()
@@ -384,7 +392,6 @@ mod tests {
384 392 &message,
385 393 &Store::open_in_memory().unwrap(),
386 394 &sidebar(),
387 &HashSet::new(),
388 395 None,
389 396 )
390 397 .unwrap();
@@ -398,12 +405,12 @@ mod tests {
398 405 message.mentions_json =
399 406 r#"[{"user_id":null,"name":"channel","target_id":"channel-open","group":true}]"#.into();
400 407 assert!(
401 collect_one(message.clone(), &store, &[])
408 collect_one(message.clone(), &store)
402 409 .signals
403 410 .mentions_channel
404 411 );
405 412 message.mentions_json = r#"[{"user_id":null,"name":"bot","target_id":"bot-1"}]"#.into();
406 assert!(!collect_one(message, &store, &[]).signals.mentions_channel);
413 assert!(!collect_one(message, &store).signals.mentions_channel);
407 414 }
408 415
409 416 #[test]
@@ -415,32 +422,53 @@ mod tests {
415 422 store.upsert_messages(&[root]).unwrap();
416 423 let mut reply = record("channel-open", "u1", start + Duration::seconds(1), "reply");
417 424 reply.reply_to_id = Some("root".into());
418 assert!(collect_one(reply.clone(), &store, &[]).signals.in_my_thread);
425 assert!(collect_one(reply.clone(), &store).signals.in_my_thread);
419 426 reply.reply_to_id = Some("unknown-root".into());
420 assert!(!collect_one(reply, &store, &[]).signals.in_my_thread);
427 assert!(!collect_one(reply, &store).signals.in_my_thread);
421 428 let top_level = record("channel-open", "u1", start, "post");
422 assert!(!collect_one(top_level, &store, &[]).signals.in_my_thread);
429 assert!(!collect_one(top_level, &store).signals.in_my_thread);
423 430 }
424 431
425 432 #[test]
426 fn followed_and_hidden_channels_are_flagged() {
433 fn hidden_channels_are_flagged() {
427 434 let store = Store::open_in_memory().unwrap();
428 let now = Utc::now();
429 let signals = |channel: &str, followed: &[&str]| {
430 collect_one(record(channel, "u1", now, "x"), &store, followed).signals
435 let signals =
436 |channel: &str| collect_one(record(channel, "u1", Utc::now(), "x"), &store).signals;
437 assert!(!signals("channel-open").hidden);
438 assert!(signals("channel-in-hidden-team").hidden);
439 assert!(signals("channel-hidden").hidden);
440 assert!(!signals("channel-shown").hidden);
441 }
442
443 #[test]
444 fn channel_notifications_and_reply_flag_come_from_the_sidebar() {
445 let store = Store::open_in_memory().unwrap();
446 let banner = ChannelNotifications {
447 level: ChannelNotificationLevel::BannerAndFeed,
448 include_replies: true,
431 449 };
432 assert!(signals("channel-open", &["channel-open"]).followed);
433 assert!(!signals("channel-open", &[]).followed);
434 assert!(!signals("channel-open", &[]).hidden);
435 assert!(signals("channel-in-hidden-team", &[]).hidden);
436 assert!(signals("channel-hidden", &[]).hidden);
437 assert!(!signals("channel-shown", &[]).hidden);
450 let mut configured = sidebar();
451 configured.teams[0]
452 .notifications
453 .insert("channel-open".into(), banner);
454 let mut reply = record("channel-open", "u1", Utc::now(), "x");
455 let build = |message: &MessageRecord| {
456 build_incoming(message, &store, &configured, Some("me"))
457 .unwrap()
458 .signals
459 };
460 assert_eq!(build(&reply).notifications, banner);
461 assert!(!build(&reply).is_reply);
462 reply.reply_to_id = Some("root".into());
463 assert!(build(&reply).is_reply);
464 let other = record("channel-shown", "u1", Utc::now(), "x");
465 assert_eq!(build(&other).notifications, ChannelNotifications::default());
438 466 }
439 467
440 468 #[test]
441 469 fn chats_carry_no_channel_signals() {
442 470 let store = Store::open_in_memory().unwrap();
443 let found = collect_one(record("group", "u1", Utc::now(), "x"), &store, &["group"]);
471 let found = collect_one(record("group", "u1", Utc::now(), "x"), &store);
444 472 assert_eq!(found.signals, ChannelSignals::default());
445 473 }
446 474 }
@@ -1,7 +1,7 @@
1use std::collections::{HashMap, HashSet};
1use std::collections::HashMap;
2
2
3use chrono::{DateTime, Utc};
3use chrono::{DateTime, Utc};
4use store::{MessageRecord, Sidebar, Store};
4use store::{ChannelNotifications, MessageRecord, Sidebar, Store};
5
5
6use super::rules::{ChannelSignals, ChatKind, Incoming, Preview};
6use super::rules::{ChannelSignals, ChatKind, Incoming, Preview};
7use crate::app_state::chat_title;
7use crate::app_state::chat_title;
@@ -26,14 +26,13 @@ impl IncomingTracker {
26 &mut self,
26 &mut self,
27 store: &Store,
27 store: &Store,
28 sidebar: &Sidebar,
28 sidebar: &Sidebar,
29 followed: &HashSet<String>,
30 my_user_id: Option<&str>,
29 my_user_id: Option<&str>,
31 conversation_id: &str,
30 conversation_id: &str,
32 ) -> Vec<Incoming> {
31 ) -> Vec<Incoming> {
33 let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {
32 let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {
34 return Vec::new();
33 return Vec::new();
35 };
34 };
36 self.fresh(records, store, sidebar, followed, my_user_id)
35 self.fresh(records, store, sidebar, my_user_id)
37 }
36 }
38
37
39 fn fresh(
38 fn fresh(
@@ -41,7 +40,6 @@ impl IncomingTracker {
41 records: Vec<MessageRecord>,
40 records: Vec<MessageRecord>,
42 store: &Store,
41 store: &Store,
43 sidebar: &Sidebar,
42 sidebar: &Sidebar,
44 followed: &HashSet<String>,
45 my_user_id: Option<&str>,
43 my_user_id: Option<&str>,
46 ) -> Vec<Incoming> {
44 ) -> Vec<Incoming> {
47 let mut incoming = Vec::new();
45 let mut incoming = Vec::new();
@@ -60,7 +58,7 @@ impl IncomingTracker {
60 if record.deleted || is_own(&record, my_user_id) {
58 if record.deleted || is_own(&record, my_user_id) {
61 continue;
59 continue;
62 }
60 }
63 if let Some(entry) = build_incoming(&record, store, sidebar, followed, my_user_id) {
61 if let Some(entry) = build_incoming(&record, store, sidebar, my_user_id) {
64 incoming.push(entry);
62 incoming.push(entry);
65 }
63 }
66 }
64 }
@@ -76,12 +74,11 @@ pub fn build_incoming(
76 record: &MessageRecord,
74 record: &MessageRecord,
77 store: &Store,
75 store: &Store,
78 sidebar: &Sidebar,
76 sidebar: &Sidebar,
79 followed: &HashSet<String>,
80 my_user_id: Option<&str>,
77 my_user_id: Option<&str>,
81) -> Option<Incoming> {
78) -> Option<Incoming> {
82 let (kind, chat_name) = chat_context(sidebar, &record.conversation_id)?;
79 let (kind, chat_name) = chat_context(sidebar, &record.conversation_id)?;
83 let signals = match kind {
80 let signals = match kind {
84 ChatKind::Channel { .. } => channel_signals(record, store, sidebar, followed, my_user_id),
81 ChatKind::Channel { .. } => channel_signals(record, store, sidebar, my_user_id),
85 _ => ChannelSignals::default(),
82 _ => ChannelSignals::default(),
86 };
83 };
87 Some(Incoming {
84 Some(Incoming {
@@ -137,7 +134,6 @@ fn channel_signals(
137 record: &MessageRecord,
134 record: &MessageRecord,
138 store: &Store,
135 store: &Store,
139 sidebar: &Sidebar,
136 sidebar: &Sidebar,
140 followed: &HashSet<String>,
141 my_user_id: Option<&str>,
137 my_user_id: Option<&str>,
142) -> ChannelSignals {
138) -> ChannelSignals {
143 let in_my_thread = match (record.reply_to_id.as_deref(), my_user_id) {
139 let in_my_thread = match (record.reply_to_id.as_deref(), my_user_id) {
@@ -152,10 +148,24 @@ fn channel_signals(
152 .any(|mention| mention.group),
148 .any(|mention| mention.group),
153 in_my_thread,
149 in_my_thread,
154 hidden: channel_hidden(sidebar, &record.conversation_id),
150 hidden: channel_hidden(sidebar, &record.conversation_id),
155 followed: followed.contains(&record.conversation_id),
151 is_reply: record.reply_to_id.is_some(),
152 notifications: channel_notifications(sidebar, &record.conversation_id),
156 }
153 }
157}
154}
158
155
156fn channel_notifications(sidebar: &Sidebar, conversation_id: &str) -> ChannelNotifications {
157 sidebar
158 .teams
159 .iter()
160 .find(|team| {
161 team.channels
162 .iter()
163 .any(|channel| channel.id == conversation_id)
164 })
165 .map(|team| team.channel_notifications(conversation_id))
166 .unwrap_or_default()
167}
168
159fn channel_hidden(sidebar: &Sidebar, conversation_id: &str) -> bool {
169fn channel_hidden(sidebar: &Sidebar, conversation_id: &str) -> bool {
160 sidebar.teams.iter().any(|team| {
170 sidebar.teams.iter().any(|team| {
161 team.channels
171 team.channels
@@ -194,7 +204,9 @@ pub fn preview_of(record: &MessageRecord) -> Preview {
194#[cfg(test)]
204#[cfg(test)]
195mod tests {
205mod tests {
196 use chrono::Duration;
206 use chrono::Duration;
197 use store::{ChannelRecord, ChatRecord, MemberRecord, SidebarTeam, TeamRecord};
207 use store::{
208 ChannelNotificationLevel, ChannelRecord, ChatRecord, MemberRecord, SidebarTeam, TeamRecord,
209 };
198
210
199 use super::*;
211 use super::*;
200
212
@@ -255,12 +267,12 @@ mod tests {
255 .iter()
267 .iter()
256 .map(|id| (*id).to_owned())
268 .map(|id| (*id).to_owned())
257 .collect(),
269 .collect(),
270 notifications: HashMap::new(),
258 }
271 }
259 }
272 }
260
273
261 fn collect_one(message: MessageRecord, store: &Store, followed: &[&str]) -> Incoming {
274 fn collect_one(message: MessageRecord, store: &Store) -> Incoming {
262 let followed: HashSet<String> = followed.iter().map(|id| (*id).to_owned()).collect();
275 build_incoming(&message, store, &sidebar(), Some("me")).unwrap()
263 build_incoming(&message, store, &sidebar(), &followed, Some("me")).unwrap()
264 }
276 }
265
277
266 fn record(conversation: &str, sender: &str, at: DateTime<Utc>, html: &str) -> MessageRecord {
278 fn record(conversation: &str, sender: &str, at: DateTime<Utc>, html: &str) -> MessageRecord {
@@ -289,9 +301,8 @@ mod tests {
289 quiet.chats[1].muted = true;
301 quiet.chats[1].muted = true;
290 let message = record("group", "u1", Utc::now(), "hi");
302 let message = record("group", "u1", Utc::now(), "hi");
291 let store = Store::open_in_memory().unwrap();
303 let store = Store::open_in_memory().unwrap();
292 let build = |sidebar: &Sidebar| {
304 let build =
293 build_incoming(&message, &store, sidebar, &HashSet::new(), Some("me")).unwrap()
305 |sidebar: &Sidebar| build_incoming(&message, &store, sidebar, Some("me")).unwrap();
294 };
295 assert!(build(&quiet).muted);
306 assert!(build(&quiet).muted);
296 assert!(!build(&sidebar()).muted);
307 assert!(!build(&sidebar()).muted);
297 }
308 }
@@ -306,7 +317,6 @@ mod tests {
306 vec![old, new],
317 vec![old, new],
307 &Store::open_in_memory().unwrap(),
318 &Store::open_in_memory().unwrap(),
308 &sidebar(),
319 &sidebar(),
309 &HashSet::new(),
310 Some("me"),
320 Some("me"),
311 );
321 );
312 assert_eq!(found.len(), 1);
322 assert_eq!(found.len(), 1);
@@ -319,12 +329,12 @@ mod tests {
319 let mut tracker = IncomingTracker::new(start);
329 let mut tracker = IncomingTracker::new(start);
320 let message = record("direct", "u1", start + Duration::seconds(5), "neu");
330 let message = record("direct", "u1", start + Duration::seconds(5), "neu");
321 let store = Store::open_in_memory().unwrap();
331 let store = Store::open_in_memory().unwrap();
322 let (sidebar, followed) = (sidebar(), HashSet::new());
332 let sidebar = sidebar();
323 let first = tracker.fresh(vec![message.clone()], &store, &sidebar, &followed, None);
333 let first = tracker.fresh(vec![message.clone()], &store, &sidebar, None);
324 assert_eq!(first.len(), 1);
334 assert_eq!(first.len(), 1);
325 assert!(
335 assert!(
326 tracker
336 tracker
327 .fresh(vec![message], &store, &sidebar, &followed, None)
337 .fresh(vec![message], &store, &sidebar, None)
328 .is_empty()
338 .is_empty()
329 );
339 );
330 }
340 }
@@ -335,7 +345,7 @@ mod tests {
335 let mut tracker = IncomingTracker::new(start);
345 let mut tracker = IncomingTracker::new(start);
336 let own = record("direct", "me", start + Duration::seconds(5), "ich");
346 let own = record("direct", "me", start + Duration::seconds(5), "ich");
337 let store = Store::open_in_memory().unwrap();
347 let store = Store::open_in_memory().unwrap();
338 let found = tracker.fresh(vec![own], &store, &sidebar(), &HashSet::new(), Some("me"));
348 let found = tracker.fresh(vec![own], &store, &sidebar(), Some("me"));
339 assert!(found.is_empty());
349 assert!(found.is_empty());
340 }
350 }
341
351
@@ -349,14 +359,13 @@ mod tests {
349 "<at>Me</at> hi",
359 "<at>Me</at> hi",
350 );
360 );
351 message.mentions_json = r#"[{"user_id":"me","name":"Me"}]"#.into();
361 message.mentions_json = r#"[{"user_id":"me","name":"Me"}]"#.into();
352 let found = collect_one(message.clone(), &Store::open_in_memory().unwrap(), &[]);
362 let found = collect_one(message.clone(), &Store::open_in_memory().unwrap());
353 assert!(found.mentions_me);
363 assert!(found.mentions_me);
354 assert_eq!(found.kind, ChatKind::Group { member_count: 5 });
364 assert_eq!(found.kind, ChatKind::Group { member_count: 5 });
355 let other = build_incoming(
365 let other = build_incoming(
356 &message,
366 &message,
357 &Store::open_in_memory().unwrap(),
367 &Store::open_in_memory().unwrap(),
358 &sidebar(),
368 &sidebar(),
359 &HashSet::new(),
360 Some("other"),
369 Some("other"),
361 );
370 );
362 assert!(!other.unwrap().mentions_me);
371 assert!(!other.unwrap().mentions_me);
@@ -370,7 +379,6 @@ mod tests {
370 &message,
379 &message,
371 &Store::open_in_memory().unwrap(),
380 &Store::open_in_memory().unwrap(),
372 &sidebar(),
381 &sidebar(),
373 &HashSet::new(),
374 None
382 None
375 )
383 )
376 .is_none()
384 .is_none()
@@ -384,7 +392,6 @@ mod tests {
384 &message,
392 &message,
385 &Store::open_in_memory().unwrap(),
393 &Store::open_in_memory().unwrap(),
386 &sidebar(),
394 &sidebar(),
387 &HashSet::new(),
388 None,
395 None,
389 )
396 )
390 .unwrap();
397 .unwrap();
@@ -398,12 +405,12 @@ mod tests {
398 message.mentions_json =
405 message.mentions_json =
399 r#"[{"user_id":null,"name":"channel","target_id":"channel-open","group":true}]"#.into();
406 r#"[{"user_id":null,"name":"channel","target_id":"channel-open","group":true}]"#.into();
400 assert!(
407 assert!(
401 collect_one(message.clone(), &store, &[])
408 collect_one(message.clone(), &store)
402 .signals
409 .signals
403 .mentions_channel
410 .mentions_channel
404 );
411 );
405 message.mentions_json = r#"[{"user_id":null,"name":"bot","target_id":"bot-1"}]"#.into();
412 message.mentions_json = r#"[{"user_id":null,"name":"bot","target_id":"bot-1"}]"#.into();
406 assert!(!collect_one(message, &store, &[]).signals.mentions_channel);
413 assert!(!collect_one(message, &store).signals.mentions_channel);
407 }
414 }
408
415
409 #[test]
416 #[test]
@@ -415,32 +422,53 @@ mod tests {
415 store.upsert_messages(&[root]).unwrap();
422 store.upsert_messages(&[root]).unwrap();
416 let mut reply = record("channel-open", "u1", start + Duration::seconds(1), "reply");
423 let mut reply = record("channel-open", "u1", start + Duration::seconds(1), "reply");
417 reply.reply_to_id = Some("root".into());
424 reply.reply_to_id = Some("root".into());
418 assert!(collect_one(reply.clone(), &store, &[]).signals.in_my_thread);
425 assert!(collect_one(reply.clone(), &store).signals.in_my_thread);
419 reply.reply_to_id = Some("unknown-root".into());
426 reply.reply_to_id = Some("unknown-root".into());
420 assert!(!collect_one(reply, &store, &[]).signals.in_my_thread);
427 assert!(!collect_one(reply, &store).signals.in_my_thread);
421 let top_level = record("channel-open", "u1", start, "post");
428 let top_level = record("channel-open", "u1", start, "post");
422 assert!(!collect_one(top_level, &store, &[]).signals.in_my_thread);
429 assert!(!collect_one(top_level, &store).signals.in_my_thread);
423 }
430 }
424
431
425 #[test]
432 #[test]
426 fn followed_and_hidden_channels_are_flagged() {
433 fn hidden_channels_are_flagged() {
427 let store = Store::open_in_memory().unwrap();
434 let store = Store::open_in_memory().unwrap();
428 let now = Utc::now();
435 let signals =
429 let signals = |channel: &str, followed: &[&str]| {
436 |channel: &str| collect_one(record(channel, "u1", Utc::now(), "x"), &store).signals;
430 collect_one(record(channel, "u1", now, "x"), &store, followed).signals
437 assert!(!signals("channel-open").hidden);
438 assert!(signals("channel-in-hidden-team").hidden);
439 assert!(signals("channel-hidden").hidden);
440 assert!(!signals("channel-shown").hidden);
441 }
442
443 #[test]
444 fn channel_notifications_and_reply_flag_come_from_the_sidebar() {
445 let store = Store::open_in_memory().unwrap();
446 let banner = ChannelNotifications {
447 level: ChannelNotificationLevel::BannerAndFeed,
448 include_replies: true,
431 };
449 };
432 assert!(signals("channel-open", &["channel-open"]).followed);
450 let mut configured = sidebar();
433 assert!(!signals("channel-open", &[]).followed);
451 configured.teams[0]
434 assert!(!signals("channel-open", &[]).hidden);
452 .notifications
435 assert!(signals("channel-in-hidden-team", &[]).hidden);
453 .insert("channel-open".into(), banner);
436 assert!(signals("channel-hidden", &[]).hidden);
454 let mut reply = record("channel-open", "u1", Utc::now(), "x");
437 assert!(!signals("channel-shown", &[]).hidden);
455 let build = |message: &MessageRecord| {
456 build_incoming(message, &store, &configured, Some("me"))
457 .unwrap()
458 .signals
459 };
460 assert_eq!(build(&reply).notifications, banner);
461 assert!(!build(&reply).is_reply);
462 reply.reply_to_id = Some("root".into());
463 assert!(build(&reply).is_reply);
464 let other = record("channel-shown", "u1", Utc::now(), "x");
465 assert_eq!(build(&other).notifications, ChannelNotifications::default());
438 }
466 }
439
467
440 #[test]
468 #[test]
441 fn chats_carry_no_channel_signals() {
469 fn chats_carry_no_channel_signals() {
442 let store = Store::open_in_memory().unwrap();
470 let store = Store::open_in_memory().unwrap();
443 let found = collect_one(record("group", "u1", Utc::now(), "x"), &store, &["group"]);
471 let found = collect_one(record("group", "u1", Utc::now(), "x"), &store);
444 assert_eq!(found.signals, ChannelSignals::default());
472 assert_eq!(found.signals, ChannelSignals::default());
445 }
473 }
446}
474}
crates/app/src/notify/mod.rs +0 −2
@@ -1,7 +1,6 @@
1 1 #[cfg_attr(not(windows), allow(dead_code))]
2 2 mod badge;
3 3 mod center;
4 mod followed;
5 4 mod incoming;
6 5 mod layout;
7 6 #[cfg_attr(not(windows), allow(dead_code))]
@@ -14,7 +13,6 @@ mod text;
14 13 mod toast;
15 14
16 15 pub use center::{NotificationCenter, selection_for};
17 pub use followed::{load as load_followed_channels, save as save_followed_channels};
18 16 pub use incoming::{IncomingTracker, preview_of};
19 17 pub use rules::{Incoming, Preview, channel_alerts};
20 18 #[cfg(test)]
@@ -1,7 +1,6 @@
1#[cfg_attr(not(windows), allow(dead_code))]
1#[cfg_attr(not(windows), allow(dead_code))]
2mod badge;
2mod badge;
3mod center;
3mod center;
4mod followed;
5mod incoming;
4mod incoming;
6mod layout;
5mod layout;
7#[cfg_attr(not(windows), allow(dead_code))]
6#[cfg_attr(not(windows), allow(dead_code))]
@@ -14,7 +13,6 @@ mod text;
14mod toast;
13mod toast;
15
14
16pub use center::{NotificationCenter, selection_for};
15pub use center::{NotificationCenter, selection_for};
17pub use followed::{load as load_followed_channels, save as save_followed_channels};
18pub use incoming::{IncomingTracker, preview_of};
16pub use incoming::{IncomingTracker, preview_of};
19pub use rules::{Incoming, Preview, channel_alerts};
17pub use rules::{Incoming, Preview, channel_alerts};
20#[cfg(test)]
18#[cfg(test)]
crates/app/src/notify/rules.rs +96 −14
@@ -2,6 +2,7 @@ use std::collections::HashMap;
2 2 use std::time::{Duration, Instant};
3 3
4 4 use chrono::{DateTime, Utc};
5 use store::{ChannelNotificationLevel, ChannelNotifications};
5 6
6 7 pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);
7 8
@@ -104,7 +105,8 @@ pub struct ChannelSignals {
104 105 pub mentions_channel: bool,
105 106 pub in_my_thread: bool,
106 107 pub hidden: bool,
107 pub followed: bool,
108 pub is_reply: bool,
109 pub notifications: ChannelNotifications,
108 110 }
109 111
110 112 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -147,7 +149,25 @@ pub fn channel_alerts(incoming: &Incoming) -> bool {
147 149 return true;
148 150 }
149 151 let signals = incoming.signals;
150 !signals.hidden && (signals.mentions_channel || signals.in_my_thread || signals.followed)
152 if signals.hidden {
153 return false;
154 }
155 if signals.mentions_channel || signals.in_my_thread {
156 return true;
157 }
158 let notifications = signals.notifications;
159 notifications.level != ChannelNotificationLevel::Off
160 && (!signals.is_reply || notifications.include_replies)
161 }
162
163 fn channel_toasts(incoming: &Incoming) -> bool {
164 if !matches!(incoming.kind, ChatKind::Channel { .. }) || incoming.mentions_me {
165 return true;
166 }
167 let signals = incoming.signals;
168 signals.mentions_channel
169 || signals.in_my_thread
170 || signals.notifications.level == ChannelNotificationLevel::BannerAndFeed
151 171 }
152 172
153 173 const SILENT: Decision = Decision {
@@ -157,6 +177,7 @@ const SILENT: Decision = Decision {
157 177
158 178 pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
159 179 let suppressed = !channel_alerts(incoming)
180 || !channel_toasts(incoming)
160 181 || environment.chat_in_foreground
161 182 || environment.system_quiet
162 183 || environment.own_do_not_disturb
@@ -302,43 +323,104 @@ mod tests {
302 323 ..Default::default()
303 324 };
304 325 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
305 assert!(decide(&settings, &incoming(ChatKind::Direct), Environment::default()).toast);
326 assert!(
327 decide(
328 &settings,
329 &incoming(ChatKind::Direct),
330 Environment::default()
331 )
332 .toast
333 );
306 334 let mut mention = group();
307 335 mention.mentions_me = true;
308 336 assert!(decide(&settings, &mention, Environment::default()).toast);
309 337 }
310 338
339 fn channel_with(level: ChannelNotificationLevel, include_replies: bool) -> Incoming {
340 let mut message = channel();
341 message.signals.notifications = ChannelNotifications {
342 level,
343 include_replies,
344 };
345 message
346 }
347
348 fn toast_of(incoming: &Incoming) -> bool {
349 decide(&Settings::default(), incoming, Environment::default()).toast
350 }
351
311 352 #[test]
312 fn plain_channel_post_is_silent() {
313 assert!(!channel_alerts(&channel()));
353 fn banner_and_activity_posts_toast_and_feed() {
354 let post = channel_with(ChannelNotificationLevel::BannerAndFeed, false);
355 assert!(channel_alerts(&post));
356 assert!(toast_of(&post));
357 }
358
359 #[test]
360 fn activity_only_posts_feed_without_a_toast() {
361 let post = channel_with(ChannelNotificationLevel::Feed, false);
362 assert!(channel_alerts(&post));
314 363 assert_eq!(
315 decide(&Settings::default(), &channel(), Environment::default()),
364 decide(&Settings::default(), &post, Environment::default()),
316 365 SILENT
317 366 );
367 assert!(channel_alerts(&channel()));
318 368 }
319 369
320 370 #[test]
321 fn channel_alerts_for_each_trigger() {
322 let triggers: [fn(&mut Incoming); 4] = [
371 fn off_channel_stays_silent_except_for_mentions_and_my_threads() {
372 let mut post = channel_with(ChannelNotificationLevel::Off, true);
373 assert!(!channel_alerts(&post));
374 assert_eq!(
375 decide(&Settings::default(), &post, Environment::default()),
376 SILENT
377 );
378 post.signals.is_reply = true;
379 assert!(!channel_alerts(&post));
380 let triggers: [fn(&mut Incoming); 3] = [
323 381 |incoming| incoming.mentions_me = true,
324 382 |incoming| incoming.signals.mentions_channel = true,
325 383 |incoming| incoming.signals.in_my_thread = true,
326 |incoming| incoming.signals.followed = true,
327 384 ];
328 385 for trigger in triggers {
329 let mut message = channel();
330 trigger(&mut message);
331 assert!(channel_alerts(&message));
332 assert!(decide(&Settings::default(), &message, Environment::default()).toast);
386 let mut mention = channel_with(ChannelNotificationLevel::Off, false);
387 trigger(&mut mention);
388 assert!(channel_alerts(&mention));
389 assert!(toast_of(&mention));
333 390 }
334 391 }
335 392
393 #[test]
394 fn replies_need_include_replies_or_my_thread() {
395 for level in [
396 ChannelNotificationLevel::Feed,
397 ChannelNotificationLevel::BannerAndFeed,
398 ] {
399 let mut reply = channel_with(level, false);
400 reply.signals.is_reply = true;
401 assert!(!channel_alerts(&reply));
402 reply.signals.in_my_thread = true;
403 assert!(channel_alerts(&reply));
404 let mut included = channel_with(level, true);
405 included.signals.is_reply = true;
406 assert!(channel_alerts(&included));
407 }
408 let mut banner_reply = channel_with(ChannelNotificationLevel::BannerAndFeed, true);
409 banner_reply.signals.is_reply = true;
410 assert!(toast_of(&banner_reply));
411 let mut feed_reply = channel_with(ChannelNotificationLevel::Feed, true);
412 feed_reply.signals.is_reply = true;
413 assert!(!toast_of(&feed_reply));
414 }
415
336 416 #[test]
337 417 fn hidden_channel_only_alerts_for_mentions_of_me() {
338 418 let triggers: [fn(&mut Incoming); 3] = [
339 419 |incoming| incoming.signals.mentions_channel = true,
340 420 |incoming| incoming.signals.in_my_thread = true,
341 |incoming| incoming.signals.followed = true,
421 |incoming| {
422 incoming.signals.notifications.level = ChannelNotificationLevel::BannerAndFeed
423 },
342 424 ];
343 425 for trigger in triggers {
344 426 let mut message = channel();
@@ -2,6 +2,7 @@ use std::collections::HashMap;
2use std::time::{Duration, Instant};
2use std::time::{Duration, Instant};
3
3
4use chrono::{DateTime, Utc};
4use chrono::{DateTime, Utc};
5use store::{ChannelNotificationLevel, ChannelNotifications};
5
6
6pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);
7pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);
7
8
@@ -104,7 +105,8 @@ pub struct ChannelSignals {
104 pub mentions_channel: bool,
105 pub mentions_channel: bool,
105 pub in_my_thread: bool,
106 pub in_my_thread: bool,
106 pub hidden: bool,
107 pub hidden: bool,
107 pub followed: bool,
108 pub is_reply: bool,
109 pub notifications: ChannelNotifications,
108}
110}
109
111
110#[derive(Debug, Clone, PartialEq, Eq)]
112#[derive(Debug, Clone, PartialEq, Eq)]
@@ -147,7 +149,25 @@ pub fn channel_alerts(incoming: &Incoming) -> bool {
147 return true;
149 return true;
148 }
150 }
149 let signals = incoming.signals;
151 let signals = incoming.signals;
150 !signals.hidden && (signals.mentions_channel || signals.in_my_thread || signals.followed)
152 if signals.hidden {
153 return false;
154 }
155 if signals.mentions_channel || signals.in_my_thread {
156 return true;
157 }
158 let notifications = signals.notifications;
159 notifications.level != ChannelNotificationLevel::Off
160 && (!signals.is_reply || notifications.include_replies)
161}
162
163fn channel_toasts(incoming: &Incoming) -> bool {
164 if !matches!(incoming.kind, ChatKind::Channel { .. }) || incoming.mentions_me {
165 return true;
166 }
167 let signals = incoming.signals;
168 signals.mentions_channel
169 || signals.in_my_thread
170 || signals.notifications.level == ChannelNotificationLevel::BannerAndFeed
151}
171}
152
172
153const SILENT: Decision = Decision {
173const SILENT: Decision = Decision {
@@ -157,6 +177,7 @@ const SILENT: Decision = Decision {
157
177
158pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
178pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
159 let suppressed = !channel_alerts(incoming)
179 let suppressed = !channel_alerts(incoming)
180 || !channel_toasts(incoming)
160 || environment.chat_in_foreground
181 || environment.chat_in_foreground
161 || environment.system_quiet
182 || environment.system_quiet
162 || environment.own_do_not_disturb
183 || environment.own_do_not_disturb
@@ -302,43 +323,104 @@ mod tests {
302 ..Default::default()
323 ..Default::default()
303 };
324 };
304 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
325 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
305 assert!(decide(&settings, &incoming(ChatKind::Direct), Environment::default()).toast);
326 assert!(
327 decide(
328 &settings,
329 &incoming(ChatKind::Direct),
330 Environment::default()
331 )
332 .toast
333 );
306 let mut mention = group();
334 let mut mention = group();
307 mention.mentions_me = true;
335 mention.mentions_me = true;
308 assert!(decide(&settings, &mention, Environment::default()).toast);
336 assert!(decide(&settings, &mention, Environment::default()).toast);
309 }
337 }
310
338
339 fn channel_with(level: ChannelNotificationLevel, include_replies: bool) -> Incoming {
340 let mut message = channel();
341 message.signals.notifications = ChannelNotifications {
342 level,
343 include_replies,
344 };
345 message
346 }
347
348 fn toast_of(incoming: &Incoming) -> bool {
349 decide(&Settings::default(), incoming, Environment::default()).toast
350 }
351
311 #[test]
352 #[test]
312 fn plain_channel_post_is_silent() {
353 fn banner_and_activity_posts_toast_and_feed() {
313 assert!(!channel_alerts(&channel()));
354 let post = channel_with(ChannelNotificationLevel::BannerAndFeed, false);
355 assert!(channel_alerts(&post));
356 assert!(toast_of(&post));
357 }
358
359 #[test]
360 fn activity_only_posts_feed_without_a_toast() {
361 let post = channel_with(ChannelNotificationLevel::Feed, false);
362 assert!(channel_alerts(&post));
314 assert_eq!(
363 assert_eq!(
315 decide(&Settings::default(), &channel(), Environment::default()),
364 decide(&Settings::default(), &post, Environment::default()),
316 SILENT
365 SILENT
317 );
366 );
367 assert!(channel_alerts(&channel()));
318 }
368 }
319
369
320 #[test]
370 #[test]
321 fn channel_alerts_for_each_trigger() {
371 fn off_channel_stays_silent_except_for_mentions_and_my_threads() {
322 let triggers: [fn(&mut Incoming); 4] = [
372 let mut post = channel_with(ChannelNotificationLevel::Off, true);
373 assert!(!channel_alerts(&post));
374 assert_eq!(
375 decide(&Settings::default(), &post, Environment::default()),
376 SILENT
377 );
378 post.signals.is_reply = true;
379 assert!(!channel_alerts(&post));
380 let triggers: [fn(&mut Incoming); 3] = [
323 |incoming| incoming.mentions_me = true,
381 |incoming| incoming.mentions_me = true,
324 |incoming| incoming.signals.mentions_channel = true,
382 |incoming| incoming.signals.mentions_channel = true,
325 |incoming| incoming.signals.in_my_thread = true,
383 |incoming| incoming.signals.in_my_thread = true,
326 |incoming| incoming.signals.followed = true,
327 ];
384 ];
328 for trigger in triggers {
385 for trigger in triggers {
329 let mut message = channel();
386 let mut mention = channel_with(ChannelNotificationLevel::Off, false);
330 trigger(&mut message);
387 trigger(&mut mention);
331 assert!(channel_alerts(&message));
388 assert!(channel_alerts(&mention));
332 assert!(decide(&Settings::default(), &message, Environment::default()).toast);
389 assert!(toast_of(&mention));
333 }
390 }
334 }
391 }
335
392
393 #[test]
394 fn replies_need_include_replies_or_my_thread() {
395 for level in [
396 ChannelNotificationLevel::Feed,
397 ChannelNotificationLevel::BannerAndFeed,
398 ] {
399 let mut reply = channel_with(level, false);
400 reply.signals.is_reply = true;
401 assert!(!channel_alerts(&reply));
402 reply.signals.in_my_thread = true;
403 assert!(channel_alerts(&reply));
404 let mut included = channel_with(level, true);
405 included.signals.is_reply = true;
406 assert!(channel_alerts(&included));
407 }
408 let mut banner_reply = channel_with(ChannelNotificationLevel::BannerAndFeed, true);
409 banner_reply.signals.is_reply = true;
410 assert!(toast_of(&banner_reply));
411 let mut feed_reply = channel_with(ChannelNotificationLevel::Feed, true);
412 feed_reply.signals.is_reply = true;
413 assert!(!toast_of(&feed_reply));
414 }
415
336 #[test]
416 #[test]
337 fn hidden_channel_only_alerts_for_mentions_of_me() {
417 fn hidden_channel_only_alerts_for_mentions_of_me() {
338 let triggers: [fn(&mut Incoming); 3] = [
418 let triggers: [fn(&mut Incoming); 3] = [
339 |incoming| incoming.signals.mentions_channel = true,
419 |incoming| incoming.signals.mentions_channel = true,
340 |incoming| incoming.signals.in_my_thread = true,
420 |incoming| incoming.signals.in_my_thread = true,
341 |incoming| incoming.signals.followed = true,
421 |incoming| {
422 incoming.signals.notifications.level = ChannelNotificationLevel::BannerAndFeed
423 },
342 ];
424 ];
343 for trigger in triggers {
425 for trigger in triggers {
344 let mut message = channel();
426 let mut message = channel();
crates/app/src/task_dialog.rs +1 −1
@@ -11,7 +11,7 @@ mod hosted;
11 11 mod sdk;
12 12
13 13 #[cfg(windows)]
14 pub use hosted::install_host;
14 pub use hosted::{host, install_host};
15 15
16 16 #[cfg_attr(not(windows), allow(dead_code))]
17 17 #[derive(Debug, Clone, PartialEq)]
@@ -11,7 +11,7 @@ mod hosted;
11mod sdk;
11mod sdk;
12
12
13#[cfg(windows)]
13#[cfg(windows)]
14pub use hosted::install_host;
14pub use hosted::{host, install_host};
15
15
16#[cfg_attr(not(windows), allow(dead_code))]
16#[cfg_attr(not(windows), allow(dead_code))]
17#[derive(Debug, Clone, PartialEq)]
17#[derive(Debug, Clone, PartialEq)]
crates/app/src/task_dialog/hosted.rs +4 −0
@@ -17,6 +17,10 @@ pub fn install_host(transport: Arc<WebViewTransport>) {
17 17 let _ = HOST.set(transport);
18 18 }
19 19
20 pub fn host() -> Option<Arc<WebViewTransport>> {
21 HOST.get().cloned()
22 }
23
20 24 pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {
21 25 let Some(host) = HOST.get().cloned() else {
22 26 cx.open_url(&dialog.fallback_url);
@@ -17,6 +17,10 @@ pub fn install_host(transport: Arc<WebViewTransport>) {
17 let _ = HOST.set(transport);
17 let _ = HOST.set(transport);
18}
18}
19
19
20pub fn host() -> Option<Arc<WebViewTransport>> {
21 HOST.get().cloned()
22}
23
20pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {
24pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {
21 let Some(host) = HOST.get().cloned() else {
25 let Some(host) = HOST.get().cloned() else {
22 cx.open_url(&dialog.fallback_url);
26 cx.open_url(&dialog.fallback_url);
crates/app/src/views/attachment_tray.rs +1 −1
@@ -616,7 +616,7 @@ impl AttachmentTray {
616 616 }
617 617 }
618 618
619 fn display_name(path: &Path) -> String {
619 pub fn display_name(path: &Path) -> String {
620 620 path.file_name()
621 621 .map(|name| name.to_string_lossy().into_owned())
622 622 .unwrap_or_else(|| path.to_string_lossy().into_owned())
@@ -616,7 +616,7 @@ impl AttachmentTray {
616 }
616 }
617}
617}
618
618
619fn display_name(path: &Path) -> String {
619pub fn display_name(path: &Path) -> String {
620 path.file_name()
620 path.file_name()
621 .map(|name| name.to_string_lossy().into_owned())
621 .map(|name| name.to_string_lossy().into_owned())
622 .unwrap_or_else(|| path.to_string_lossy().into_owned())
622 .unwrap_or_else(|| path.to_string_lossy().into_owned())
crates/app/src/views/channel_tabs.rs added +299 −0
@@ -0,0 +1,299 @@
1 use std::rc::Rc;
2
3 use gpui_kit::component::{
4 button::{Button, ButtonVariants as _},
5 h_flex,
6 menu::{DropdownMenu as _, PopupMenuItem},
7 };
8 use gpui_kit::prelude::FluentBuilder as _;
9 use gpui_kit::*;
10 use store::ChannelTabRecord;
11 use teams_core::channel_tab_link;
12
13 use crate::theme;
14
15 const TAB_HEIGHT: f32 = 34.;
16 const TAB_GAP: f32 = 14.;
17 const TAB_TEXT_SIZE: f32 = 12.5;
18 const BAR_PADDING: f32 = 20.;
19 const CHAR_WIDTH: f32 = 6.5;
20 const ARROW_WIDTH: f32 = 14.;
21 const OVERFLOW_WIDTH: f32 = 44.;
22 const EXTERNAL_ARROW: &str = "\u{2197}";
23
24 pub const POSTS_LABEL: &str = "Posts";
25 pub const SHARED_LABEL: &str = "Shared";
26
27 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
28 pub enum ChannelPane {
29 Posts,
30 Shared,
31 Web,
32 }
33
34 pub type SelectPane = Rc<dyn Fn(ChannelPane, &mut App)>;
35 pub type OpenTab = Rc<dyn Fn(usize, &mut Window, &mut App)>;
36 pub type MenuToggled = Rc<dyn Fn(bool, &mut Window, &mut App)>;
37
38 #[derive(Clone)]
39 pub struct TabBarActions {
40 pub select: SelectPane,
41 pub open: OpenTab,
42 pub menu_toggled: MenuToggled,
43 }
44
45 #[derive(Debug, Clone, PartialEq, Eq)]
46 pub enum TabAction {
47 Embed(String),
48 Browser(String),
49 ResolveLink,
50 }
51
52 pub fn tab_action(
53 tab: &ChannelTabRecord,
54 embedding: bool,
55 resolved_link: Option<&str>,
56 ) -> TabAction {
57 match (&tab.open_url, resolved_link) {
58 (Some(url), _) if embedding && tab.is_website() => TabAction::Embed(url.clone()),
59 (Some(url), _) => TabAction::Browser(url.clone()),
60 (None, Some(link)) => TabAction::Browser(link.to_owned()),
61 (None, None) => TabAction::ResolveLink,
62 }
63 }
64
65 pub fn fallback_tab_link(tab: &ChannelTabRecord, channel_id: &str) -> String {
66 channel_tab_link(channel_id, &tab.tab_id, &tab.name)
67 }
68
69 fn label_width(label: &str, external: bool) -> f32 {
70 label.chars().count() as f32 * CHAR_WIDTH + if external { ARROW_WIDTH } else { 0. }
71 }
72
73 pub fn visible_tab_count(tabs: &[ChannelTabRecord], available_width: f32) -> usize {
74 let fixed = label_width(POSTS_LABEL, false) + TAB_GAP + label_width(SHARED_LABEL, false);
75 let widths: Vec<f32> = tabs
76 .iter()
77 .map(|tab| TAB_GAP + label_width(&tab.name, true))
78 .collect();
79 if fixed + widths.iter().sum::<f32>() <= available_width {
80 return tabs.len();
81 }
82 let room = available_width - fixed - TAB_GAP - OVERFLOW_WIDTH;
83 let mut used = 0.;
84 widths
85 .iter()
86 .take_while(|width| {
87 used += **width;
88 used <= room
89 })
90 .count()
91 }
92
93 fn tab_label(
94 id: ElementId,
95 text: &str,
96 active: bool,
97 external: bool,
98 on_click: impl Fn(&mut Window, &mut App) + 'static,
99 ) -> Stateful<Div> {
100 let color = if active {
101 theme::text()
102 } else {
103 theme::text_muted()
104 };
105 h_flex()
106 .id(id)
107 .h(px(TAB_HEIGHT))
108 .flex_none()
109 .items_center()
110 .gap(px(3.))
111 .cursor_pointer()
112 .border_b_2()
113 .border_color(if active {
114 theme::accent()
115 } else {
116 transparent_black()
117 })
118 .text_size(px(TAB_TEXT_SIZE))
119 .font_weight(if active {
120 FontWeight::SEMIBOLD
121 } else {
122 FontWeight::NORMAL
123 })
124 .text_color(color)
125 .hover(|tab| tab.text_color(theme::text()))
126 .on_click(move |_, window, cx| on_click(window, cx))
127 .child(text.to_owned())
128 .when(external, |tab| {
129 tab.child(div().text_color(theme::text_faint()).child(EXTERNAL_ARROW))
130 })
131 }
132
133 fn overflow_button(
134 hidden: &[(usize, String, bool)],
135 embedding: bool,
136 actions: &TabBarActions,
137 ) -> impl IntoElement {
138 let entries = hidden.to_vec();
139 let open = actions.open.clone();
140 let menu_toggled = actions.menu_toggled.clone();
141 Button::new("channel-tab-overflow")
142 .ghost()
143 .compact()
144 .label(format!("+{}", hidden.len()))
145 .dropdown_menu(move |menu, _, _| {
146 entries.iter().fold(menu, |menu, (index, name, website)| {
147 let (open, index) = (open.clone(), *index);
148 let label = if embedding && *website {
149 name.clone()
150 } else {
151 format!("{name} {EXTERNAL_ARROW}")
152 };
153 menu.item(
154 PopupMenuItem::new(label)
155 .on_click(move |_, window, cx| open(index, window, cx)),
156 )
157 })
158 })
159 .on_open_change(move |open, window, cx| menu_toggled(*open, window, cx))
160 }
161
162 pub fn render_tab_bar(
163 tabs: &[ChannelTabRecord],
164 pane: ChannelPane,
165 active_tab_id: Option<&str>,
166 embedding: bool,
167 available_width: f32,
168 actions: &TabBarActions,
169 ) -> AnyElement {
170 let visible = visible_tab_count(tabs, available_width - 2. * BAR_PADDING);
171 let select = actions.select.clone();
172 let posts = tab_label(
173 "channel-tab-posts".into(),
174 POSTS_LABEL,
175 pane == ChannelPane::Posts,
176 false,
177 {
178 let select = select.clone();
179 move |_, cx| select(ChannelPane::Posts, cx)
180 },
181 );
182 let shared = tab_label(
183 "channel-tab-shared".into(),
184 SHARED_LABEL,
185 pane == ChannelPane::Shared,
186 false,
187 move |_, cx| select(ChannelPane::Shared, cx),
188 );
189 let configured = tabs.iter().enumerate().take(visible).map(|(index, tab)| {
190 let open = actions.open.clone();
191 tab_label(
192 ElementId::NamedInteger("channel-tab".into(), index as u64),
193 &tab.name,
194 active_tab_id == Some(tab.tab_id.as_str()),
195 !(embedding && tab.is_website()),
196 move |window, cx| open(index, window, cx),
197 )
198 });
199 let hidden: Vec<(usize, String, bool)> = tabs
200 .iter()
201 .enumerate()
202 .skip(visible)
203 .map(|(index, tab)| (index, tab.name.clone(), tab.is_website()))
204 .collect();
205 h_flex()
206 .w_full()
207 .flex_none()
208 .px(px(BAR_PADDING))
209 .gap(px(TAB_GAP))
210 .items_center()
211 .border_b_1()
212 .border_color(theme::border())
213 .child(posts)
214 .child(shared)
215 .children(configured)
216 .when(!hidden.is_empty(), |bar| {
217 bar.child(overflow_button(&hidden, embedding, actions))
218 })
219 .into_any_element()
220 }
221
222 #[cfg(test)]
223 mod tests {
224 use store::ChannelTabRecord;
225
226 use super::{TabAction, fallback_tab_link, tab_action, visible_tab_count};
227
228 fn tab(name: &str, open_url: Option<&str>) -> ChannelTabRecord {
229 ChannelTabRecord {
230 tab_id: "tab-1".to_owned(),
231 name: name.to_owned(),
232 definition_id: "app".to_owned(),
233 open_url: open_url.map(str::to_owned),
234 }
235 }
236
237 fn website(url: &str) -> ChannelTabRecord {
238 ChannelTabRecord {
239 definition_id: "com.microsoft.teamspace.tab.web".to_owned(),
240 ..tab("Docs", Some(url))
241 }
242 }
243
244 #[test]
245 fn website_tabs_embed_only_where_the_host_can() {
246 let docs = website("https://docs.example");
247 assert_eq!(
248 tab_action(&docs, true, None),
249 TabAction::Embed("https://docs.example".to_owned())
250 );
251 assert_eq!(
252 tab_action(&docs, false, None),
253 TabAction::Browser("https://docs.example".to_owned())
254 );
255 }
256
257 #[test]
258 fn other_tabs_with_a_page_open_it_in_the_browser() {
259 let notes = tab("Notes", Some("https://onenote.example/web"));
260 assert_eq!(
261 tab_action(&notes, true, None),
262 TabAction::Browser("https://onenote.example/web".to_owned())
263 );
264 }
265
266 #[test]
267 fn app_tabs_resolve_their_link_once_and_then_reuse_it() {
268 let board = tab("Board", None);
269 assert_eq!(tab_action(&board, true, None), TabAction::ResolveLink);
270 assert_eq!(
271 tab_action(&board, true, Some("https://teams.example/l/tab")),
272 TabAction::Browser("https://teams.example/l/tab".to_owned())
273 );
274 }
275
276 #[test]
277 fn the_fallback_link_is_the_hand_built_deep_link() {
278 assert_eq!(
279 fallback_tab_link(&tab("Board", None), "19:c@thread.tacv2"),
280 "https://teams.microsoft.com/l/channel/19:c@thread.tacv2/tab%3A%3Atab-1?label=Board"
281 );
282 }
283
284 #[test]
285 fn every_tab_stays_visible_while_it_fits() {
286 let tabs = [tab("Docs", None), tab("Planner", None)];
287 assert_eq!(visible_tab_count(&tabs, 600.), 2);
288 }
289
290 #[test]
291 fn tabs_that_do_not_fit_move_into_the_overflow() {
292 let tabs: Vec<ChannelTabRecord> = (0..8)
293 .map(|n| tab(&format!("Tab number {n}"), None))
294 .collect();
295 let visible = visible_tab_count(&tabs, 420.);
296 assert!(visible > 0 && visible < tabs.len());
297 assert_eq!(visible_tab_count(&tabs, 40.), 0);
298 }
299 }
@@ -0,0 +1,299 @@
1use std::rc::Rc;
2
3use gpui_kit::component::{
4 button::{Button, ButtonVariants as _},
5 h_flex,
6 menu::{DropdownMenu as _, PopupMenuItem},
7};
8use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::*;
10use store::ChannelTabRecord;
11use teams_core::channel_tab_link;
12
13use crate::theme;
14
15const TAB_HEIGHT: f32 = 34.;
16const TAB_GAP: f32 = 14.;
17const TAB_TEXT_SIZE: f32 = 12.5;
18const BAR_PADDING: f32 = 20.;
19const CHAR_WIDTH: f32 = 6.5;
20const ARROW_WIDTH: f32 = 14.;
21const OVERFLOW_WIDTH: f32 = 44.;
22const EXTERNAL_ARROW: &str = "\u{2197}";
23
24pub const POSTS_LABEL: &str = "Posts";
25pub const SHARED_LABEL: &str = "Shared";
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum ChannelPane {
29 Posts,
30 Shared,
31 Web,
32}
33
34pub type SelectPane = Rc<dyn Fn(ChannelPane, &mut App)>;
35pub type OpenTab = Rc<dyn Fn(usize, &mut Window, &mut App)>;
36pub type MenuToggled = Rc<dyn Fn(bool, &mut Window, &mut App)>;
37
38#[derive(Clone)]
39pub struct TabBarActions {
40 pub select: SelectPane,
41 pub open: OpenTab,
42 pub menu_toggled: MenuToggled,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum TabAction {
47 Embed(String),
48 Browser(String),
49 ResolveLink,
50}
51
52pub fn tab_action(
53 tab: &ChannelTabRecord,
54 embedding: bool,
55 resolved_link: Option<&str>,
56) -> TabAction {
57 match (&tab.open_url, resolved_link) {
58 (Some(url), _) if embedding && tab.is_website() => TabAction::Embed(url.clone()),
59 (Some(url), _) => TabAction::Browser(url.clone()),
60 (None, Some(link)) => TabAction::Browser(link.to_owned()),
61 (None, None) => TabAction::ResolveLink,
62 }
63}
64
65pub fn fallback_tab_link(tab: &ChannelTabRecord, channel_id: &str) -> String {
66 channel_tab_link(channel_id, &tab.tab_id, &tab.name)
67}
68
69fn label_width(label: &str, external: bool) -> f32 {
70 label.chars().count() as f32 * CHAR_WIDTH + if external { ARROW_WIDTH } else { 0. }
71}
72
73pub fn visible_tab_count(tabs: &[ChannelTabRecord], available_width: f32) -> usize {
74 let fixed = label_width(POSTS_LABEL, false) + TAB_GAP + label_width(SHARED_LABEL, false);
75 let widths: Vec<f32> = tabs
76 .iter()
77 .map(|tab| TAB_GAP + label_width(&tab.name, true))
78 .collect();
79 if fixed + widths.iter().sum::<f32>() <= available_width {
80 return tabs.len();
81 }
82 let room = available_width - fixed - TAB_GAP - OVERFLOW_WIDTH;
83 let mut used = 0.;
84 widths
85 .iter()
86 .take_while(|width| {
87 used += **width;
88 used <= room
89 })
90 .count()
91}
92
93fn tab_label(
94 id: ElementId,
95 text: &str,
96 active: bool,
97 external: bool,
98 on_click: impl Fn(&mut Window, &mut App) + 'static,
99) -> Stateful<Div> {
100 let color = if active {
101 theme::text()
102 } else {
103 theme::text_muted()
104 };
105 h_flex()
106 .id(id)
107 .h(px(TAB_HEIGHT))
108 .flex_none()
109 .items_center()
110 .gap(px(3.))
111 .cursor_pointer()
112 .border_b_2()
113 .border_color(if active {
114 theme::accent()
115 } else {
116 transparent_black()
117 })
118 .text_size(px(TAB_TEXT_SIZE))
119 .font_weight(if active {
120 FontWeight::SEMIBOLD
121 } else {
122 FontWeight::NORMAL
123 })
124 .text_color(color)
125 .hover(|tab| tab.text_color(theme::text()))
126 .on_click(move |_, window, cx| on_click(window, cx))
127 .child(text.to_owned())
128 .when(external, |tab| {
129 tab.child(div().text_color(theme::text_faint()).child(EXTERNAL_ARROW))
130 })
131}
132
133fn overflow_button(
134 hidden: &[(usize, String, bool)],
135 embedding: bool,
136 actions: &TabBarActions,
137) -> impl IntoElement {
138 let entries = hidden.to_vec();
139 let open = actions.open.clone();
140 let menu_toggled = actions.menu_toggled.clone();
141 Button::new("channel-tab-overflow")
142 .ghost()
143 .compact()
144 .label(format!("+{}", hidden.len()))
145 .dropdown_menu(move |menu, _, _| {
146 entries.iter().fold(menu, |menu, (index, name, website)| {
147 let (open, index) = (open.clone(), *index);
148 let label = if embedding && *website {
149 name.clone()
150 } else {
151 format!("{name} {EXTERNAL_ARROW}")
152 };
153 menu.item(
154 PopupMenuItem::new(label)
155 .on_click(move |_, window, cx| open(index, window, cx)),
156 )
157 })
158 })
159 .on_open_change(move |open, window, cx| menu_toggled(*open, window, cx))
160}
161
162pub fn render_tab_bar(
163 tabs: &[ChannelTabRecord],
164 pane: ChannelPane,
165 active_tab_id: Option<&str>,
166 embedding: bool,
167 available_width: f32,
168 actions: &TabBarActions,
169) -> AnyElement {
170 let visible = visible_tab_count(tabs, available_width - 2. * BAR_PADDING);
171 let select = actions.select.clone();
172 let posts = tab_label(
173 "channel-tab-posts".into(),
174 POSTS_LABEL,
175 pane == ChannelPane::Posts,
176 false,
177 {
178 let select = select.clone();
179 move |_, cx| select(ChannelPane::Posts, cx)
180 },
181 );
182 let shared = tab_label(
183 "channel-tab-shared".into(),
184 SHARED_LABEL,
185 pane == ChannelPane::Shared,
186 false,
187 move |_, cx| select(ChannelPane::Shared, cx),
188 );
189 let configured = tabs.iter().enumerate().take(visible).map(|(index, tab)| {
190 let open = actions.open.clone();
191 tab_label(
192 ElementId::NamedInteger("channel-tab".into(), index as u64),
193 &tab.name,
194 active_tab_id == Some(tab.tab_id.as_str()),
195 !(embedding && tab.is_website()),
196 move |window, cx| open(index, window, cx),
197 )
198 });
199 let hidden: Vec<(usize, String, bool)> = tabs
200 .iter()
201 .enumerate()
202 .skip(visible)
203 .map(|(index, tab)| (index, tab.name.clone(), tab.is_website()))
204 .collect();
205 h_flex()
206 .w_full()
207 .flex_none()
208 .px(px(BAR_PADDING))
209 .gap(px(TAB_GAP))
210 .items_center()
211 .border_b_1()
212 .border_color(theme::border())
213 .child(posts)
214 .child(shared)
215 .children(configured)
216 .when(!hidden.is_empty(), |bar| {
217 bar.child(overflow_button(&hidden, embedding, actions))
218 })
219 .into_any_element()
220}
221
222#[cfg(test)]
223mod tests {
224 use store::ChannelTabRecord;
225
226 use super::{TabAction, fallback_tab_link, tab_action, visible_tab_count};
227
228 fn tab(name: &str, open_url: Option<&str>) -> ChannelTabRecord {
229 ChannelTabRecord {
230 tab_id: "tab-1".to_owned(),
231 name: name.to_owned(),
232 definition_id: "app".to_owned(),
233 open_url: open_url.map(str::to_owned),
234 }
235 }
236
237 fn website(url: &str) -> ChannelTabRecord {
238 ChannelTabRecord {
239 definition_id: "com.microsoft.teamspace.tab.web".to_owned(),
240 ..tab("Docs", Some(url))
241 }
242 }
243
244 #[test]
245 fn website_tabs_embed_only_where_the_host_can() {
246 let docs = website("https://docs.example");
247 assert_eq!(
248 tab_action(&docs, true, None),
249 TabAction::Embed("https://docs.example".to_owned())
250 );
251 assert_eq!(
252 tab_action(&docs, false, None),
253 TabAction::Browser("https://docs.example".to_owned())
254 );
255 }
256
257 #[test]
258 fn other_tabs_with_a_page_open_it_in_the_browser() {
259 let notes = tab("Notes", Some("https://onenote.example/web"));
260 assert_eq!(
261 tab_action(&notes, true, None),
262 TabAction::Browser("https://onenote.example/web".to_owned())
263 );
264 }
265
266 #[test]
267 fn app_tabs_resolve_their_link_once_and_then_reuse_it() {
268 let board = tab("Board", None);
269 assert_eq!(tab_action(&board, true, None), TabAction::ResolveLink);
270 assert_eq!(
271 tab_action(&board, true, Some("https://teams.example/l/tab")),
272 TabAction::Browser("https://teams.example/l/tab".to_owned())
273 );
274 }
275
276 #[test]
277 fn the_fallback_link_is_the_hand_built_deep_link() {
278 assert_eq!(
279 fallback_tab_link(&tab("Board", None), "19:c@thread.tacv2"),
280 "https://teams.microsoft.com/l/channel/19:c@thread.tacv2/tab%3A%3Atab-1?label=Board"
281 );
282 }
283
284 #[test]
285 fn every_tab_stays_visible_while_it_fits() {
286 let tabs = [tab("Docs", None), tab("Planner", None)];
287 assert_eq!(visible_tab_count(&tabs, 600.), 2);
288 }
289
290 #[test]
291 fn tabs_that_do_not_fit_move_into_the_overflow() {
292 let tabs: Vec<ChannelTabRecord> = (0..8)
293 .map(|n| tab(&format!("Tab number {n}"), None))
294 .collect();
295 let visible = visible_tab_count(&tabs, 420.);
296 assert!(visible > 0 && visible < tabs.len());
297 assert_eq!(visible_tab_count(&tabs, 40.), 0);
298 }
299}
crates/app/src/views/conversation.rs +71 −18
@@ -16,30 +16,35 @@ use gpui_kit::component::{
16 16 };
17 17 use gpui_kit::prelude::FluentBuilder as _;
18 18 use gpui_kit::*;
19 use store::{MessageRecord, OutboxState, OutboxTarget};
19 use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget};
20 20 use teams_core::{ExecuteAction, FileCard, LinkPreview};
21 21
22 22 mod feed;
23 23 mod pins;
24 24 mod render_env;
25 25 mod scheduled;
26 mod shared;
26 27
27 28 use super::attachments::FileActions;
28 use super::profile_card::opens_profile;
29 29 use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
30 use super::channel_tabs::ChannelPane;
30 31 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
31 32 use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
32 33 use super::message_row::{render_message_row, render_skeleton_row};
33 34 use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
34 35 use super::post_card::render_post;
36 use super::profile_card::opens_profile;
35 37 use super::reaction_picker::{PickHandler, ReactionPicker};
36 38 use super::reaction_pills::{ReactionControls, ReactionPopover};
37 39 use super::widgets::{icon, symbol};
38 40 use crate::app_state::{AppEvent, AppState, Selection, selection_title};
39 41 use crate::backend::Engine;
40 42 use crate::card_state::CardScope;
43 use crate::channel_files::DownloadSource;
41 44 use crate::data::{is_one_on_one, others};
45 use crate::demo_library::DemoLibrary;
42 46 use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
47 use crate::embedded_web::EmbeddedWeb;
43 48 use crate::emoji;
44 49 use crate::notice::short_error;
45 50 use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
@@ -59,6 +64,7 @@ use crate::theme;
59 64 use crate::typing::typing_tooltip;
60 65 use feed::{FeedStash, subject_input};
61 66 use render_env::RenderEnv;
67 use shared::SharedState;
62 68
63 69 const CHAT_OPEN_LIMIT: usize = 60;
64 70 const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -170,6 +176,14 @@ pub struct ConversationView {
170 176 drag_file_count: usize,
171 177 sync_generation: u64,
172 178 window_active: bool,
179 pane: ChannelPane,
180 channel_tabs: Vec<ChannelTabRecord>,
181 tab_links: HashMap<String, String>,
182 web: Option<Entity<EmbeddedWeb>>,
183 web_subscription: Option<Subscription>,
184 shared: SharedState,
185 demo_library: DemoLibrary,
186 new_folder_input: Option<Entity<InputState>>,
173 187 _subscriptions: Vec<Subscription>,
174 188 }
175 189
@@ -184,6 +198,7 @@ fn open_limit(selection: &Selection) -> usize {
184 198 enum DropTarget {
185 199 Chat,
186 200 Channel,
201 Library,
187 202 NewChat,
188 203 }
189 204
@@ -202,6 +217,10 @@ fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String,
202 217 format!("Drop to attach to {title}"),
203 218 format!("{files}. Images go into the message, other files to the channel's Files."),
204 219 ),
220 DropTarget::Library => (
221 format!("Drop to upload to {title}"),
222 format!("{files}. Files go into the folder you have open."),
223 ),
205 224 DropTarget::NewChat => (
206 225 "Drop to attach to the new chat".to_owned(),
207 226 format!(
@@ -230,20 +249,20 @@ enum DownloadEvent {
230 249 async fn save_file(
231 250 engine: &Engine,
232 251 card: &FileCard,
252 source: &DownloadSource,
233 253 events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,
234 254 ) -> Result<PathBuf, String> {
235 255 let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)
236 256 .map_err(|error| short_error(&error))?;
237 engine
238 .download_file(
239 &card.open_url,
240 |bytes| part.write(bytes),
241 |percent| {
242 let _ = events.send(DownloadEvent::Progress(percent));
243 },
244 )
245 .await
246 .map_err(|error| short_error(&error))?;
257 let write = |bytes: &[u8]| part.write(bytes);
258 let progress = |percent| {
259 let _ = events.send(DownloadEvent::Progress(percent));
260 };
261 match source {
262 DownloadSource::Share => engine.download_file(&card.open_url, write, progress).await,
263 DownloadSource::Library(file) => engine.download_library_file(file, write, progress).await,
264 }
265 .map_err(|error| short_error(&error))?;
247 266 part.finish().map_err(|error| short_error(&error))
248 267 }
249 268
@@ -268,7 +287,7 @@ impl ConversationView {
268 287 let key = key.clone();
269 288 let conversation_id = conversation_id.clone();
270 289 view.update(cx, |this, cx| {
271 this.activate_file(&conversation_id, &key, card, cx)
290 this.activate_file(&conversation_id, &key, card, DownloadSource::Share, cx)
272 291 })
273 292 .ok();
274 293 }),
@@ -280,12 +299,13 @@ impl ConversationView {
280 299 conversation_id: &str,
281 300 message_key: &str,
282 301 card: FileCard,
302 source: DownloadSource,
283 303 cx: &mut Context<Self>,
284 304 ) {
285 305 let key = DownloadKey::new(conversation_id, message_key, &card.open_url);
286 306 match downloads::click_action(self.downloads.state(&key)) {
287 307 ClickAction::Ignore => {}
288 ClickAction::Start => self.start_download(key, card, cx),
308 ClickAction::Start => self.start_download(key, card, source, cx),
289 309 ClickAction::Reveal(path) => {
290 310 let folder = path
291 311 .parent()
@@ -299,7 +319,13 @@ impl ConversationView {
299 319 }
300 320 }
301 321
302 fn start_download(&mut self, key: DownloadKey, card: FileCard, cx: &mut Context<Self>) {
322 fn start_download(
323 &mut self,
324 key: DownloadKey,
325 card: FileCard,
326 source: DownloadSource,
327 cx: &mut Context<Self>,
328 ) {
303 329 if !self.downloads.begin(&key) {
304 330 return;
305 331 }
@@ -336,7 +362,7 @@ impl ConversationView {
336 362 return;
337 363 };
338 364 drop(runtime::spawn(async move {
339 let outcome = save_file(&engine, &card, &sender).await;
365 let outcome = save_file(&engine, &card, &source, &sender).await;
340 366 let _ = sender.send(DownloadEvent::Finished(outcome));
341 367 }));
342 368 cx.spawn(async move |this, cx| {
@@ -420,6 +446,14 @@ impl ConversationView {
420 446 drag_file_count: 0,
421 447 sync_generation: 0,
422 448 window_active: window.is_window_active(),
449 pane: ChannelPane::Posts,
450 channel_tabs: Vec::new(),
451 tab_links: HashMap::new(),
452 web: None,
453 web_subscription: None,
454 shared: SharedState::default(),
455 demo_library: DemoLibrary::default(),
456 new_folder_input: None,
423 457 _subscriptions: subscriptions,
424 458 };
425 459 if let Some(selection) = view.app.read(cx).selection.clone() {
@@ -488,6 +522,9 @@ impl ConversationView {
488 522 .as_ref()
489 523 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
490 524 if is_current {
525 if self.shared_active() {
526 self.refresh_shared_items(cx);
527 }
491 528 self.rebuild(false, cx);
492 529 self.mark_read(ReadTrigger::Incoming, cx);
493 530 self.on_pins_changed(conversation_id, cx);
@@ -529,6 +566,7 @@ impl ConversationView {
529 566 }
530 567 }
531 568 AppEvent::Sidebar => {
569 self.reload_channel_tabs(cx);
532 570 self.mark_read(ReadTrigger::Incoming, cx);
533 571 self.refresh_reactor_names(cx);
534 572 if self.draft_active {
@@ -689,11 +727,11 @@ impl ConversationView {
689 727 sync: SyncProgress::default(),
690 728 });
691 729 self.sync_generation += 1;
730 self.reset_channel_tabs(cx);
692 731 self.reload_pending(cx);
693 732 self.notice = None;
694 733 self.scheduled_failure = None;
695 self.app
696 .update(cx, |state, cx| state.refresh_scheduled(cx));
734 self.app.update(cx, |state, cx| state.refresh_scheduled(cx));
697 735 self.rebuild(true, cx);
698 736 self.start_fetch(cx);
699 737 self.mark_read(ReadTrigger::Open, cx);
@@ -929,6 +967,8 @@ impl ConversationView {
929 967 current.first_unread = None;
930 968 let in_channel = matches!(current.selection, Selection::Channel(_));
931 969 if in_channel {
970 self.pane = ChannelPane::Posts;
971 self.close_web();
932 972 match record.reply_to_id.clone() {
933 973 Some(root_id) => {
934 974 self.enter_thread_mode(root_id.clone(), cx);
@@ -2683,6 +2723,7 @@ impl ConversationView {
2683 2723 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
2684 2724 let target = match self.current.as_ref().map(|current| &current.selection) {
2685 2725 Some(Selection::Chat(_)) => DropTarget::Chat,
2726 Some(Selection::Channel(_)) if self.shared_active() => DropTarget::Library,
2686 2727 Some(Selection::Channel(_)) => DropTarget::Channel,
2687 2728 None => DropTarget::NewChat,
2688 2729 };
@@ -2719,6 +2760,10 @@ impl ConversationView {
2719 2760 )
2720 2761 .on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {
2721 2762 let paths = dropped.paths().to_vec();
2763 if this.shared_active() {
2764 this.upload_paths(paths, cx);
2765 return;
2766 }
2722 2767 this.composer
2723 2768 .update(cx, |composer, cx| composer.add_paths(paths, window, cx));
2724 2769 }))
@@ -2931,6 +2976,9 @@ impl ConversationView {
2931 2976
2932 2977 impl Render for ConversationView {
2933 2978 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2979 if self.web.is_some() && !self.web_active() {
2980 self.close_web();
2981 }
2934 2982 let background = theme::background();
2935 2983 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
2936 2984 let drafting = self.draft_active;
@@ -3031,6 +3079,7 @@ impl Render for ConversationView {
3031 3079 Some(current) => root.child(self.render_header(current, cx)),
3032 3080 None => root.child(self.draft.clone()),
3033 3081 };
3082 root = root.children(self.render_tab_bar(window, cx).filter(|_| !drafting));
3034 3083 root = root.children(self.render_pin_banner(cx).filter(|_| !drafting));
3035 3084 let sync_failed = self
3036 3085 .current
@@ -3064,6 +3113,10 @@ impl Render for ConversationView {
3064 3113 let draft = self.draft.read(cx);
3065 3114 let group_name = draft.group_name(cx);
3066 3115 draft.render_empty(&self.app.read(cx).directory, &group_name)
3116 } else if self.shared_active() {
3117 self.render_shared(cx)
3118 } else if let Some(web) = self.web.clone().filter(|_| self.web_active()) {
3119 web.into_any_element()
3067 3120 } else if empty_channel {
3068 3121 div()
3069 3122 .size_full()
@@ -16,30 +16,35 @@ use gpui_kit::component::{
16};
16};
17use gpui_kit::prelude::FluentBuilder as _;
17use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::*;
18use gpui_kit::*;
19use store::{MessageRecord, OutboxState, OutboxTarget};
19use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget};
20use teams_core::{ExecuteAction, FileCard, LinkPreview};
20use teams_core::{ExecuteAction, FileCard, LinkPreview};
21
21
22mod feed;
22mod feed;
23mod pins;
23mod pins;
24mod render_env;
24mod render_env;
25mod scheduled;
25mod scheduled;
26mod shared;
26
27
27use super::attachments::FileActions;
28use super::attachments::FileActions;
28use super::profile_card::opens_profile;
29use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
29use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
30use super::channel_tabs::ChannelPane;
30use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
31use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
31use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
32use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
32use super::message_row::{render_message_row, render_skeleton_row};
33use super::message_row::{render_message_row, render_skeleton_row};
33use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
34use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
34use super::post_card::render_post;
35use super::post_card::render_post;
36use super::profile_card::opens_profile;
35use super::reaction_picker::{PickHandler, ReactionPicker};
37use super::reaction_picker::{PickHandler, ReactionPicker};
36use super::reaction_pills::{ReactionControls, ReactionPopover};
38use super::reaction_pills::{ReactionControls, ReactionPopover};
37use super::widgets::{icon, symbol};
39use super::widgets::{icon, symbol};
38use crate::app_state::{AppEvent, AppState, Selection, selection_title};
40use crate::app_state::{AppEvent, AppState, Selection, selection_title};
39use crate::backend::Engine;
41use crate::backend::Engine;
40use crate::card_state::CardScope;
42use crate::card_state::CardScope;
43use crate::channel_files::DownloadSource;
41use crate::data::{is_one_on_one, others};
44use crate::data::{is_one_on_one, others};
45use crate::demo_library::DemoLibrary;
42use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
46use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
47use crate::embedded_web::EmbeddedWeb;
43use crate::emoji;
48use crate::emoji;
44use crate::notice::short_error;
49use crate::notice::short_error;
45use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
50use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
@@ -59,6 +64,7 @@ use crate::theme;
59use crate::typing::typing_tooltip;
64use crate::typing::typing_tooltip;
60use feed::{FeedStash, subject_input};
65use feed::{FeedStash, subject_input};
61use render_env::RenderEnv;
66use render_env::RenderEnv;
67use shared::SharedState;
62
68
63const CHAT_OPEN_LIMIT: usize = 60;
69const CHAT_OPEN_LIMIT: usize = 60;
64const CHANNEL_OPEN_LIMIT: usize = 300;
70const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -170,6 +176,14 @@ pub struct ConversationView {
170 drag_file_count: usize,
176 drag_file_count: usize,
171 sync_generation: u64,
177 sync_generation: u64,
172 window_active: bool,
178 window_active: bool,
179 pane: ChannelPane,
180 channel_tabs: Vec<ChannelTabRecord>,
181 tab_links: HashMap<String, String>,
182 web: Option<Entity<EmbeddedWeb>>,
183 web_subscription: Option<Subscription>,
184 shared: SharedState,
185 demo_library: DemoLibrary,
186 new_folder_input: Option<Entity<InputState>>,
173 _subscriptions: Vec<Subscription>,
187 _subscriptions: Vec<Subscription>,
174}
188}
175
189
@@ -184,6 +198,7 @@ fn open_limit(selection: &Selection) -> usize {
184enum DropTarget {
198enum DropTarget {
185 Chat,
199 Chat,
186 Channel,
200 Channel,
201 Library,
187 NewChat,
202 NewChat,
188}
203}
189
204
@@ -202,6 +217,10 @@ fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String,
202 format!("Drop to attach to {title}"),
217 format!("Drop to attach to {title}"),
203 format!("{files}. Images go into the message, other files to the channel's Files."),
218 format!("{files}. Images go into the message, other files to the channel's Files."),
204 ),
219 ),
220 DropTarget::Library => (
221 format!("Drop to upload to {title}"),
222 format!("{files}. Files go into the folder you have open."),
223 ),
205 DropTarget::NewChat => (
224 DropTarget::NewChat => (
206 "Drop to attach to the new chat".to_owned(),
225 "Drop to attach to the new chat".to_owned(),
207 format!(
226 format!(
@@ -230,20 +249,20 @@ enum DownloadEvent {
230async fn save_file(
249async fn save_file(
231 engine: &Engine,
250 engine: &Engine,
232 card: &FileCard,
251 card: &FileCard,
252 source: &DownloadSource,
233 events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,
253 events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,
234) -> Result<PathBuf, String> {
254) -> Result<PathBuf, String> {
235 let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)
255 let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)
236 .map_err(|error| short_error(&error))?;
256 .map_err(|error| short_error(&error))?;
237 engine
257 let write = |bytes: &[u8]| part.write(bytes);
238 .download_file(
258 let progress = |percent| {
239 &card.open_url,
259 let _ = events.send(DownloadEvent::Progress(percent));
240 |bytes| part.write(bytes),
260 };
241 |percent| {
261 match source {
242 let _ = events.send(DownloadEvent::Progress(percent));
262 DownloadSource::Share => engine.download_file(&card.open_url, write, progress).await,
243 },
263 DownloadSource::Library(file) => engine.download_library_file(file, write, progress).await,
244 )
264 }
245 .await
265 .map_err(|error| short_error(&error))?;
246 .map_err(|error| short_error(&error))?;
247 part.finish().map_err(|error| short_error(&error))
266 part.finish().map_err(|error| short_error(&error))
248}
267}
249
268
@@ -268,7 +287,7 @@ impl ConversationView {
268 let key = key.clone();
287 let key = key.clone();
269 let conversation_id = conversation_id.clone();
288 let conversation_id = conversation_id.clone();
270 view.update(cx, |this, cx| {
289 view.update(cx, |this, cx| {
271 this.activate_file(&conversation_id, &key, card, cx)
290 this.activate_file(&conversation_id, &key, card, DownloadSource::Share, cx)
272 })
291 })
273 .ok();
292 .ok();
274 }),
293 }),
@@ -280,12 +299,13 @@ impl ConversationView {
280 conversation_id: &str,
299 conversation_id: &str,
281 message_key: &str,
300 message_key: &str,
282 card: FileCard,
301 card: FileCard,
302 source: DownloadSource,
283 cx: &mut Context<Self>,
303 cx: &mut Context<Self>,
284 ) {
304 ) {
285 let key = DownloadKey::new(conversation_id, message_key, &card.open_url);
305 let key = DownloadKey::new(conversation_id, message_key, &card.open_url);
286 match downloads::click_action(self.downloads.state(&key)) {
306 match downloads::click_action(self.downloads.state(&key)) {
287 ClickAction::Ignore => {}
307 ClickAction::Ignore => {}
288 ClickAction::Start => self.start_download(key, card, cx),
308 ClickAction::Start => self.start_download(key, card, source, cx),
289 ClickAction::Reveal(path) => {
309 ClickAction::Reveal(path) => {
290 let folder = path
310 let folder = path
291 .parent()
311 .parent()
@@ -299,7 +319,13 @@ impl ConversationView {
299 }
319 }
300 }
320 }
301
321
302 fn start_download(&mut self, key: DownloadKey, card: FileCard, cx: &mut Context<Self>) {
322 fn start_download(
323 &mut self,
324 key: DownloadKey,
325 card: FileCard,
326 source: DownloadSource,
327 cx: &mut Context<Self>,
328 ) {
303 if !self.downloads.begin(&key) {
329 if !self.downloads.begin(&key) {
304 return;
330 return;
305 }
331 }
@@ -336,7 +362,7 @@ impl ConversationView {
336 return;
362 return;
337 };
363 };
338 drop(runtime::spawn(async move {
364 drop(runtime::spawn(async move {
339 let outcome = save_file(&engine, &card, &sender).await;
365 let outcome = save_file(&engine, &card, &source, &sender).await;
340 let _ = sender.send(DownloadEvent::Finished(outcome));
366 let _ = sender.send(DownloadEvent::Finished(outcome));
341 }));
367 }));
342 cx.spawn(async move |this, cx| {
368 cx.spawn(async move |this, cx| {
@@ -420,6 +446,14 @@ impl ConversationView {
420 drag_file_count: 0,
446 drag_file_count: 0,
421 sync_generation: 0,
447 sync_generation: 0,
422 window_active: window.is_window_active(),
448 window_active: window.is_window_active(),
449 pane: ChannelPane::Posts,
450 channel_tabs: Vec::new(),
451 tab_links: HashMap::new(),
452 web: None,
453 web_subscription: None,
454 shared: SharedState::default(),
455 demo_library: DemoLibrary::default(),
456 new_folder_input: None,
423 _subscriptions: subscriptions,
457 _subscriptions: subscriptions,
424 };
458 };
425 if let Some(selection) = view.app.read(cx).selection.clone() {
459 if let Some(selection) = view.app.read(cx).selection.clone() {
@@ -488,6 +522,9 @@ impl ConversationView {
488 .as_ref()
522 .as_ref()
489 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
523 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
490 if is_current {
524 if is_current {
525 if self.shared_active() {
526 self.refresh_shared_items(cx);
527 }
491 self.rebuild(false, cx);
528 self.rebuild(false, cx);
492 self.mark_read(ReadTrigger::Incoming, cx);
529 self.mark_read(ReadTrigger::Incoming, cx);
493 self.on_pins_changed(conversation_id, cx);
530 self.on_pins_changed(conversation_id, cx);
@@ -529,6 +566,7 @@ impl ConversationView {
529 }
566 }
530 }
567 }
531 AppEvent::Sidebar => {
568 AppEvent::Sidebar => {
569 self.reload_channel_tabs(cx);
532 self.mark_read(ReadTrigger::Incoming, cx);
570 self.mark_read(ReadTrigger::Incoming, cx);
533 self.refresh_reactor_names(cx);
571 self.refresh_reactor_names(cx);
534 if self.draft_active {
572 if self.draft_active {
@@ -689,11 +727,11 @@ impl ConversationView {
689 sync: SyncProgress::default(),
727 sync: SyncProgress::default(),
690 });
728 });
691 self.sync_generation += 1;
729 self.sync_generation += 1;
730 self.reset_channel_tabs(cx);
692 self.reload_pending(cx);
731 self.reload_pending(cx);
693 self.notice = None;
732 self.notice = None;
694 self.scheduled_failure = None;
733 self.scheduled_failure = None;
695 self.app
734 self.app.update(cx, |state, cx| state.refresh_scheduled(cx));
696 .update(cx, |state, cx| state.refresh_scheduled(cx));
697 self.rebuild(true, cx);
735 self.rebuild(true, cx);
698 self.start_fetch(cx);
736 self.start_fetch(cx);
699 self.mark_read(ReadTrigger::Open, cx);
737 self.mark_read(ReadTrigger::Open, cx);
@@ -929,6 +967,8 @@ impl ConversationView {
929 current.first_unread = None;
967 current.first_unread = None;
930 let in_channel = matches!(current.selection, Selection::Channel(_));
968 let in_channel = matches!(current.selection, Selection::Channel(_));
931 if in_channel {
969 if in_channel {
970 self.pane = ChannelPane::Posts;
971 self.close_web();
932 match record.reply_to_id.clone() {
972 match record.reply_to_id.clone() {
933 Some(root_id) => {
973 Some(root_id) => {
934 self.enter_thread_mode(root_id.clone(), cx);
974 self.enter_thread_mode(root_id.clone(), cx);
@@ -2683,6 +2723,7 @@ impl ConversationView {
2683 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
2723 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
2684 let target = match self.current.as_ref().map(|current| &current.selection) {
2724 let target = match self.current.as_ref().map(|current| &current.selection) {
2685 Some(Selection::Chat(_)) => DropTarget::Chat,
2725 Some(Selection::Chat(_)) => DropTarget::Chat,
2726 Some(Selection::Channel(_)) if self.shared_active() => DropTarget::Library,
2686 Some(Selection::Channel(_)) => DropTarget::Channel,
2727 Some(Selection::Channel(_)) => DropTarget::Channel,
2687 None => DropTarget::NewChat,
2728 None => DropTarget::NewChat,
2688 };
2729 };
@@ -2719,6 +2760,10 @@ impl ConversationView {
2719 )
2760 )
2720 .on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {
2761 .on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {
2721 let paths = dropped.paths().to_vec();
2762 let paths = dropped.paths().to_vec();
2763 if this.shared_active() {
2764 this.upload_paths(paths, cx);
2765 return;
2766 }
2722 this.composer
2767 this.composer
2723 .update(cx, |composer, cx| composer.add_paths(paths, window, cx));
2768 .update(cx, |composer, cx| composer.add_paths(paths, window, cx));
2724 }))
2769 }))
@@ -2931,6 +2976,9 @@ impl ConversationView {
2931
2976
2932impl Render for ConversationView {
2977impl Render for ConversationView {
2933 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2978 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2979 if self.web.is_some() && !self.web_active() {
2980 self.close_web();
2981 }
2934 let background = theme::background();
2982 let background = theme::background();
2935 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
2983 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
2936 let drafting = self.draft_active;
2984 let drafting = self.draft_active;
@@ -3031,6 +3079,7 @@ impl Render for ConversationView {
3031 Some(current) => root.child(self.render_header(current, cx)),
3079 Some(current) => root.child(self.render_header(current, cx)),
3032 None => root.child(self.draft.clone()),
3080 None => root.child(self.draft.clone()),
3033 };
3081 };
3082 root = root.children(self.render_tab_bar(window, cx).filter(|_| !drafting));
3034 root = root.children(self.render_pin_banner(cx).filter(|_| !drafting));
3083 root = root.children(self.render_pin_banner(cx).filter(|_| !drafting));
3035 let sync_failed = self
3084 let sync_failed = self
3036 .current
3085 .current
@@ -3064,6 +3113,10 @@ impl Render for ConversationView {
3064 let draft = self.draft.read(cx);
3113 let draft = self.draft.read(cx);
3065 let group_name = draft.group_name(cx);
3114 let group_name = draft.group_name(cx);
3066 draft.render_empty(&self.app.read(cx).directory, &group_name)
3115 draft.render_empty(&self.app.read(cx).directory, &group_name)
3116 } else if self.shared_active() {
3117 self.render_shared(cx)
3118 } else if let Some(web) = self.web.clone().filter(|_| self.web_active()) {
3119 web.into_any_element()
3067 } else if empty_channel {
3120 } else if empty_channel {
3068 div()
3121 div()
3069 .size_full()
3122 .size_full()
crates/app/src/views/conversation/feed.rs +5 −1
@@ -16,6 +16,7 @@ use crate::notice::short_error;
16 16 use crate::rows::Row;
17 17 use crate::runtime;
18 18 use crate::theme;
19 use crate::views::channel_tabs::ChannelPane;
19 20 use crate::views::composer::{Composer, ComposerEvent, ReplyPreview};
20 21 use crate::views::widgets::icon;
21 22
@@ -214,7 +215,7 @@ impl ConversationView {
214 215 window: &Window,
215 216 cx: &mut Context<Self>,
216 217 ) -> Option<AnyElement> {
217 if !self.in_feed() {
218 if !self.in_feed() || self.pane != ChannelPane::Posts {
218 219 return None;
219 220 }
220 221 if !self.new_post_open {
@@ -314,6 +315,9 @@ impl ConversationView {
314 315 }
315 316
316 317 pub(super) fn on_escape(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
318 if self.close_new_folder(cx) {
319 return true;
320 }
317 321 if self.reply_root.is_some() {
318 322 self.close_reply_editor(cx);
319 323 return true;
@@ -16,6 +16,7 @@ use crate::notice::short_error;
16use crate::rows::Row;
16use crate::rows::Row;
17use crate::runtime;
17use crate::runtime;
18use crate::theme;
18use crate::theme;
19use crate::views::channel_tabs::ChannelPane;
19use crate::views::composer::{Composer, ComposerEvent, ReplyPreview};
20use crate::views::composer::{Composer, ComposerEvent, ReplyPreview};
20use crate::views::widgets::icon;
21use crate::views::widgets::icon;
21
22
@@ -214,7 +215,7 @@ impl ConversationView {
214 window: &Window,
215 window: &Window,
215 cx: &mut Context<Self>,
216 cx: &mut Context<Self>,
216 ) -> Option<AnyElement> {
217 ) -> Option<AnyElement> {
217 if !self.in_feed() {
218 if !self.in_feed() || self.pane != ChannelPane::Posts {
218 return None;
219 return None;
219 }
220 }
220 if !self.new_post_open {
221 if !self.new_post_open {
@@ -314,6 +315,9 @@ impl ConversationView {
314 }
315 }
315
316
316 pub(super) fn on_escape(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
317 pub(super) fn on_escape(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
318 if self.close_new_folder(cx) {
319 return true;
320 }
317 if self.reply_root.is_some() {
321 if self.reply_root.is_some() {
318 self.close_reply_editor(cx);
322 self.close_reply_editor(cx);
319 return true;
323 return true;
crates/app/src/views/conversation/shared.rs added +701 −0
@@ -0,0 +1,701 @@
1 use std::path::PathBuf;
2 use std::rc::Rc;
3 use std::time::Instant;
4
5 use gpui_kit::component::input::{InputEvent, InputState};
6 use gpui_kit::*;
7 use store::ChannelTabRecord;
8 use teams_core::{DriveEntry, DriveFolder};
9
10 use super::ConversationView;
11 use crate::app_state::Selection;
12 use crate::channel_files::{
13 Crumb, DownloadSource, LibraryPath, MessageFilter, SharedContent, SharedItem, file_card,
14 library_file, shared_items, sorted_entries,
15 };
16 use crate::downloads::DownloadKey;
17 use crate::embedded_web::{self, EmbeddedWeb, EmbeddedWebEvent, Overlays};
18 use crate::notice::short_error;
19 use crate::runtime;
20 use crate::views::attachment_tray::{display_name, read_attachment};
21 use crate::views::channel_tabs::{
22 ChannelPane, TabAction, TabBarActions, fallback_tab_link, render_tab_bar, tab_action,
23 };
24 use crate::views::shared_tab::{
25 LibraryView, Listing, MessagesView, SharedCommand, SharedRun, SharedScope, render_library,
26 render_messages,
27 };
28 use crate::views::sidebar::SIDEBAR_WIDTH;
29
30 const LIBRARY_KEY: &str = "library";
31 const NEW_FOLDER_PLACEHOLDER: &str = "Folder name";
32 const ITEM_SCAN_LIMIT: usize = 5000;
33
34 pub(super) struct SharedState {
35 scope: SharedScope,
36 filter: MessageFilter,
37 path: Option<LibraryPath>,
38 listing: Listing,
39 generation: u64,
40 new_folder_open: bool,
41 uploads_running: usize,
42 items: Vec<SharedItem>,
43 listed_at: Option<Instant>,
44 }
45
46 impl Default for SharedState {
47 fn default() -> Self {
48 SharedState {
49 scope: SharedScope::Library,
50 filter: MessageFilter::All,
51 path: None,
52 listing: Listing::Loading,
53 generation: 0,
54 new_folder_open: false,
55 uploads_running: 0,
56 items: Vec::new(),
57 listed_at: None,
58 }
59 }
60 }
61
62 impl ConversationView {
63 fn channel_id(&self) -> Option<String> {
64 match &self.current.as_ref()?.selection {
65 Selection::Channel(channel_id) => Some(channel_id.clone()),
66 Selection::Chat(_) => None,
67 }
68 }
69
70 pub(super) fn shared_active(&self) -> bool {
71 self.pane == ChannelPane::Shared && self.in_feed()
72 }
73
74 pub(super) fn web_active(&self) -> bool {
75 self.pane == ChannelPane::Web && self.web.is_some() && self.in_feed()
76 }
77
78 pub(super) fn close_web(&mut self) {
79 self.web = None;
80 self.web_subscription = None;
81 }
82
83 pub(super) fn reset_channel_tabs(&mut self, cx: &mut Context<Self>) {
84 self.pane = ChannelPane::Posts;
85 self.close_web();
86 self.tab_links.clear();
87 self.shared = SharedState {
88 generation: self.shared.generation + 1,
89 ..SharedState::default()
90 };
91 self.reload_channel_tabs(cx);
92 }
93
94 pub(super) fn reload_channel_tabs(&mut self, cx: &mut Context<Self>) {
95 let store = self.app.read(cx).store.clone();
96 let tabs = self
97 .channel_id()
98 .and_then(|channel_id| store.channel_tabs(&channel_id).ok())
99 .unwrap_or_default();
100 if tabs != self.channel_tabs {
101 self.channel_tabs = tabs;
102 cx.notify();
103 }
104 }
105
106 pub(super) fn render_tab_bar(
107 &self,
108 window: &Window,
109 cx: &mut Context<Self>,
110 ) -> Option<AnyElement> {
111 self.channel_id().filter(|_| self.in_feed())?;
112 let available = f32::from(window.viewport_size().width) - SIDEBAR_WIDTH;
113 let view = cx.weak_entity();
114 let select = Rc::new(move |pane, cx: &mut App| {
115 view.update(cx, |this, cx| this.select_pane(pane, cx)).ok();
116 });
117 let open = {
118 let view = cx.weak_entity();
119 Rc::new(move |index: usize, window: &mut Window, cx: &mut App| {
120 view.update(cx, |this, cx| this.open_channel_tab(index, window, cx))
121 .ok();
122 })
123 };
124 let menu_toggled = Rc::new(move |open: bool, window: &mut Window, cx: &mut App| {
125 Overlays::update(cx, |overlays| overlays.tab_menu = open);
126 window.refresh();
127 });
128 let active_tab_id = self
129 .web
130 .as_ref()
131 .filter(|_| self.web_active())
132 .map(|web| web.read(cx).tab_id().to_owned());
133 Some(render_tab_bar(
134 &self.channel_tabs,
135 self.pane,
136 active_tab_id.as_deref(),
137 embedded_web::available(),
138 available,
139 &TabBarActions {
140 select,
141 open,
142 menu_toggled,
143 },
144 ))
145 }
146
147 fn open_channel_tab(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
148 let (Some(tab), Some(channel_id)) =
149 (self.channel_tabs.get(index).cloned(), self.channel_id())
150 else {
151 return;
152 };
153 let resolved = self.tab_links.get(&tab.tab_id).map(String::as_str);
154 match tab_action(&tab, embedded_web::available(), resolved) {
155 TabAction::Embed(url) => self.show_web_tab(tab.tab_id, url, window, cx),
156 TabAction::Browser(url) => cx.open_url(&url),
157 TabAction::ResolveLink => self.resolve_tab_link(tab, channel_id, cx),
158 }
159 }
160
161 fn show_web_tab(
162 &mut self,
163 tab_id: String,
164 url: String,
165 window: &mut Window,
166 cx: &mut Context<Self>,
167 ) {
168 if self.web_active()
169 && self
170 .web
171 .as_ref()
172 .is_some_and(|web| web.read(cx).tab_id() == tab_id)
173 {
174 return;
175 }
176 self.close_web();
177 let Some((native, events)) = embedded_web::Native::open(&url, window) else {
178 cx.open_url(&url);
179 return;
180 };
181 let web = cx.new(|cx| EmbeddedWeb::new(tab_id, url, native, events, cx));
182 self.web_subscription =
183 Some(cx.subscribe(&web, |this, _, event: &EmbeddedWebEvent, cx| {
184 let EmbeddedWebEvent::Closed { start_url } = event;
185 this.close_web();
186 this.pane = ChannelPane::Posts;
187 cx.open_url(start_url);
188 cx.notify();
189 }));
190 self.web = Some(web);
191 self.pane = ChannelPane::Web;
192 cx.notify();
193 }
194
195 fn resolve_tab_link(
196 &mut self,
197 tab: ChannelTabRecord,
198 channel_id: String,
199 cx: &mut Context<Self>,
200 ) {
201 let fallback = fallback_tab_link(&tab, &channel_id);
202 let state = self.app.read(cx);
203 let engine = state.engine.clone().filter(|_| !state.mode.demo);
204 let Some(engine) = engine else {
205 cx.open_url(&fallback);
206 return;
207 };
208 let tab_id = tab.tab_id;
209 let lookup = {
210 let tab_id = tab_id.clone();
211 runtime::spawn(async move { engine.channel_tab_web_url(&channel_id, &tab_id).await })
212 };
213 cx.spawn(async move |this, cx| {
214 let link = lookup.await.ok().and_then(Result::ok).flatten();
215 this.update(cx, |this, cx| {
216 let target = match link {
217 Some(link) => {
218 this.tab_links.insert(tab_id, link.clone());
219 link
220 }
221 None => fallback,
222 };
223 cx.open_url(&target);
224 })
225 .ok();
226 })
227 .detach();
228 }
229
230 pub(super) fn select_pane(&mut self, pane: ChannelPane, cx: &mut Context<Self>) {
231 if self.pane == pane {
232 return;
233 }
234 self.pane = pane;
235 self.close_web();
236 if pane == ChannelPane::Shared {
237 self.refresh_shared_items(cx);
238 if self.shared.path.is_none() {
239 self.load_library(cx);
240 }
241 }
242 cx.notify();
243 }
244
245 pub(super) fn refresh_shared_items(&mut self, cx: &mut Context<Self>) {
246 let Some(channel_id) = self.channel_id() else {
247 return;
248 };
249 let store = self.app.read(cx).store.clone();
250 let records = store
251 .messages(&channel_id, None, ITEM_SCAN_LIMIT)
252 .unwrap_or_default();
253 self.shared.items = shared_items(&records);
254 }
255
256 fn download_library_entry(
257 &mut self,
258 conversation_id: &str,
259 entry: &DriveEntry,
260 cx: &mut Context<Self>,
261 ) {
262 let source =
263 DownloadSource::Library(library_file(entry, self.shared.listed_at, Instant::now()));
264 self.activate_file(conversation_id, LIBRARY_KEY, file_card(entry), source, cx);
265 }
266
267 fn library_entry(&self, index: usize) -> Option<DriveEntry> {
268 match &self.shared.listing {
269 Listing::Ready(entries) => entries.get(index).cloned(),
270 _ => None,
271 }
272 }
273
274 fn library_download_states(&self) -> Vec<Option<crate::downloads::DownloadState>> {
275 let conversation_id = self.conversation_id().unwrap_or_default();
276 let Listing::Ready(entries) = &self.shared.listing else {
277 return Vec::new();
278 };
279 entries
280 .iter()
281 .map(|entry| {
282 let key = DownloadKey::new(&conversation_id, LIBRARY_KEY, &entry.web_url);
283 self.downloads.state(&key).cloned()
284 })
285 .collect()
286 }
287
288 fn item_download_states(&self) -> Vec<Option<crate::downloads::DownloadState>> {
289 let conversation_id = self.conversation_id().unwrap_or_default();
290 self.shared
291 .items
292 .iter()
293 .map(|item| match &item.content {
294 SharedContent::File(card) => {
295 let key = DownloadKey::new(&conversation_id, &item.message_id, &card.open_url);
296 self.downloads.state(&key).cloned()
297 }
298 SharedContent::Link(_) => None,
299 })
300 .collect()
301 }
302
303 pub(super) fn render_shared(&self, cx: &mut Context<Self>) -> AnyElement {
304 let view = cx.weak_entity();
305 let run: SharedRun = Rc::new(move |command, window, cx| {
306 view.update(cx, |this, cx| this.run_shared(command, window, cx))
307 .ok();
308 });
309 match self.shared.scope {
310 SharedScope::Library => {
311 let status = (self.shared.uploads_running > 0)
312 .then(|| format!("Uploading {} ...", self.shared.uploads_running));
313 render_library(
314 LibraryView {
315 path: self.shared.path.as_ref(),
316 listing: &self.shared.listing,
317 new_folder: self
318 .new_folder_input
319 .as_ref()
320 .filter(|_| self.shared.new_folder_open),
321 status: status.as_deref(),
322 download_states: self.library_download_states(),
323 },
324 &run,
325 )
326 }
327 SharedScope::Messages => render_messages(
328 MessagesView {
329 items: &self.shared.items,
330 filter: self.shared.filter,
331 download_states: self.item_download_states(),
332 },
333 &run,
334 ),
335 }
336 }
337
338 fn run_shared(&mut self, command: SharedCommand, window: &mut Window, cx: &mut Context<Self>) {
339 let conversation_id = self.conversation_id().unwrap_or_default();
340 match command {
341 SharedCommand::Scope(scope) => {
342 self.shared.scope = scope;
343 if scope == SharedScope::Messages {
344 self.refresh_shared_items(cx);
345 }
346 cx.notify();
347 }
348 SharedCommand::Filter(filter) => {
349 self.shared.filter = filter;
350 cx.notify();
351 }
352 SharedCommand::Crumb(index) => {
353 if let Some(path) = self.shared.path.as_mut() {
354 path.go_to(index);
355 }
356 self.shared.new_folder_open = false;
357 self.load_library(cx);
358 }
359 SharedCommand::Open(index) => {
360 let Some(entry) = self.library_entry(index) else {
361 return;
362 };
363 if entry.is_folder() {
364 if let Some(path) = self.shared.path.as_mut() {
365 path.enter(&entry);
366 }
367 self.shared.new_folder_open = false;
368 self.load_library(cx);
369 } else {
370 self.download_library_entry(&conversation_id, &entry, cx);
371 }
372 }
373 SharedCommand::OpenInBrowser(index) => {
374 if let Some(entry) = self.library_entry(index) {
375 cx.open_url(&entry.web_url);
376 }
377 }
378 SharedCommand::Download(index) => {
379 if let Some(entry) = self.library_entry(index) {
380 self.download_library_entry(&conversation_id, &entry, cx);
381 }
382 }
383 SharedCommand::CopyLink(index) => {
384 if let Some(entry) = self.library_entry(index) {
385 cx.write_to_clipboard(ClipboardItem::new_string(entry.web_url));
386 self.app.update(cx, |state, cx| {
387 state.raise_notice("Link copied".to_owned(), None, cx)
388 });
389 }
390 }
391 SharedCommand::Retry => self.load_library(cx),
392 SharedCommand::ToggleNewFolder => self.toggle_new_folder(window, cx),
393 SharedCommand::Upload => self.pick_upload(cx),
394 SharedCommand::OpenSharePoint => {
395 if let Some(path) = &self.shared.path {
396 cx.open_url(path.current_web_url());
397 }
398 }
399 SharedCommand::OpenItem(index) => {
400 let Some(item) = self.shared.items.get(index).cloned() else {
401 return;
402 };
403 match item.content {
404 SharedContent::File(card) => self.activate_file(
405 &conversation_id,
406 &item.message_id,
407 card,
408 DownloadSource::Share,
409 cx,
410 ),
411 SharedContent::Link(url) => cx.open_url(&url),
412 }
413 }
414 SharedCommand::JumpToPost(index) => {
415 let Some(message_id) = self
416 .shared
417 .items
418 .get(index)
419 .map(|item| item.message_id.clone())
420 else {
421 return;
422 };
423 self.jump_to_message(&conversation_id, &message_id, cx);
424 }
425 }
426 }
427
428 fn load_library(&mut self, cx: &mut Context<Self>) {
429 let Some(channel_id) = self.channel_id() else {
430 return;
431 };
432 self.shared.generation += 1;
433 let generation = self.shared.generation;
434 self.shared.listing = Listing::Loading;
435 cx.notify();
436 let state = self.app.read(cx);
437 let (demo, engine) = (state.mode.demo, state.engine.clone());
438 let folder = self.shared.path.as_ref().map(|path| path.current().clone());
439 if demo {
440 self.load_demo_library(&channel_id, folder.is_none());
441 return;
442 }
443 let Some(engine) = engine else {
444 self.shared.listing = Listing::Failed("not connected".to_owned());
445 return;
446 };
447 let receiver = runtime::spawn(async move {
448 let (root, target) = match folder {
449 Some(folder) => (None, folder),
450 None => {
451 let root = engine.channel_library_root(&channel_id).await?;
452 let target = root.folder();
453 (Some(root), target)
454 }
455 };
456 let entries = engine.library_children(&target).await?;
457 Ok::<_, teams_core::Error>((root, entries))
458 });
459 cx.spawn(async move |this, cx| {
460 let outcome = match receiver.await {
461 Ok(Ok(loaded)) => Ok(loaded),
462 Ok(Err(error)) => Err(short_error(&error)),
463 Err(error) => Err(short_error(&error)),
464 };
465 this.update(cx, |this, cx| {
466 this.finish_library_load(generation, outcome, cx)
467 })
468 .ok();
469 })
470 .detach();
471 }
472
473 fn finish_library_load(
474 &mut self,
475 generation: u64,
476 outcome: Result<(Option<DriveEntry>, Vec<DriveEntry>), String>,
477 cx: &mut Context<Self>,
478 ) {
479 if generation != self.shared.generation {
480 return;
481 }
482 match outcome {
483 Ok((root, entries)) => {
484 if let Some(root) = root {
485 self.shared.path = Some(LibraryPath::new(Crumb {
486 name: root.name.clone(),
487 folder: root.folder(),
488 web_url: root.web_url,
489 }));
490 }
491 self.shared.listing = Listing::Ready(sorted_entries(entries));
492 self.shared.listed_at = Some(Instant::now());
493 }
494 Err(reason) => self.shared.listing = Listing::Failed(reason),
495 }
496 cx.notify();
497 }
498
499 fn load_demo_library(&mut self, channel_id: &str, at_root: bool) {
500 if at_root {
501 let name = self
502 .current
503 .as_ref()
504 .map(|current| current.title.clone())
505 .unwrap_or_default();
506 let root = self.demo_library.root(channel_id, &name);
507 self.shared.path = Some(LibraryPath::new(Crumb {
508 name: root.name.clone(),
509 folder: root.folder(),
510 web_url: root.web_url,
511 }));
512 }
513 let Some(path) = &self.shared.path else {
514 return;
515 };
516 let entries = self.demo_library.children(&path.current().item_id);
517 self.shared.listing = Listing::Ready(sorted_entries(entries));
518 }
519
520 fn toggle_new_folder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
521 if self.shared.new_folder_open {
522 self.shared.new_folder_open = false;
523 cx.notify();
524 return;
525 }
526 let input = match &self.new_folder_input {
527 Some(input) => input.clone(),
528 None => {
529 let input =
530 cx.new(|cx| InputState::new(window, cx).placeholder(NEW_FOLDER_PLACEHOLDER));
531 let subscription = cx.subscribe_in(&input, window, Self::on_new_folder_event);
532 self._subscriptions.push(subscription);
533 self.new_folder_input = Some(input.clone());
534 input
535 }
536 };
537 input.update(cx, |input, cx| {
538 input.set_value("", window, cx);
539 input.focus(window, cx);
540 });
541 self.shared.new_folder_open = true;
542 cx.notify();
543 }
544
545 fn on_new_folder_event(
546 &mut self,
547 _: &Entity<InputState>,
548 event: &InputEvent,
549 _: &mut Window,
550 cx: &mut Context<Self>,
551 ) {
552 if matches!(event, InputEvent::PressEnter { .. }) {
553 self.create_folder(cx);
554 }
555 }
556
557 pub(super) fn close_new_folder(&mut self, cx: &mut Context<Self>) -> bool {
558 if !self.shared.new_folder_open {
559 return false;
560 }
561 self.shared.new_folder_open = false;
562 cx.notify();
563 true
564 }
565
566 fn create_folder(&mut self, cx: &mut Context<Self>) {
567 let Some(input) = self.new_folder_input.clone() else {
568 return;
569 };
570 let name = input.read(cx).value().trim().to_owned();
571 let Some(parent) = self.shared.path.as_ref().map(|path| path.current().clone()) else {
572 return;
573 };
574 if name.is_empty() {
575 return;
576 }
577 self.shared.new_folder_open = false;
578 let state = self.app.read(cx);
579 let (demo, engine) = (state.mode.demo, state.engine.clone());
580 if demo {
581 self.demo_library.create_folder(&parent.item_id, &name);
582 self.load_library(cx);
583 return;
584 }
585 let Some(engine) = engine else {
586 return;
587 };
588 let target = parent.clone();
589 let receiver =
590 runtime::spawn(async move { engine.create_library_folder(&target, &name).await });
591 cx.spawn(async move |this, cx| {
592 let outcome = match receiver.await {
593 Ok(Ok(_)) => Ok(()),
594 Ok(Err(error)) => Err(short_error(&error)),
595 Err(error) => Err(short_error(&error)),
596 };
597 this.update(cx, |this, cx| {
598 this.finish_change(&parent, outcome, "Folder not created", cx)
599 })
600 .ok();
601 })
602 .detach();
603 }
604
605 fn finish_change(
606 &mut self,
607 folder: &DriveFolder,
608 outcome: Result<(), String>,
609 failure: &str,
610 cx: &mut Context<Self>,
611 ) {
612 if let Err(reason) = outcome {
613 self.notice = Some(format!("{failure}: {reason}"));
614 }
615 let still_open = self
616 .shared
617 .path
618 .as_ref()
619 .is_some_and(|path| path.current() == folder);
620 if still_open {
621 self.load_library(cx);
622 } else {
623 cx.notify();
624 }
625 }
626
627 fn pick_upload(&mut self, cx: &mut Context<Self>) {
628 let receiver = cx.prompt_for_paths(PathPromptOptions {
629 files: true,
630 directories: false,
631 multiple: true,
632 prompt: None,
633 });
634 cx.spawn(async move |this, cx| {
635 if let Ok(Ok(Some(paths))) = receiver.await {
636 this.update(cx, |this, cx| this.upload_paths(paths, cx))
637 .ok();
638 }
639 })
640 .detach();
641 }
642
643 pub(super) fn upload_paths(&mut self, paths: Vec<PathBuf>, cx: &mut Context<Self>) {
644 let Some(folder) = self.shared.path.as_ref().map(|path| path.current().clone()) else {
645 return;
646 };
647 let state = self.app.read(cx);
648 let (demo, engine) = (state.mode.demo, state.engine.clone());
649 for path in paths {
650 self.shared.uploads_running += 1;
651 let (folder, engine) = (folder.clone(), engine.clone());
652 cx.spawn(async move |this, cx| {
653 let name = display_name(&path);
654 let loaded = cx
655 .background_executor()
656 .spawn(async move { read_attachment(&path) })
657 .await;
658 let outcome = match loaded {
659 Err(reason) => Err(reason),
660 Ok(file) if demo => {
661 let size = file.bytes.len() as u64;
662 let (folder_id, file_name) = (folder.item_id.clone(), name.clone());
663 this.update(cx, |this, _| {
664 this.demo_library.add_file(&folder_id, &file_name, size);
665 })
666 .ok();
667 Ok(())
668 }
669 Ok(file) => match engine {
670 None => Err("not connected".to_owned()),
671 Some(engine) => {
672 let (target, file_name) = (folder.clone(), name.clone());
673 let receiver = runtime::spawn(async move {
674 engine
675 .upload_to_library(&target, &file_name, &file.bytes, |_| {})
676 .await
677 });
678 match receiver.await {
679 Ok(Ok(_)) => Ok(()),
680 Ok(Err(error)) => Err(short_error(&error)),
681 Err(error) => Err(short_error(&error)),
682 }
683 }
684 },
685 };
686 this.update(cx, |this, cx| {
687 this.shared.uploads_running = this.shared.uploads_running.saturating_sub(1);
688 let failure = format!("{name} not uploaded");
689 if this.shared.uploads_running == 0 || outcome.is_err() {
690 this.finish_change(&folder, outcome, &failure, cx);
691 } else {
692 cx.notify();
693 }
694 })
695 .ok();
696 })
697 .detach();
698 }
699 cx.notify();
700 }
701 }
@@ -0,0 +1,701 @@
1use std::path::PathBuf;
2use std::rc::Rc;
3use std::time::Instant;
4
5use gpui_kit::component::input::{InputEvent, InputState};
6use gpui_kit::*;
7use store::ChannelTabRecord;
8use teams_core::{DriveEntry, DriveFolder};
9
10use super::ConversationView;
11use crate::app_state::Selection;
12use crate::channel_files::{
13 Crumb, DownloadSource, LibraryPath, MessageFilter, SharedContent, SharedItem, file_card,
14 library_file, shared_items, sorted_entries,
15};
16use crate::downloads::DownloadKey;
17use crate::embedded_web::{self, EmbeddedWeb, EmbeddedWebEvent, Overlays};
18use crate::notice::short_error;
19use crate::runtime;
20use crate::views::attachment_tray::{display_name, read_attachment};
21use crate::views::channel_tabs::{
22 ChannelPane, TabAction, TabBarActions, fallback_tab_link, render_tab_bar, tab_action,
23};
24use crate::views::shared_tab::{
25 LibraryView, Listing, MessagesView, SharedCommand, SharedRun, SharedScope, render_library,
26 render_messages,
27};
28use crate::views::sidebar::SIDEBAR_WIDTH;
29
30const LIBRARY_KEY: &str = "library";
31const NEW_FOLDER_PLACEHOLDER: &str = "Folder name";
32const ITEM_SCAN_LIMIT: usize = 5000;
33
34pub(super) struct SharedState {
35 scope: SharedScope,
36 filter: MessageFilter,
37 path: Option<LibraryPath>,
38 listing: Listing,
39 generation: u64,
40 new_folder_open: bool,
41 uploads_running: usize,
42 items: Vec<SharedItem>,
43 listed_at: Option<Instant>,
44}
45
46impl Default for SharedState {
47 fn default() -> Self {
48 SharedState {
49 scope: SharedScope::Library,
50 filter: MessageFilter::All,
51 path: None,
52 listing: Listing::Loading,
53 generation: 0,
54 new_folder_open: false,
55 uploads_running: 0,
56 items: Vec::new(),
57 listed_at: None,
58 }
59 }
60}
61
62impl ConversationView {
63 fn channel_id(&self) -> Option<String> {
64 match &self.current.as_ref()?.selection {
65 Selection::Channel(channel_id) => Some(channel_id.clone()),
66 Selection::Chat(_) => None,
67 }
68 }
69
70 pub(super) fn shared_active(&self) -> bool {
71 self.pane == ChannelPane::Shared && self.in_feed()
72 }
73
74 pub(super) fn web_active(&self) -> bool {
75 self.pane == ChannelPane::Web && self.web.is_some() && self.in_feed()
76 }
77
78 pub(super) fn close_web(&mut self) {
79 self.web = None;
80 self.web_subscription = None;
81 }
82
83 pub(super) fn reset_channel_tabs(&mut self, cx: &mut Context<Self>) {
84 self.pane = ChannelPane::Posts;
85 self.close_web();
86 self.tab_links.clear();
87 self.shared = SharedState {
88 generation: self.shared.generation + 1,
89 ..SharedState::default()
90 };
91 self.reload_channel_tabs(cx);
92 }
93
94 pub(super) fn reload_channel_tabs(&mut self, cx: &mut Context<Self>) {
95 let store = self.app.read(cx).store.clone();
96 let tabs = self
97 .channel_id()
98 .and_then(|channel_id| store.channel_tabs(&channel_id).ok())
99 .unwrap_or_default();
100 if tabs != self.channel_tabs {
101 self.channel_tabs = tabs;
102 cx.notify();
103 }
104 }
105
106 pub(super) fn render_tab_bar(
107 &self,
108 window: &Window,
109 cx: &mut Context<Self>,
110 ) -> Option<AnyElement> {
111 self.channel_id().filter(|_| self.in_feed())?;
112 let available = f32::from(window.viewport_size().width) - SIDEBAR_WIDTH;
113 let view = cx.weak_entity();
114 let select = Rc::new(move |pane, cx: &mut App| {
115 view.update(cx, |this, cx| this.select_pane(pane, cx)).ok();
116 });
117 let open = {
118 let view = cx.weak_entity();
119 Rc::new(move |index: usize, window: &mut Window, cx: &mut App| {
120 view.update(cx, |this, cx| this.open_channel_tab(index, window, cx))
121 .ok();
122 })
123 };
124 let menu_toggled = Rc::new(move |open: bool, window: &mut Window, cx: &mut App| {
125 Overlays::update(cx, |overlays| overlays.tab_menu = open);
126 window.refresh();
127 });
128 let active_tab_id = self
129 .web
130 .as_ref()
131 .filter(|_| self.web_active())
132 .map(|web| web.read(cx).tab_id().to_owned());
133 Some(render_tab_bar(
134 &self.channel_tabs,
135 self.pane,
136 active_tab_id.as_deref(),
137 embedded_web::available(),
138 available,
139 &TabBarActions {
140 select,
141 open,
142 menu_toggled,
143 },
144 ))
145 }
146
147 fn open_channel_tab(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
148 let (Some(tab), Some(channel_id)) =
149 (self.channel_tabs.get(index).cloned(), self.channel_id())
150 else {
151 return;
152 };
153 let resolved = self.tab_links.get(&tab.tab_id).map(String::as_str);
154 match tab_action(&tab, embedded_web::available(), resolved) {
155 TabAction::Embed(url) => self.show_web_tab(tab.tab_id, url, window, cx),
156 TabAction::Browser(url) => cx.open_url(&url),
157 TabAction::ResolveLink => self.resolve_tab_link(tab, channel_id, cx),
158 }
159 }
160
161 fn show_web_tab(
162 &mut self,
163 tab_id: String,
164 url: String,
165 window: &mut Window,
166 cx: &mut Context<Self>,
167 ) {
168 if self.web_active()
169 && self
170 .web
171 .as_ref()
172 .is_some_and(|web| web.read(cx).tab_id() == tab_id)
173 {
174 return;
175 }
176 self.close_web();
177 let Some((native, events)) = embedded_web::Native::open(&url, window) else {
178 cx.open_url(&url);
179 return;
180 };
181 let web = cx.new(|cx| EmbeddedWeb::new(tab_id, url, native, events, cx));
182 self.web_subscription =
183 Some(cx.subscribe(&web, |this, _, event: &EmbeddedWebEvent, cx| {
184 let EmbeddedWebEvent::Closed { start_url } = event;
185 this.close_web();
186 this.pane = ChannelPane::Posts;
187 cx.open_url(start_url);
188 cx.notify();
189 }));
190 self.web = Some(web);
191 self.pane = ChannelPane::Web;
192 cx.notify();
193 }
194
195 fn resolve_tab_link(
196 &mut self,
197 tab: ChannelTabRecord,
198 channel_id: String,
199 cx: &mut Context<Self>,
200 ) {
201 let fallback = fallback_tab_link(&tab, &channel_id);
202 let state = self.app.read(cx);
203 let engine = state.engine.clone().filter(|_| !state.mode.demo);
204 let Some(engine) = engine else {
205 cx.open_url(&fallback);
206 return;
207 };
208 let tab_id = tab.tab_id;
209 let lookup = {
210 let tab_id = tab_id.clone();
211 runtime::spawn(async move { engine.channel_tab_web_url(&channel_id, &tab_id).await })
212 };
213 cx.spawn(async move |this, cx| {
214 let link = lookup.await.ok().and_then(Result::ok).flatten();
215 this.update(cx, |this, cx| {
216 let target = match link {
217 Some(link) => {
218 this.tab_links.insert(tab_id, link.clone());
219 link
220 }
221 None => fallback,
222 };
223 cx.open_url(&target);
224 })
225 .ok();
226 })
227 .detach();
228 }
229
230 pub(super) fn select_pane(&mut self, pane: ChannelPane, cx: &mut Context<Self>) {
231 if self.pane == pane {
232 return;
233 }
234 self.pane = pane;
235 self.close_web();
236 if pane == ChannelPane::Shared {
237 self.refresh_shared_items(cx);
238 if self.shared.path.is_none() {
239 self.load_library(cx);
240 }
241 }
242 cx.notify();
243 }
244
245 pub(super) fn refresh_shared_items(&mut self, cx: &mut Context<Self>) {
246 let Some(channel_id) = self.channel_id() else {
247 return;
248 };
249 let store = self.app.read(cx).store.clone();
250 let records = store
251 .messages(&channel_id, None, ITEM_SCAN_LIMIT)
252 .unwrap_or_default();
253 self.shared.items = shared_items(&records);
254 }
255
256 fn download_library_entry(
257 &mut self,
258 conversation_id: &str,
259 entry: &DriveEntry,
260 cx: &mut Context<Self>,
261 ) {
262 let source =
263 DownloadSource::Library(library_file(entry, self.shared.listed_at, Instant::now()));
264 self.activate_file(conversation_id, LIBRARY_KEY, file_card(entry), source, cx);
265 }
266
267 fn library_entry(&self, index: usize) -> Option<DriveEntry> {
268 match &self.shared.listing {
269 Listing::Ready(entries) => entries.get(index).cloned(),
270 _ => None,
271 }
272 }
273
274 fn library_download_states(&self) -> Vec<Option<crate::downloads::DownloadState>> {
275 let conversation_id = self.conversation_id().unwrap_or_default();
276 let Listing::Ready(entries) = &self.shared.listing else {
277 return Vec::new();
278 };
279 entries
280 .iter()
281 .map(|entry| {
282 let key = DownloadKey::new(&conversation_id, LIBRARY_KEY, &entry.web_url);
283 self.downloads.state(&key).cloned()
284 })
285 .collect()
286 }
287
288 fn item_download_states(&self) -> Vec<Option<crate::downloads::DownloadState>> {
289 let conversation_id = self.conversation_id().unwrap_or_default();
290 self.shared
291 .items
292 .iter()
293 .map(|item| match &item.content {
294 SharedContent::File(card) => {
295 let key = DownloadKey::new(&conversation_id, &item.message_id, &card.open_url);
296 self.downloads.state(&key).cloned()
297 }
298 SharedContent::Link(_) => None,
299 })
300 .collect()
301 }
302
303 pub(super) fn render_shared(&self, cx: &mut Context<Self>) -> AnyElement {
304 let view = cx.weak_entity();
305 let run: SharedRun = Rc::new(move |command, window, cx| {
306 view.update(cx, |this, cx| this.run_shared(command, window, cx))
307 .ok();
308 });
309 match self.shared.scope {
310 SharedScope::Library => {
311 let status = (self.shared.uploads_running > 0)
312 .then(|| format!("Uploading {} ...", self.shared.uploads_running));
313 render_library(
314 LibraryView {
315 path: self.shared.path.as_ref(),
316 listing: &self.shared.listing,
317 new_folder: self
318 .new_folder_input
319 .as_ref()
320 .filter(|_| self.shared.new_folder_open),
321 status: status.as_deref(),
322 download_states: self.library_download_states(),
323 },
324 &run,
325 )
326 }
327 SharedScope::Messages => render_messages(
328 MessagesView {
329 items: &self.shared.items,
330 filter: self.shared.filter,
331 download_states: self.item_download_states(),
332 },
333 &run,
334 ),
335 }
336 }
337
338 fn run_shared(&mut self, command: SharedCommand, window: &mut Window, cx: &mut Context<Self>) {
339 let conversation_id = self.conversation_id().unwrap_or_default();
340 match command {
341 SharedCommand::Scope(scope) => {
342 self.shared.scope = scope;
343 if scope == SharedScope::Messages {
344 self.refresh_shared_items(cx);
345 }
346 cx.notify();
347 }
348 SharedCommand::Filter(filter) => {
349 self.shared.filter = filter;
350 cx.notify();
351 }
352 SharedCommand::Crumb(index) => {
353 if let Some(path) = self.shared.path.as_mut() {
354 path.go_to(index);
355 }
356 self.shared.new_folder_open = false;
357 self.load_library(cx);
358 }
359 SharedCommand::Open(index) => {
360 let Some(entry) = self.library_entry(index) else {
361 return;
362 };
363 if entry.is_folder() {
364 if let Some(path) = self.shared.path.as_mut() {
365 path.enter(&entry);
366 }
367 self.shared.new_folder_open = false;
368 self.load_library(cx);
369 } else {
370 self.download_library_entry(&conversation_id, &entry, cx);
371 }
372 }
373 SharedCommand::OpenInBrowser(index) => {
374 if let Some(entry) = self.library_entry(index) {
375 cx.open_url(&entry.web_url);
376 }
377 }
378 SharedCommand::Download(index) => {
379 if let Some(entry) = self.library_entry(index) {
380 self.download_library_entry(&conversation_id, &entry, cx);
381 }
382 }
383 SharedCommand::CopyLink(index) => {
384 if let Some(entry) = self.library_entry(index) {
385 cx.write_to_clipboard(ClipboardItem::new_string(entry.web_url));
386 self.app.update(cx, |state, cx| {
387 state.raise_notice("Link copied".to_owned(), None, cx)
388 });
389 }
390 }
391 SharedCommand::Retry => self.load_library(cx),
392 SharedCommand::ToggleNewFolder => self.toggle_new_folder(window, cx),
393 SharedCommand::Upload => self.pick_upload(cx),
394 SharedCommand::OpenSharePoint => {
395 if let Some(path) = &self.shared.path {
396 cx.open_url(path.current_web_url());
397 }
398 }
399 SharedCommand::OpenItem(index) => {
400 let Some(item) = self.shared.items.get(index).cloned() else {
401 return;
402 };
403 match item.content {
404 SharedContent::File(card) => self.activate_file(
405 &conversation_id,
406 &item.message_id,
407 card,
408 DownloadSource::Share,
409 cx,
410 ),
411 SharedContent::Link(url) => cx.open_url(&url),
412 }
413 }
414 SharedCommand::JumpToPost(index) => {
415 let Some(message_id) = self
416 .shared
417 .items
418 .get(index)
419 .map(|item| item.message_id.clone())
420 else {
421 return;
422 };
423 self.jump_to_message(&conversation_id, &message_id, cx);
424 }
425 }
426 }
427
428 fn load_library(&mut self, cx: &mut Context<Self>) {
429 let Some(channel_id) = self.channel_id() else {
430 return;
431 };
432 self.shared.generation += 1;
433 let generation = self.shared.generation;
434 self.shared.listing = Listing::Loading;
435 cx.notify();
436 let state = self.app.read(cx);
437 let (demo, engine) = (state.mode.demo, state.engine.clone());
438 let folder = self.shared.path.as_ref().map(|path| path.current().clone());
439 if demo {
440 self.load_demo_library(&channel_id, folder.is_none());
441 return;
442 }
443 let Some(engine) = engine else {
444 self.shared.listing = Listing::Failed("not connected".to_owned());
445 return;
446 };
447 let receiver = runtime::spawn(async move {
448 let (root, target) = match folder {
449 Some(folder) => (None, folder),
450 None => {
451 let root = engine.channel_library_root(&channel_id).await?;
452 let target = root.folder();
453 (Some(root), target)
454 }
455 };
456 let entries = engine.library_children(&target).await?;
457 Ok::<_, teams_core::Error>((root, entries))
458 });
459 cx.spawn(async move |this, cx| {
460 let outcome = match receiver.await {
461 Ok(Ok(loaded)) => Ok(loaded),
462 Ok(Err(error)) => Err(short_error(&error)),
463 Err(error) => Err(short_error(&error)),
464 };
465 this.update(cx, |this, cx| {
466 this.finish_library_load(generation, outcome, cx)
467 })
468 .ok();
469 })
470 .detach();
471 }
472
473 fn finish_library_load(
474 &mut self,
475 generation: u64,
476 outcome: Result<(Option<DriveEntry>, Vec<DriveEntry>), String>,
477 cx: &mut Context<Self>,
478 ) {
479 if generation != self.shared.generation {
480 return;
481 }
482 match outcome {
483 Ok((root, entries)) => {
484 if let Some(root) = root {
485 self.shared.path = Some(LibraryPath::new(Crumb {
486 name: root.name.clone(),
487 folder: root.folder(),
488 web_url: root.web_url,
489 }));
490 }
491 self.shared.listing = Listing::Ready(sorted_entries(entries));
492 self.shared.listed_at = Some(Instant::now());
493 }
494 Err(reason) => self.shared.listing = Listing::Failed(reason),
495 }
496 cx.notify();
497 }
498
499 fn load_demo_library(&mut self, channel_id: &str, at_root: bool) {
500 if at_root {
501 let name = self
502 .current
503 .as_ref()
504 .map(|current| current.title.clone())
505 .unwrap_or_default();
506 let root = self.demo_library.root(channel_id, &name);
507 self.shared.path = Some(LibraryPath::new(Crumb {
508 name: root.name.clone(),
509 folder: root.folder(),
510 web_url: root.web_url,
511 }));
512 }
513 let Some(path) = &self.shared.path else {
514 return;
515 };
516 let entries = self.demo_library.children(&path.current().item_id);
517 self.shared.listing = Listing::Ready(sorted_entries(entries));
518 }
519
520 fn toggle_new_folder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
521 if self.shared.new_folder_open {
522 self.shared.new_folder_open = false;
523 cx.notify();
524 return;
525 }
526 let input = match &self.new_folder_input {
527 Some(input) => input.clone(),
528 None => {
529 let input =
530 cx.new(|cx| InputState::new(window, cx).placeholder(NEW_FOLDER_PLACEHOLDER));
531 let subscription = cx.subscribe_in(&input, window, Self::on_new_folder_event);
532 self._subscriptions.push(subscription);
533 self.new_folder_input = Some(input.clone());
534 input
535 }
536 };
537 input.update(cx, |input, cx| {
538 input.set_value("", window, cx);
539 input.focus(window, cx);
540 });
541 self.shared.new_folder_open = true;
542 cx.notify();
543 }
544
545 fn on_new_folder_event(
546 &mut self,
547 _: &Entity<InputState>,
548 event: &InputEvent,
549 _: &mut Window,
550 cx: &mut Context<Self>,
551 ) {
552 if matches!(event, InputEvent::PressEnter { .. }) {
553 self.create_folder(cx);
554 }
555 }
556
557 pub(super) fn close_new_folder(&mut self, cx: &mut Context<Self>) -> bool {
558 if !self.shared.new_folder_open {
559 return false;
560 }
561 self.shared.new_folder_open = false;
562 cx.notify();
563 true
564 }
565
566 fn create_folder(&mut self, cx: &mut Context<Self>) {
567 let Some(input) = self.new_folder_input.clone() else {
568 return;
569 };
570 let name = input.read(cx).value().trim().to_owned();
571 let Some(parent) = self.shared.path.as_ref().map(|path| path.current().clone()) else {
572 return;
573 };
574 if name.is_empty() {
575 return;
576 }
577 self.shared.new_folder_open = false;
578 let state = self.app.read(cx);
579 let (demo, engine) = (state.mode.demo, state.engine.clone());
580 if demo {
581 self.demo_library.create_folder(&parent.item_id, &name);
582 self.load_library(cx);
583 return;
584 }
585 let Some(engine) = engine else {
586 return;
587 };
588 let target = parent.clone();
589 let receiver =
590 runtime::spawn(async move { engine.create_library_folder(&target, &name).await });
591 cx.spawn(async move |this, cx| {
592 let outcome = match receiver.await {
593 Ok(Ok(_)) => Ok(()),
594 Ok(Err(error)) => Err(short_error(&error)),
595 Err(error) => Err(short_error(&error)),
596 };
597 this.update(cx, |this, cx| {
598 this.finish_change(&parent, outcome, "Folder not created", cx)
599 })
600 .ok();
601 })
602 .detach();
603 }
604
605 fn finish_change(
606 &mut self,
607 folder: &DriveFolder,
608 outcome: Result<(), String>,
609 failure: &str,
610 cx: &mut Context<Self>,
611 ) {
612 if let Err(reason) = outcome {
613 self.notice = Some(format!("{failure}: {reason}"));
614 }
615 let still_open = self
616 .shared
617 .path
618 .as_ref()
619 .is_some_and(|path| path.current() == folder);
620 if still_open {
621 self.load_library(cx);
622 } else {
623 cx.notify();
624 }
625 }
626
627 fn pick_upload(&mut self, cx: &mut Context<Self>) {
628 let receiver = cx.prompt_for_paths(PathPromptOptions {
629 files: true,
630 directories: false,
631 multiple: true,
632 prompt: None,
633 });
634 cx.spawn(async move |this, cx| {
635 if let Ok(Ok(Some(paths))) = receiver.await {
636 this.update(cx, |this, cx| this.upload_paths(paths, cx))
637 .ok();
638 }
639 })
640 .detach();
641 }
642
643 pub(super) fn upload_paths(&mut self, paths: Vec<PathBuf>, cx: &mut Context<Self>) {
644 let Some(folder) = self.shared.path.as_ref().map(|path| path.current().clone()) else {
645 return;
646 };
647 let state = self.app.read(cx);
648 let (demo, engine) = (state.mode.demo, state.engine.clone());
649 for path in paths {
650 self.shared.uploads_running += 1;
651 let (folder, engine) = (folder.clone(), engine.clone());
652 cx.spawn(async move |this, cx| {
653 let name = display_name(&path);
654 let loaded = cx
655 .background_executor()
656 .spawn(async move { read_attachment(&path) })
657 .await;
658 let outcome = match loaded {
659 Err(reason) => Err(reason),
660 Ok(file) if demo => {
661 let size = file.bytes.len() as u64;
662 let (folder_id, file_name) = (folder.item_id.clone(), name.clone());
663 this.update(cx, |this, _| {
664 this.demo_library.add_file(&folder_id, &file_name, size);
665 })
666 .ok();
667 Ok(())
668 }
669 Ok(file) => match engine {
670 None => Err("not connected".to_owned()),
671 Some(engine) => {
672 let (target, file_name) = (folder.clone(), name.clone());
673 let receiver = runtime::spawn(async move {
674 engine
675 .upload_to_library(&target, &file_name, &file.bytes, |_| {})
676 .await
677 });
678 match receiver.await {
679 Ok(Ok(_)) => Ok(()),
680 Ok(Err(error)) => Err(short_error(&error)),
681 Err(error) => Err(short_error(&error)),
682 }
683 }
684 },
685 };
686 this.update(cx, |this, cx| {
687 this.shared.uploads_running = this.shared.uploads_running.saturating_sub(1);
688 let failure = format!("{name} not uploaded");
689 if this.shared.uploads_running == 0 || outcome.is_err() {
690 this.finish_change(&folder, outcome, &failure, cx);
691 } else {
692 cx.notify();
693 }
694 })
695 .ok();
696 })
697 .detach();
698 }
699 cx.notify();
700 }
701}
crates/app/src/views/mod.rs +2 −0
@@ -11,6 +11,7 @@ pub mod card_input;
11 11 pub mod card_media;
12 12 pub mod card_table;
13 13 pub mod card_widgets;
14 pub mod channel_tabs;
14 15 pub mod composer;
15 16 pub mod conversation;
16 17 pub mod dialog_overlay;
@@ -30,6 +31,7 @@ pub mod reaction_picker;
30 31 pub mod reaction_pills;
31 32 pub mod saved_panel;
32 33 pub mod scheduled_toolbar;
34 pub mod shared_tab;
33 35 pub mod shell;
34 36 pub mod sidebar;
35 37 pub mod status_bar;
@@ -11,6 +11,7 @@ pub mod card_input;
11pub mod card_media;
11pub mod card_media;
12pub mod card_table;
12pub mod card_table;
13pub mod card_widgets;
13pub mod card_widgets;
14pub mod channel_tabs;
14pub mod composer;
15pub mod composer;
15pub mod conversation;
16pub mod conversation;
16pub mod dialog_overlay;
17pub mod dialog_overlay;
@@ -30,6 +31,7 @@ pub mod reaction_picker;
30pub mod reaction_pills;
31pub mod reaction_pills;
31pub mod saved_panel;
32pub mod saved_panel;
32pub mod scheduled_toolbar;
33pub mod scheduled_toolbar;
34pub mod shared_tab;
33pub mod shell;
35pub mod shell;
34pub mod sidebar;
36pub mod sidebar;
35pub mod status_bar;
37pub mod status_bar;
crates/app/src/views/shared_tab.rs added +689 −0
@@ -0,0 +1,689 @@
1 use std::rc::Rc;
2
3 use chrono::{Local, Offset as _};
4 use gpui_kit::assets::IconName;
5 use gpui_kit::component::{
6 button::{Button, ButtonVariants as _},
7 h_flex,
8 input::{Input, InputState},
9 menu::{ContextMenuExt as _, PopupMenuItem},
10 v_flex,
11 };
12 use gpui_kit::prelude::FluentBuilder as _;
13 use gpui_kit::*;
14 use teams_core::{DriveEntry, FileKind};
15
16 use super::attachments::file_badge;
17 use super::widgets::icon;
18 use crate::channel_files::{
19 LibraryPath, MessageFilter, SharedContent, SharedItem, grouped_items, size_label,
20 };
21 use crate::downloads::{DownloadState, percent_label};
22 use crate::format;
23 use crate::theme;
24
25 const SIDE_PADDING: f32 = 24.;
26 const ROW_HEIGHT: f32 = 40.;
27 const BADGE_SIZE: f32 = 26.;
28 const MODIFIED_WIDTH: f32 = 110.;
29 const MODIFIED_BY_WIDTH: f32 = 160.;
30 const SIZE_WIDTH: f32 = 90.;
31 const SKELETON_ROWS: usize = 6;
32 const NEW_FOLDER_WIDTH: f32 = 220.;
33 const MENU_ICON_SIZE: f32 = 14.;
34
35 pub const EMPTY_LIBRARY: &str = "No files yet. Upload or drop files here.";
36 pub const EMPTY_MESSAGES: &str = "No files or links shared in this channel yet.";
37
38 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
39 pub enum SharedScope {
40 Library,
41 Messages,
42 }
43
44 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
45 pub enum SharedCommand {
46 Scope(SharedScope),
47 Filter(MessageFilter),
48 Crumb(usize),
49 Open(usize),
50 OpenInBrowser(usize),
51 Download(usize),
52 CopyLink(usize),
53 Retry,
54 ToggleNewFolder,
55 Upload,
56 OpenSharePoint,
57 OpenItem(usize),
58 JumpToPost(usize),
59 }
60
61 pub type SharedRun = Rc<dyn Fn(SharedCommand, &mut Window, &mut App)>;
62
63 pub enum Listing {
64 Loading,
65 Failed(String),
66 Ready(Vec<DriveEntry>),
67 }
68
69 pub struct LibraryView<'a> {
70 pub path: Option<&'a LibraryPath>,
71 pub listing: &'a Listing,
72 pub new_folder: Option<&'a Entity<InputState>>,
73 pub status: Option<&'a str>,
74 pub download_states: Vec<Option<DownloadState>>,
75 }
76
77 pub struct MessagesView<'a> {
78 pub items: &'a [SharedItem],
79 pub filter: MessageFilter,
80 pub download_states: Vec<Option<DownloadState>>,
81 }
82
83 pub fn download_label(state: Option<&DownloadState>) -> Option<String> {
84 match state? {
85 DownloadState::Saving(percent) => Some(percent_label(*percent)),
86 DownloadState::Saved(_) => Some("Saved".to_owned()),
87 DownloadState::Failed(_) => Some("Failed, click to retry".to_owned()),
88 }
89 }
90
91 fn segment(
92 id: &'static str,
93 label: &'static str,
94 active: bool,
95 command: SharedCommand,
96 run: &SharedRun,
97 ) -> Stateful<Div> {
98 let run = run.clone();
99 div()
100 .id(id)
101 .px(px(14.))
102 .py(px(5.))
103 .rounded(px(6.))
104 .cursor_pointer()
105 .text_size(px(12.5))
106 .font_weight(if active {
107 FontWeight::SEMIBOLD
108 } else {
109 FontWeight::NORMAL
110 })
111 .text_color(if active {
112 theme::text()
113 } else {
114 theme::text_muted()
115 })
116 .when(active, |segment| segment.bg(theme::border_strong()))
117 .on_click(move |_, window, cx| run(command, window, cx))
118 .child(label)
119 }
120
121 fn switch(scope: SharedScope, run: &SharedRun) -> Div {
122 h_flex()
123 .p(px(2.))
124 .gap(px(2.))
125 .rounded(px(8.))
126 .bg(theme::surface_raised())
127 .child(segment(
128 "shared-in-library",
129 "In library",
130 scope == SharedScope::Library,
131 SharedCommand::Scope(SharedScope::Library),
132 run,
133 ))
134 .child(segment(
135 "shared-in-messages",
136 "In messages",
137 scope == SharedScope::Messages,
138 SharedCommand::Scope(SharedScope::Messages),
139 run,
140 ))
141 }
142
143 fn tool_button(
144 id: &'static str,
145 label: &'static str,
146 glyph: IconName,
147 command: SharedCommand,
148 run: &SharedRun,
149 ) -> impl IntoElement {
150 let run = run.clone();
151 Button::new(id)
152 .ghost()
153 .compact()
154 .icon(glyph)
155 .label(label)
156 .on_click(move |_, window, cx| run(command, window, cx))
157 }
158
159 fn header(scope: SharedScope, trailing: Option<AnyElement>, run: &SharedRun) -> Div {
160 h_flex()
161 .w_full()
162 .flex_none()
163 .px(px(SIDE_PADDING))
164 .py(px(10.))
165 .gap(px(12.))
166 .items_center()
167 .child(switch(scope, run))
168 .children(trailing)
169 }
170
171 fn crumb_trail(path: &LibraryPath, run: &SharedRun) -> Div {
172 let last = path.crumbs().len() - 1;
173 let mut trail = h_flex().flex_1().min_w_0().gap(px(4.)).items_center();
174 for (index, crumb) in path.crumbs().iter().enumerate() {
175 if index > 0 {
176 trail = trail.child(icon(IconName::ChevronRight, 12., theme::text_faint()));
177 }
178 let run = run.clone();
179 let current = index == last;
180 trail = trail.child(
181 div()
182 .id(ElementId::NamedInteger(
183 "library-crumb".into(),
184 index as u64,
185 ))
186 .px(px(4.))
187 .py(px(2.))
188 .rounded(px(4.))
189 .truncate()
190 .text_size(px(13.))
191 .font_weight(if current {
192 FontWeight::SEMIBOLD
193 } else {
194 FontWeight::NORMAL
195 })
196 .text_color(if current {
197 theme::text()
198 } else {
199 theme::text_muted()
200 })
201 .when(!current, |crumb| {
202 crumb
203 .cursor_pointer()
204 .hover(|crumb| crumb.bg(theme::row_hover()))
205 .on_click(move |_, window, cx| run(SharedCommand::Crumb(index), window, cx))
206 })
207 .child(crumb.name.clone()),
208 );
209 }
210 trail
211 }
212
213 fn column(width: Option<f32>) -> Div {
214 match width {
215 Some(width) => div().w(px(width)).flex_none().truncate(),
216 None => div().flex_1().min_w_0().truncate(),
217 }
218 }
219
220 fn column_header() -> Div {
221 h_flex()
222 .w_full()
223 .flex_none()
224 .h(px(28.))
225 .px(px(SIDE_PADDING))
226 .gap(px(12.))
227 .items_center()
228 .border_b_1()
229 .border_color(theme::border())
230 .text_size(px(11.5))
231 .font_weight(FontWeight::SEMIBOLD)
232 .text_color(theme::text_faint())
233 .child(column(None).pl(px(BADGE_SIZE + 10.)).child("Name"))
234 .child(column(Some(MODIFIED_WIDTH)).child("Modified"))
235 .child(column(Some(MODIFIED_BY_WIDTH)).child("Modified by"))
236 .child(column(Some(SIZE_WIDTH)).child("Size"))
237 }
238
239 fn entry_badge(entry: &DriveEntry) -> Div {
240 if entry.is_folder() {
241 return div()
242 .size(px(BADGE_SIZE))
243 .flex_none()
244 .flex()
245 .items_center()
246 .justify_center()
247 .child(icon(IconName::Folder, 22., theme::accent_text()));
248 }
249 file_badge(FileKind::from_name(&entry.name), BADGE_SIZE)
250 }
251
252 fn modified_text(entry: &DriveEntry) -> String {
253 entry.modified_at.map_or_else(String::new, |time| {
254 let now = Local::now();
255 format::list_time_label(time, now.date_naive(), now.offset().fix())
256 })
257 }
258
259 fn menu_icon(glyph: IconName) -> gpui_kit::component::Icon {
260 icon(glyph, MENU_ICON_SIZE, theme::text_muted())
261 }
262
263 fn entry_row(
264 index: usize,
265 entry: &DriveEntry,
266 download: Option<String>,
267 run: &SharedRun,
268 ) -> impl IntoElement {
269 let folder = entry.is_folder();
270 let (open_run, menu_run) = (run.clone(), run.clone());
271 let name = h_flex()
272 .flex_1()
273 .min_w_0()
274 .gap(px(10.))
275 .items_center()
276 .child(entry_badge(entry))
277 .child(
278 div()
279 .truncate()
280 .text_size(px(13.))
281 .text_color(theme::text())
282 .child(entry.name.clone()),
283 )
284 .children(download.map(|label| {
285 div()
286 .flex_none()
287 .text_size(px(11.5))
288 .text_color(theme::accent_text())
289 .child(label)
290 }));
291 h_flex()
292 .id(ElementId::NamedInteger("library-row".into(), index as u64))
293 .w_full()
294 .flex_none()
295 .h(px(ROW_HEIGHT))
296 .px(px(SIDE_PADDING))
297 .gap(px(12.))
298 .items_center()
299 .cursor_pointer()
300 .text_size(px(12.5))
301 .text_color(theme::text_muted())
302 .hover(|row| row.bg(theme::row_hover()))
303 .on_click(move |_, window, cx| open_run(SharedCommand::Open(index), window, cx))
304 .child(name)
305 .child(column(Some(MODIFIED_WIDTH)).child(modified_text(entry)))
306 .child(column(Some(MODIFIED_BY_WIDTH)).child(entry.modified_by.clone().unwrap_or_default()))
307 .child(column(Some(SIZE_WIDTH)).child(size_label(entry)))
308 .context_menu(move |popup, _, _| {
309 let item = |label: &'static str, glyph: IconName, command: SharedCommand| {
310 let run = menu_run.clone();
311 PopupMenuItem::new(label)
312 .icon(menu_icon(glyph))
313 .on_click(move |_, window, cx| run(command, window, cx))
314 };
315 let popup = popup.item(item(
316 "Open in browser",
317 IconName::ExternalLink,
318 SharedCommand::OpenInBrowser(index),
319 ));
320 let popup = if folder {
321 popup
322 } else {
323 popup.item(item(
324 "Download",
325 IconName::Download,
326 SharedCommand::Download(index),
327 ))
328 };
329 popup.item(item(
330 "Copy link",
331 IconName::Link,
332 SharedCommand::CopyLink(index),
333 ))
334 })
335 }
336
337 fn skeleton_rows() -> impl IntoElement {
338 v_flex().w_full().children((0..SKELETON_ROWS).map(|index| {
339 let bar = |width: f32| {
340 div()
341 .h(px(10.))
342 .w(px(width))
343 .rounded(px(5.))
344 .bg(theme::surface_raised())
345 };
346 h_flex()
347 .id(ElementId::NamedInteger(
348 "library-skeleton".into(),
349 index as u64,
350 ))
351 .w_full()
352 .h(px(ROW_HEIGHT))
353 .px(px(SIDE_PADDING))
354 .gap(px(12.))
355 .items_center()
356 .child(
357 h_flex()
358 .flex_1()
359 .gap(px(10.))
360 .items_center()
361 .child(
362 div()
363 .size(px(BADGE_SIZE))
364 .rounded(px(7.))
365 .bg(theme::surface_raised()),
366 )
367 .child(bar(140. + 30. * (index % 3) as f32)),
368 )
369 .child(column(Some(MODIFIED_WIDTH)).child(bar(50.)))
370 .child(column(Some(MODIFIED_BY_WIDTH)).child(bar(90.)))
371 .child(column(Some(SIZE_WIDTH)).child(bar(40.)))
372 }))
373 }
374
375 fn centered() -> Div {
376 div()
377 .w_full()
378 .flex_1()
379 .flex()
380 .items_center()
381 .justify_center()
382 .text_size(px(13.))
383 .text_color(theme::text_muted())
384 }
385
386 fn centered_note(text: &'static str) -> Div {
387 centered().child(text)
388 }
389
390 fn new_folder_row(input: &Entity<InputState>) -> Div {
391 h_flex()
392 .w_full()
393 .flex_none()
394 .px(px(SIDE_PADDING))
395 .pb(px(8.))
396 .gap(px(8.))
397 .items_center()
398 .child(icon(IconName::Folder, 18., theme::accent_text()))
399 .child(
400 div()
401 .w(px(NEW_FOLDER_WIDTH))
402 .h(px(30.))
403 .px(px(2.))
404 .flex()
405 .items_center()
406 .rounded(px(8.))
407 .bg(theme::surface())
408 .border_1()
409 .border_color(theme::accent())
410 .child(Input::new(input).appearance(false).bordered(false)),
411 )
412 .child(
413 div()
414 .text_size(px(11.5))
415 .text_color(theme::text_faint())
416 .child("Enter to create, Esc to cancel"),
417 )
418 }
419
420 pub fn render_library(view: LibraryView, run: &SharedRun) -> AnyElement {
421 let toolbar = view.path.map(|path| {
422 h_flex()
423 .flex_1()
424 .min_w_0()
425 .gap(px(4.))
426 .items_center()
427 .child(crumb_trail(path, run))
428 .child(tool_button(
429 "library-new-folder",
430 "New folder",
431 IconName::Plus,
432 SharedCommand::ToggleNewFolder,
433 run,
434 ))
435 .child(tool_button(
436 "library-upload",
437 "Upload",
438 IconName::Upload,
439 SharedCommand::Upload,
440 run,
441 ))
442 .child(tool_button(
443 "library-open-sharepoint",
444 "Open in SharePoint \u{2197}",
445 IconName::ExternalLink,
446 SharedCommand::OpenSharePoint,
447 run,
448 ))
449 .into_any_element()
450 });
451 let body = match view.listing {
452 Listing::Loading => skeleton_rows().into_any_element(),
453 Listing::Failed(reason) => {
454 let retry = run.clone();
455 centered()
456 .flex_col()
457 .gap(px(8.))
458 .child(
459 div()
460 .text_color(theme::red_soft())
461 .child(format!("Could not load the files: {reason}")),
462 )
463 .child(
464 Button::new("library-retry")
465 .ghost()
466 .compact()
467 .label("Retry")
468 .on_click(move |_, window, cx| retry(SharedCommand::Retry, window, cx)),
469 )
470 .into_any_element()
471 }
472 Listing::Ready(entries) if entries.is_empty() => {
473 centered_note(EMPTY_LIBRARY).into_any_element()
474 }
475 Listing::Ready(entries) => v_flex()
476 .id("library-rows")
477 .w_full()
478 .flex_1()
479 .min_h_0()
480 .overflow_y_scroll()
481 .children(entries.iter().enumerate().map(|(index, entry)| {
482 let download = view
483 .download_states
484 .get(index)
485 .and_then(|state| download_label(state.as_ref()));
486 entry_row(index, entry, download, run)
487 }))
488 .into_any_element(),
489 };
490 v_flex()
491 .size_full()
492 .child(header(SharedScope::Library, toolbar, run))
493 .children(view.new_folder.map(new_folder_row))
494 .children(view.status.map(|status| {
495 div()
496 .px(px(SIDE_PADDING))
497 .pb(px(6.))
498 .text_size(px(12.))
499 .text_color(theme::accent_text())
500 .child(status.to_owned())
501 }))
502 .child(column_header())
503 .child(body)
504 .into_any_element()
505 }
506
507 fn chip(
508 id: &'static str,
509 label: &'static str,
510 active: bool,
511 command: SharedCommand,
512 run: &SharedRun,
513 ) -> Stateful<Div> {
514 let run = run.clone();
515 div()
516 .id(id)
517 .px(px(12.))
518 .py(px(4.))
519 .rounded_full()
520 .cursor_pointer()
521 .text_size(px(12.))
522 .border_1()
523 .border_color(if active {
524 theme::accent()
525 } else {
526 theme::border_strong()
527 })
528 .text_color(if active {
529 theme::accent_text()
530 } else {
531 theme::text_muted()
532 })
533 .when(active, |chip| chip.bg(theme::accent_soft().opacity(0.12)))
534 .on_click(move |_, window, cx| run(command, window, cx))
535 .child(label)
536 }
537
538 fn chips(filter: MessageFilter, run: &SharedRun) -> AnyElement {
539 h_flex()
540 .gap(px(8.))
541 .child(chip(
542 "shared-filter-all",
543 "All",
544 filter == MessageFilter::All,
545 SharedCommand::Filter(MessageFilter::All),
546 run,
547 ))
548 .child(chip(
549 "shared-filter-files",
550 "Files",
551 filter == MessageFilter::Files,
552 SharedCommand::Filter(MessageFilter::Files),
553 run,
554 ))
555 .child(chip(
556 "shared-filter-links",
557 "Links",
558 filter == MessageFilter::Links,
559 SharedCommand::Filter(MessageFilter::Links),
560 run,
561 ))
562 .into_any_element()
563 }
564
565 fn item_badge(item: &SharedItem) -> Div {
566 match &item.content {
567 SharedContent::File(card) => file_badge(card.kind, BADGE_SIZE),
568 SharedContent::Link(_) => div()
569 .size(px(BADGE_SIZE))
570 .flex_none()
571 .flex()
572 .items_center()
573 .justify_center()
574 .rounded(px(7.))
575 .bg(theme::surface_raised())
576 .child(icon(IconName::Link, 14., theme::text_muted())),
577 }
578 }
579
580 fn item_row(
581 index: usize,
582 item: &SharedItem,
583 download: Option<String>,
584 run: &SharedRun,
585 ) -> Stateful<Div> {
586 let (open_run, post_run) = (run.clone(), run.clone());
587 let post =
588 (!item.post_label.is_empty()).then(|| format!("\u{201c}{}\u{201d}", item.post_label));
589 let source = h_flex()
590 .gap(px(4.))
591 .text_size(px(12.))
592 .text_color(theme::text_muted())
593 .child(format!("{} in", item.author))
594 .children(post.map(|label| {
595 div()
596 .id(ElementId::NamedInteger("shared-post".into(), index as u64))
597 .truncate()
598 .cursor_pointer()
599 .hover(|post| post.text_color(theme::accent_text()))
600 .on_click(move |_, window, cx| {
601 cx.stop_propagation();
602 post_run(SharedCommand::JumpToPost(index), window, cx)
603 })
604 .child(label)
605 }));
606 h_flex()
607 .id(ElementId::NamedInteger("shared-item".into(), index as u64))
608 .w_full()
609 .flex_none()
610 .px(px(SIDE_PADDING))
611 .py(px(6.))
612 .gap(px(10.))
613 .items_center()
614 .cursor_pointer()
615 .hover(|row| row.bg(theme::row_hover()))
616 .on_click(move |_, window, cx| open_run(SharedCommand::OpenItem(index), window, cx))
617 .child(item_badge(item))
618 .child(
619 v_flex()
620 .flex_1()
621 .min_w_0()
622 .child(
623 div()
624 .truncate()
625 .text_size(px(13.))
626 .text_color(theme::text())
627 .child(item.name().to_owned()),
628 )
629 .child(source),
630 )
631 .children(download.map(|label| {
632 div()
633 .flex_none()
634 .text_size(px(11.5))
635 .text_color(theme::accent_text())
636 .child(label)
637 }))
638 }
639
640 pub fn render_messages(view: MessagesView, run: &SharedRun) -> AnyElement {
641 let now = Local::now();
642 let groups = grouped_items(
643 view.items,
644 view.filter,
645 now.date_naive(),
646 now.offset().fix(),
647 );
648 let body = if groups.is_empty() {
649 centered_note(EMPTY_MESSAGES).into_any_element()
650 } else {
651 v_flex()
652 .id("shared-messages")
653 .w_full()
654 .flex_1()
655 .min_h_0()
656 .overflow_y_scroll()
657 .children(groups.into_iter().map(|(group, indices)| {
658 v_flex()
659 .w_full()
660 .child(
661 div()
662 .px(px(SIDE_PADDING))
663 .pt(px(10.))
664 .pb(px(4.))
665 .text_size(px(11.5))
666 .font_weight(FontWeight::SEMIBOLD)
667 .text_color(theme::text_faint())
668 .child(group.label()),
669 )
670 .children(indices.into_iter().map(|index| {
671 let download = view
672 .download_states
673 .get(index)
674 .and_then(|state| download_label(state.as_ref()));
675 item_row(index, &view.items[index], download, run)
676 }))
677 }))
678 .into_any_element()
679 };
680 v_flex()
681 .size_full()
682 .child(header(
683 SharedScope::Messages,
684 Some(chips(view.filter, run)),
685 run,
686 ))
687 .child(body)
688 .into_any_element()
689 }
@@ -0,0 +1,689 @@
1use std::rc::Rc;
2
3use chrono::{Local, Offset as _};
4use gpui_kit::assets::IconName;
5use gpui_kit::component::{
6 button::{Button, ButtonVariants as _},
7 h_flex,
8 input::{Input, InputState},
9 menu::{ContextMenuExt as _, PopupMenuItem},
10 v_flex,
11};
12use gpui_kit::prelude::FluentBuilder as _;
13use gpui_kit::*;
14use teams_core::{DriveEntry, FileKind};
15
16use super::attachments::file_badge;
17use super::widgets::icon;
18use crate::channel_files::{
19 LibraryPath, MessageFilter, SharedContent, SharedItem, grouped_items, size_label,
20};
21use crate::downloads::{DownloadState, percent_label};
22use crate::format;
23use crate::theme;
24
25const SIDE_PADDING: f32 = 24.;
26const ROW_HEIGHT: f32 = 40.;
27const BADGE_SIZE: f32 = 26.;
28const MODIFIED_WIDTH: f32 = 110.;
29const MODIFIED_BY_WIDTH: f32 = 160.;
30const SIZE_WIDTH: f32 = 90.;
31const SKELETON_ROWS: usize = 6;
32const NEW_FOLDER_WIDTH: f32 = 220.;
33const MENU_ICON_SIZE: f32 = 14.;
34
35pub const EMPTY_LIBRARY: &str = "No files yet. Upload or drop files here.";
36pub const EMPTY_MESSAGES: &str = "No files or links shared in this channel yet.";
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum SharedScope {
40 Library,
41 Messages,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum SharedCommand {
46 Scope(SharedScope),
47 Filter(MessageFilter),
48 Crumb(usize),
49 Open(usize),
50 OpenInBrowser(usize),
51 Download(usize),
52 CopyLink(usize),
53 Retry,
54 ToggleNewFolder,
55 Upload,
56 OpenSharePoint,
57 OpenItem(usize),
58 JumpToPost(usize),
59}
60
61pub type SharedRun = Rc<dyn Fn(SharedCommand, &mut Window, &mut App)>;
62
63pub enum Listing {
64 Loading,
65 Failed(String),
66 Ready(Vec<DriveEntry>),
67}
68
69pub struct LibraryView<'a> {
70 pub path: Option<&'a LibraryPath>,
71 pub listing: &'a Listing,
72 pub new_folder: Option<&'a Entity<InputState>>,
73 pub status: Option<&'a str>,
74 pub download_states: Vec<Option<DownloadState>>,
75}
76
77pub struct MessagesView<'a> {
78 pub items: &'a [SharedItem],
79 pub filter: MessageFilter,
80 pub download_states: Vec<Option<DownloadState>>,
81}
82
83pub fn download_label(state: Option<&DownloadState>) -> Option<String> {
84 match state? {
85 DownloadState::Saving(percent) => Some(percent_label(*percent)),
86 DownloadState::Saved(_) => Some("Saved".to_owned()),
87 DownloadState::Failed(_) => Some("Failed, click to retry".to_owned()),
88 }
89}
90
91fn segment(
92 id: &'static str,
93 label: &'static str,
94 active: bool,
95 command: SharedCommand,
96 run: &SharedRun,
97) -> Stateful<Div> {
98 let run = run.clone();
99 div()
100 .id(id)
101 .px(px(14.))
102 .py(px(5.))
103 .rounded(px(6.))
104 .cursor_pointer()
105 .text_size(px(12.5))
106 .font_weight(if active {
107 FontWeight::SEMIBOLD
108 } else {
109 FontWeight::NORMAL
110 })
111 .text_color(if active {
112 theme::text()
113 } else {
114 theme::text_muted()
115 })
116 .when(active, |segment| segment.bg(theme::border_strong()))
117 .on_click(move |_, window, cx| run(command, window, cx))
118 .child(label)
119}
120
121fn switch(scope: SharedScope, run: &SharedRun) -> Div {
122 h_flex()
123 .p(px(2.))
124 .gap(px(2.))
125 .rounded(px(8.))
126 .bg(theme::surface_raised())
127 .child(segment(
128 "shared-in-library",
129 "In library",
130 scope == SharedScope::Library,
131 SharedCommand::Scope(SharedScope::Library),
132 run,
133 ))
134 .child(segment(
135 "shared-in-messages",
136 "In messages",
137 scope == SharedScope::Messages,
138 SharedCommand::Scope(SharedScope::Messages),
139 run,
140 ))
141}
142
143fn tool_button(
144 id: &'static str,
145 label: &'static str,
146 glyph: IconName,
147 command: SharedCommand,
148 run: &SharedRun,
149) -> impl IntoElement {
150 let run = run.clone();
151 Button::new(id)
152 .ghost()
153 .compact()
154 .icon(glyph)
155 .label(label)
156 .on_click(move |_, window, cx| run(command, window, cx))
157}
158
159fn header(scope: SharedScope, trailing: Option<AnyElement>, run: &SharedRun) -> Div {
160 h_flex()
161 .w_full()
162 .flex_none()
163 .px(px(SIDE_PADDING))
164 .py(px(10.))
165 .gap(px(12.))
166 .items_center()
167 .child(switch(scope, run))
168 .children(trailing)
169}
170
171fn crumb_trail(path: &LibraryPath, run: &SharedRun) -> Div {
172 let last = path.crumbs().len() - 1;
173 let mut trail = h_flex().flex_1().min_w_0().gap(px(4.)).items_center();
174 for (index, crumb) in path.crumbs().iter().enumerate() {
175 if index > 0 {
176 trail = trail.child(icon(IconName::ChevronRight, 12., theme::text_faint()));
177 }
178 let run = run.clone();
179 let current = index == last;
180 trail = trail.child(
181 div()
182 .id(ElementId::NamedInteger(
183 "library-crumb".into(),
184 index as u64,
185 ))
186 .px(px(4.))
187 .py(px(2.))
188 .rounded(px(4.))
189 .truncate()
190 .text_size(px(13.))
191 .font_weight(if current {
192 FontWeight::SEMIBOLD
193 } else {
194 FontWeight::NORMAL
195 })
196 .text_color(if current {
197 theme::text()
198 } else {
199 theme::text_muted()
200 })
201 .when(!current, |crumb| {
202 crumb
203 .cursor_pointer()
204 .hover(|crumb| crumb.bg(theme::row_hover()))
205 .on_click(move |_, window, cx| run(SharedCommand::Crumb(index), window, cx))
206 })
207 .child(crumb.name.clone()),
208 );
209 }
210 trail
211}
212
213fn column(width: Option<f32>) -> Div {
214 match width {
215 Some(width) => div().w(px(width)).flex_none().truncate(),
216 None => div().flex_1().min_w_0().truncate(),
217 }
218}
219
220fn column_header() -> Div {
221 h_flex()
222 .w_full()
223 .flex_none()
224 .h(px(28.))
225 .px(px(SIDE_PADDING))
226 .gap(px(12.))
227 .items_center()
228 .border_b_1()
229 .border_color(theme::border())
230 .text_size(px(11.5))
231 .font_weight(FontWeight::SEMIBOLD)
232 .text_color(theme::text_faint())
233 .child(column(None).pl(px(BADGE_SIZE + 10.)).child("Name"))
234 .child(column(Some(MODIFIED_WIDTH)).child("Modified"))
235 .child(column(Some(MODIFIED_BY_WIDTH)).child("Modified by"))
236 .child(column(Some(SIZE_WIDTH)).child("Size"))
237}
238
239fn entry_badge(entry: &DriveEntry) -> Div {
240 if entry.is_folder() {
241 return div()
242 .size(px(BADGE_SIZE))
243 .flex_none()
244 .flex()
245 .items_center()
246 .justify_center()
247 .child(icon(IconName::Folder, 22., theme::accent_text()));
248 }
249 file_badge(FileKind::from_name(&entry.name), BADGE_SIZE)
250}
251
252fn modified_text(entry: &DriveEntry) -> String {
253 entry.modified_at.map_or_else(String::new, |time| {
254 let now = Local::now();
255 format::list_time_label(time, now.date_naive(), now.offset().fix())
256 })
257}
258
259fn menu_icon(glyph: IconName) -> gpui_kit::component::Icon {
260 icon(glyph, MENU_ICON_SIZE, theme::text_muted())
261}
262
263fn entry_row(
264 index: usize,
265 entry: &DriveEntry,
266 download: Option<String>,
267 run: &SharedRun,
268) -> impl IntoElement {
269 let folder = entry.is_folder();
270 let (open_run, menu_run) = (run.clone(), run.clone());
271 let name = h_flex()
272 .flex_1()
273 .min_w_0()
274 .gap(px(10.))
275 .items_center()
276 .child(entry_badge(entry))
277 .child(
278 div()
279 .truncate()
280 .text_size(px(13.))
281 .text_color(theme::text())
282 .child(entry.name.clone()),
283 )
284 .children(download.map(|label| {
285 div()
286 .flex_none()
287 .text_size(px(11.5))
288 .text_color(theme::accent_text())
289 .child(label)
290 }));
291 h_flex()
292 .id(ElementId::NamedInteger("library-row".into(), index as u64))
293 .w_full()
294 .flex_none()
295 .h(px(ROW_HEIGHT))
296 .px(px(SIDE_PADDING))
297 .gap(px(12.))
298 .items_center()
299 .cursor_pointer()
300 .text_size(px(12.5))
301 .text_color(theme::text_muted())
302 .hover(|row| row.bg(theme::row_hover()))
303 .on_click(move |_, window, cx| open_run(SharedCommand::Open(index), window, cx))
304 .child(name)
305 .child(column(Some(MODIFIED_WIDTH)).child(modified_text(entry)))
306 .child(column(Some(MODIFIED_BY_WIDTH)).child(entry.modified_by.clone().unwrap_or_default()))
307 .child(column(Some(SIZE_WIDTH)).child(size_label(entry)))
308 .context_menu(move |popup, _, _| {
309 let item = |label: &'static str, glyph: IconName, command: SharedCommand| {
310 let run = menu_run.clone();
311 PopupMenuItem::new(label)
312 .icon(menu_icon(glyph))
313 .on_click(move |_, window, cx| run(command, window, cx))
314 };
315 let popup = popup.item(item(
316 "Open in browser",
317 IconName::ExternalLink,
318 SharedCommand::OpenInBrowser(index),
319 ));
320 let popup = if folder {
321 popup
322 } else {
323 popup.item(item(
324 "Download",
325 IconName::Download,
326 SharedCommand::Download(index),
327 ))
328 };
329 popup.item(item(
330 "Copy link",
331 IconName::Link,
332 SharedCommand::CopyLink(index),
333 ))
334 })
335}
336
337fn skeleton_rows() -> impl IntoElement {
338 v_flex().w_full().children((0..SKELETON_ROWS).map(|index| {
339 let bar = |width: f32| {
340 div()
341 .h(px(10.))
342 .w(px(width))
343 .rounded(px(5.))
344 .bg(theme::surface_raised())
345 };
346 h_flex()
347 .id(ElementId::NamedInteger(
348 "library-skeleton".into(),
349 index as u64,
350 ))
351 .w_full()
352 .h(px(ROW_HEIGHT))
353 .px(px(SIDE_PADDING))
354 .gap(px(12.))
355 .items_center()
356 .child(
357 h_flex()
358 .flex_1()
359 .gap(px(10.))
360 .items_center()
361 .child(
362 div()
363 .size(px(BADGE_SIZE))
364 .rounded(px(7.))
365 .bg(theme::surface_raised()),
366 )
367 .child(bar(140. + 30. * (index % 3) as f32)),
368 )
369 .child(column(Some(MODIFIED_WIDTH)).child(bar(50.)))
370 .child(column(Some(MODIFIED_BY_WIDTH)).child(bar(90.)))
371 .child(column(Some(SIZE_WIDTH)).child(bar(40.)))
372 }))
373}
374
375fn centered() -> Div {
376 div()
377 .w_full()
378 .flex_1()
379 .flex()
380 .items_center()
381 .justify_center()
382 .text_size(px(13.))
383 .text_color(theme::text_muted())
384}
385
386fn centered_note(text: &'static str) -> Div {
387 centered().child(text)
388}
389
390fn new_folder_row(input: &Entity<InputState>) -> Div {
391 h_flex()
392 .w_full()
393 .flex_none()
394 .px(px(SIDE_PADDING))
395 .pb(px(8.))
396 .gap(px(8.))
397 .items_center()
398 .child(icon(IconName::Folder, 18., theme::accent_text()))
399 .child(
400 div()
401 .w(px(NEW_FOLDER_WIDTH))
402 .h(px(30.))
403 .px(px(2.))
404 .flex()
405 .items_center()
406 .rounded(px(8.))
407 .bg(theme::surface())
408 .border_1()
409 .border_color(theme::accent())
410 .child(Input::new(input).appearance(false).bordered(false)),
411 )
412 .child(
413 div()
414 .text_size(px(11.5))
415 .text_color(theme::text_faint())
416 .child("Enter to create, Esc to cancel"),
417 )
418}
419
420pub fn render_library(view: LibraryView, run: &SharedRun) -> AnyElement {
421 let toolbar = view.path.map(|path| {
422 h_flex()
423 .flex_1()
424 .min_w_0()
425 .gap(px(4.))
426 .items_center()
427 .child(crumb_trail(path, run))
428 .child(tool_button(
429 "library-new-folder",
430 "New folder",
431 IconName::Plus,
432 SharedCommand::ToggleNewFolder,
433 run,
434 ))
435 .child(tool_button(
436 "library-upload",
437 "Upload",
438 IconName::Upload,
439 SharedCommand::Upload,
440 run,
441 ))
442 .child(tool_button(
443 "library-open-sharepoint",
444 "Open in SharePoint \u{2197}",
445 IconName::ExternalLink,
446 SharedCommand::OpenSharePoint,
447 run,
448 ))
449 .into_any_element()
450 });
451 let body = match view.listing {
452 Listing::Loading => skeleton_rows().into_any_element(),
453 Listing::Failed(reason) => {
454 let retry = run.clone();
455 centered()
456 .flex_col()
457 .gap(px(8.))
458 .child(
459 div()
460 .text_color(theme::red_soft())
461 .child(format!("Could not load the files: {reason}")),
462 )
463 .child(
464 Button::new("library-retry")
465 .ghost()
466 .compact()
467 .label("Retry")
468 .on_click(move |_, window, cx| retry(SharedCommand::Retry, window, cx)),
469 )
470 .into_any_element()
471 }
472 Listing::Ready(entries) if entries.is_empty() => {
473 centered_note(EMPTY_LIBRARY).into_any_element()
474 }
475 Listing::Ready(entries) => v_flex()
476 .id("library-rows")
477 .w_full()
478 .flex_1()
479 .min_h_0()
480 .overflow_y_scroll()
481 .children(entries.iter().enumerate().map(|(index, entry)| {
482 let download = view
483 .download_states
484 .get(index)
485 .and_then(|state| download_label(state.as_ref()));
486 entry_row(index, entry, download, run)
487 }))
488 .into_any_element(),
489 };
490 v_flex()
491 .size_full()
492 .child(header(SharedScope::Library, toolbar, run))
493 .children(view.new_folder.map(new_folder_row))
494 .children(view.status.map(|status| {
495 div()
496 .px(px(SIDE_PADDING))
497 .pb(px(6.))
498 .text_size(px(12.))
499 .text_color(theme::accent_text())
500 .child(status.to_owned())
501 }))
502 .child(column_header())
503 .child(body)
504 .into_any_element()
505}
506
507fn chip(
508 id: &'static str,
509 label: &'static str,
510 active: bool,
511 command: SharedCommand,
512 run: &SharedRun,
513) -> Stateful<Div> {
514 let run = run.clone();
515 div()
516 .id(id)
517 .px(px(12.))
518 .py(px(4.))
519 .rounded_full()
520 .cursor_pointer()
521 .text_size(px(12.))
522 .border_1()
523 .border_color(if active {
524 theme::accent()
525 } else {
526 theme::border_strong()
527 })
528 .text_color(if active {
529 theme::accent_text()
530 } else {
531 theme::text_muted()
532 })
533 .when(active, |chip| chip.bg(theme::accent_soft().opacity(0.12)))
534 .on_click(move |_, window, cx| run(command, window, cx))
535 .child(label)
536}
537
538fn chips(filter: MessageFilter, run: &SharedRun) -> AnyElement {
539 h_flex()
540 .gap(px(8.))
541 .child(chip(
542 "shared-filter-all",
543 "All",
544 filter == MessageFilter::All,
545 SharedCommand::Filter(MessageFilter::All),
546 run,
547 ))
548 .child(chip(
549 "shared-filter-files",
550 "Files",
551 filter == MessageFilter::Files,
552 SharedCommand::Filter(MessageFilter::Files),
553 run,
554 ))
555 .child(chip(
556 "shared-filter-links",
557 "Links",
558 filter == MessageFilter::Links,
559 SharedCommand::Filter(MessageFilter::Links),
560 run,
561 ))
562 .into_any_element()
563}
564
565fn item_badge(item: &SharedItem) -> Div {
566 match &item.content {
567 SharedContent::File(card) => file_badge(card.kind, BADGE_SIZE),
568 SharedContent::Link(_) => div()
569 .size(px(BADGE_SIZE))
570 .flex_none()
571 .flex()
572 .items_center()
573 .justify_center()
574 .rounded(px(7.))
575 .bg(theme::surface_raised())
576 .child(icon(IconName::Link, 14., theme::text_muted())),
577 }
578}
579
580fn item_row(
581 index: usize,
582 item: &SharedItem,
583 download: Option<String>,
584 run: &SharedRun,
585) -> Stateful<Div> {
586 let (open_run, post_run) = (run.clone(), run.clone());
587 let post =
588 (!item.post_label.is_empty()).then(|| format!("\u{201c}{}\u{201d}", item.post_label));
589 let source = h_flex()
590 .gap(px(4.))
591 .text_size(px(12.))
592 .text_color(theme::text_muted())
593 .child(format!("{} in", item.author))
594 .children(post.map(|label| {
595 div()
596 .id(ElementId::NamedInteger("shared-post".into(), index as u64))
597 .truncate()
598 .cursor_pointer()
599 .hover(|post| post.text_color(theme::accent_text()))
600 .on_click(move |_, window, cx| {
601 cx.stop_propagation();
602 post_run(SharedCommand::JumpToPost(index), window, cx)
603 })
604 .child(label)
605 }));
606 h_flex()
607 .id(ElementId::NamedInteger("shared-item".into(), index as u64))
608 .w_full()
609 .flex_none()
610 .px(px(SIDE_PADDING))
611 .py(px(6.))
612 .gap(px(10.))
613 .items_center()
614 .cursor_pointer()
615 .hover(|row| row.bg(theme::row_hover()))
616 .on_click(move |_, window, cx| open_run(SharedCommand::OpenItem(index), window, cx))
617 .child(item_badge(item))
618 .child(
619 v_flex()
620 .flex_1()
621 .min_w_0()
622 .child(
623 div()
624 .truncate()
625 .text_size(px(13.))
626 .text_color(theme::text())
627 .child(item.name().to_owned()),
628 )
629 .child(source),
630 )
631 .children(download.map(|label| {
632 div()
633 .flex_none()
634 .text_size(px(11.5))
635 .text_color(theme::accent_text())
636 .child(label)
637 }))
638}
639
640pub fn render_messages(view: MessagesView, run: &SharedRun) -> AnyElement {
641 let now = Local::now();
642 let groups = grouped_items(
643 view.items,
644 view.filter,
645 now.date_naive(),
646 now.offset().fix(),
647 );
648 let body = if groups.is_empty() {
649 centered_note(EMPTY_MESSAGES).into_any_element()
650 } else {
651 v_flex()
652 .id("shared-messages")
653 .w_full()
654 .flex_1()
655 .min_h_0()
656 .overflow_y_scroll()
657 .children(groups.into_iter().map(|(group, indices)| {
658 v_flex()
659 .w_full()
660 .child(
661 div()
662 .px(px(SIDE_PADDING))
663 .pt(px(10.))
664 .pb(px(4.))
665 .text_size(px(11.5))
666 .font_weight(FontWeight::SEMIBOLD)
667 .text_color(theme::text_faint())
668 .child(group.label()),
669 )
670 .children(indices.into_iter().map(|index| {
671 let download = view
672 .download_states
673 .get(index)
674 .and_then(|state| download_label(state.as_ref()));
675 item_row(index, &view.items[index], download, run)
676 }))
677 }))
678 .into_any_element()
679 };
680 v_flex()
681 .size_full()
682 .child(header(
683 SharedScope::Messages,
684 Some(chips(view.filter, run)),
685 run,
686 ))
687 .child(body)
688 .into_any_element()
689}
crates/app/src/views/shell.rs +16 −3
@@ -15,6 +15,7 @@ use super::switcher::{Switcher, SwitcherEvent, candidates_from};
15 15 use super::title_bar::render_title_bar;
16 16 use crate::activity::ActivityCenter;
17 17 use crate::app_state::{AppEvent, AppState, Selection};
18 use crate::embedded_web::Overlays;
18 19 use crate::notice::NoticeAction;
19 20 use crate::notify::{NotificationCenter, selection_for};
20 21 use crate::theme;
@@ -384,12 +385,13 @@ impl AppShell {
384 385 return;
385 386 };
386 387 if let Some(card) = &self.profile_card {
387 card.update(cx, |card, cx| card.move_to(request.user_id, request.anchor, cx));
388 card.update(cx, |card, cx| {
389 card.move_to(request.user_id, request.anchor, cx)
390 });
388 391 return;
389 392 }
390 393 let app = self.state.clone();
391 let card =
392 cx.new(|cx| ProfileCard::new(app, request.user_id, request.anchor, window, cx));
394 let card = cx.new(|cx| ProfileCard::new(app, request.user_id, request.anchor, window, cx));
393 395 cx.subscribe_in(
394 396 &card,
395 397 window,
@@ -463,6 +465,17 @@ impl Render for AppShell {
463 465 });
464 466 });
465 467 }
468 let panels = self.switcher.is_some()
469 || self.activity_panel.is_some()
470 || self.saved_panel.is_some()
471 || self.forward_dialog.is_some()
472 || self.status_dialog.is_some()
473 || self.profile_card.is_some()
474 || {
475 let state = self.state.read(cx);
476 state.task_dialog.is_some() || state.status_menu_open
477 };
478 Overlays::update(cx, |overlays| overlays.panels = panels);
466 479 let state = self.state.read(cx);
467 480 let status = render_status_bar(
468 481 state,
@@ -15,6 +15,7 @@ use super::switcher::{Switcher, SwitcherEvent, candidates_from};
15use super::title_bar::render_title_bar;
15use super::title_bar::render_title_bar;
16use crate::activity::ActivityCenter;
16use crate::activity::ActivityCenter;
17use crate::app_state::{AppEvent, AppState, Selection};
17use crate::app_state::{AppEvent, AppState, Selection};
18use crate::embedded_web::Overlays;
18use crate::notice::NoticeAction;
19use crate::notice::NoticeAction;
19use crate::notify::{NotificationCenter, selection_for};
20use crate::notify::{NotificationCenter, selection_for};
20use crate::theme;
21use crate::theme;
@@ -384,12 +385,13 @@ impl AppShell {
384 return;
385 return;
385 };
386 };
386 if let Some(card) = &self.profile_card {
387 if let Some(card) = &self.profile_card {
387 card.update(cx, |card, cx| card.move_to(request.user_id, request.anchor, cx));
388 card.update(cx, |card, cx| {
389 card.move_to(request.user_id, request.anchor, cx)
390 });
388 return;
391 return;
389 }
392 }
390 let app = self.state.clone();
393 let app = self.state.clone();
391 let card =
394 let card = cx.new(|cx| ProfileCard::new(app, request.user_id, request.anchor, window, cx));
392 cx.new(|cx| ProfileCard::new(app, request.user_id, request.anchor, window, cx));
393 cx.subscribe_in(
395 cx.subscribe_in(
394 &card,
396 &card,
395 window,
397 window,
@@ -463,6 +465,17 @@ impl Render for AppShell {
463 });
465 });
464 });
466 });
465 }
467 }
468 let panels = self.switcher.is_some()
469 || self.activity_panel.is_some()
470 || self.saved_panel.is_some()
471 || self.forward_dialog.is_some()
472 || self.status_dialog.is_some()
473 || self.profile_card.is_some()
474 || {
475 let state = self.state.read(cx);
476 state.task_dialog.is_some() || state.status_menu_open
477 };
478 Overlays::update(cx, |overlays| overlays.panels = panels);
466 let state = self.state.read(cx);
479 let state = self.state.read(cx);
467 let status = render_status_bar(
480 let status = render_status_bar(
468 state,
481 state,
crates/app/src/views/sidebar.rs +95 −36
@@ -8,10 +8,12 @@ use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenu, PopupMenuItem};
8 8 use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
9 9 use gpui_kit::prelude::FluentBuilder as _;
10 10 use gpui_kit::*;
11 use store::{ChannelRecord, SidebarTeam, Store, TeamRecord};
11 use store::{
12 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,
13 };
12 14
13 15 use super::avatar::{spec_avatar, square_avatar, with_presence};
14 use super::widgets::{count_badge, dot, icon, symbol, unread_marker};
16 use super::widgets::{count_badge, dot, icon, unread_marker};
15 17 use crate::app_state::{AppEvent, AppState, Selection};
16 18 use crate::chat_actions::TITLE_LIMIT;
17 19 use crate::data::{Directory, FolderKind};
@@ -43,6 +45,7 @@ const REVEAL_ROW_HEIGHT: f32 = 32.;
43 45 const NEW_CHAT_BUTTON_SIZE: f32 = 34.;
44 46 const MENU_ICON_SIZE: f32 = 15.;
45 47 const MUTED_ICON_SIZE: f32 = 13.;
48 const NOTIFICATION_ICON_SIZE: f32 = 13.;
46 49
47 50 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
48 51 enum SidebarTab {
@@ -883,7 +886,7 @@ impl SidebarView {
883 886 team: &TeamRecord,
884 887 channel: &ChannelRecord,
885 888 selected: bool,
886 followed: bool,
889 notifications: ChannelNotifications,
887 890 ) -> AnyElement {
888 891 let unread = channel.unread;
889 892 let state = self.state.clone();
@@ -933,7 +936,7 @@ impl SidebarView {
933 936 .text_color(theme::text())
934 937 .child(format!("{} / {}", team.name, channel.name)),
935 938 )
936 .when(followed, |line| line.child(followed_bell()))
939 .children(notification_badge(notifications.level))
937 940 .child(
938 941 div()
939 942 .flex_none()
@@ -966,12 +969,15 @@ impl SidebarView {
966 969 let selection = selection.clone();
967 970 state.update(cx, |state, cx| state.select(selection, cx));
968 971 })
969 .context_menu(move |popup, _, _| {
970 popup.item(follow_item(
972 .context_menu(move |popup, window, cx| {
973 channel_menu(
974 popup,
975 window,
976 cx,
971 977 menu_state.clone(),
972 menu_channel_id.clone(),
973 followed,
974 ))
978 &menu_channel_id,
979 notifications,
980 )
975 981 })
976 982 .into_any_element()
977 983 }
@@ -996,7 +1002,6 @@ impl SidebarView {
996 1002 selected: Option<&Selection>,
997 1003 cx: &mut Context<Self>,
998 1004 ) -> Div {
999 let followed = self.state.read(cx).followed_channels.clone();
1000 1005 let team_id = entry.team.id.clone();
1001 1006 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1002 1007 let unread = entry.channels.iter().any(|channel| channel.unread);
@@ -1059,7 +1064,7 @@ impl SidebarView {
1059 1064 list = list.child(self.team_channel_row(
1060 1065 channel,
1061 1066 is_selected(channel),
1062 followed.contains(&channel.id),
1067 entry.channel_notifications(&channel.id),
1063 1068 ));
1064 1069 }
1065 1070 let hidden: Vec<&ChannelRecord> = entry
@@ -1089,7 +1094,7 @@ impl SidebarView {
1089 1094 list = list.child(self.team_channel_row(
1090 1095 channel,
1091 1096 false,
1092 followed.contains(&channel.id),
1097 entry.channel_notifications(&channel.id),
1093 1098 ));
1094 1099 }
1095 1100 }
@@ -1137,7 +1142,7 @@ impl SidebarView {
1137 1142 &self,
1138 1143 channel: &ChannelRecord,
1139 1144 is_selected: bool,
1140 followed: bool,
1145 notifications: ChannelNotifications,
1141 1146 ) -> impl IntoElement {
1142 1147 let state = self.state.clone();
1143 1148 let menu_state = self.state.clone();
@@ -1180,33 +1185,35 @@ impl SidebarView {
1180 1185 .text_color(theme::text())
1181 1186 .child(channel.name.clone()),
1182 1187 )
1183 .when(followed, |row| row.child(followed_bell()))
1188 .children(notification_badge(notifications.level))
1184 1189 .when(channel.unread, |row| row.child(dot(7.)))
1185 1190 .on_click(move |_, _, cx| {
1186 1191 let selection = selection.clone();
1187 1192 state.update(cx, |state, cx| state.select(selection, cx));
1188 1193 })
1189 .context_menu(move |popup, _, _| {
1190 popup.item(follow_item(
1194 .context_menu(move |popup, window, cx| {
1195 channel_menu(
1196 popup,
1197 window,
1198 cx,
1191 1199 menu_state.clone(),
1192 menu_channel_id.clone(),
1193 followed,
1194 ))
1200 &menu_channel_id,
1201 notifications,
1202 )
1195 1203 })
1196 1204 }
1197 1205
1198 1206 fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {
1199 let (sidebar, pinned_ids, followed, selected) = {
1207 let (sidebar, pinned_ids, selected) = {
1200 1208 let state = self.state.read(cx);
1201 1209 (
1202 1210 state.sidebar.clone(),
1203 1211 state.directory.pinned_channels.clone(),
1204 state.followed_channels.clone(),
1205 1212 state.selection.clone().filter(|_| !state.new_chat),
1206 1213 )
1207 1214 };
1208 1215 let mut list = v_flex().w_full().pb(px(12.));
1209 let pinned: Vec<(&TeamRecord, &ChannelRecord)> = pinned_ids
1216 let pinned: Vec<(&SidebarTeam, &ChannelRecord)> = pinned_ids
1210 1217 .iter()
1211 1218 .filter_map(|id| {
1212 1219 sidebar.teams.iter().find_map(|entry| {
@@ -1214,20 +1221,20 @@ impl SidebarView {
1214 1221 .channels
1215 1222 .iter()
1216 1223 .find(|channel| &channel.id == id)
1217 .map(|channel| (&entry.team, channel))
1224 .map(|channel| (entry, channel))
1218 1225 })
1219 1226 })
1220 1227 .collect();
1221 1228 if !pinned.is_empty() {
1222 1229 list = list.child(self.plain_header(PINNED_LABEL));
1223 for (team, channel) in pinned {
1230 for (entry, channel) in pinned {
1224 1231 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
1225 1232 list = list.child(self.channel_row(
1226 1233 &channel.id,
1227 team,
1234 &entry.team,
1228 1235 channel,
1229 1236 is_selected,
1230 followed.contains(&channel.id),
1237 entry.channel_notifications(&channel.id),
1231 1238 ));
1232 1239 }
1233 1240 }
@@ -1269,18 +1276,70 @@ impl SidebarView {
1269 1276 }
1270 1277 }
1271 1278
1272 fn followed_bell() -> impl IntoElement {
1273 symbol("notifications", 12., theme::text_muted())
1279 fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1280 let name = match level {
1281 ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
1282 ChannelNotificationLevel::Off => IconName::BellOff,
1283 ChannelNotificationLevel::Feed => return None,
1284 };
1285 Some(icon(name, NOTIFICATION_ICON_SIZE, theme::text_muted()))
1274 1286 }
1275 1287
1276 fn follow_item(state: Entity<AppState>, channel_id: String, followed: bool) -> PopupMenuItem {
1277 PopupMenuItem::new("Notify on all posts")
1278 .checked(followed)
1279 .on_click(move |_, _, cx| {
1280 state.update(cx, |state, cx| {
1281 state.toggle_followed_channel(&channel_id, cx)
1282 });
1283 })
1288 fn channel_menu(
1289 popup: PopupMenu,
1290 window: &mut Window,
1291 cx: &mut Context<PopupMenu>,
1292 state: Entity<AppState>,
1293 channel_id: &str,
1294 notifications: ChannelNotifications,
1295 ) -> PopupMenu {
1296 let channel_id = channel_id.to_owned();
1297 popup.submenu_with_icon(
1298 Some(menu_icon(IconName::Bell)),
1299 "Notifications",
1300 window,
1301 cx,
1302 move |submenu, _, _| {
1303 let level_item = |label: &'static str, level: ChannelNotificationLevel| {
1304 let (state, channel_id) = (state.clone(), channel_id.clone());
1305 PopupMenuItem::new(label)
1306 .checked(notifications.level == level)
1307 .on_click(move |_, _, cx| {
1308 let changed = ChannelNotifications {
1309 level,
1310 include_replies: notifications.include_replies
1311 && level != ChannelNotificationLevel::Off,
1312 };
1313 state.update(cx, |state, cx| {
1314 state.set_channel_notifications(&channel_id, changed, cx)
1315 });
1316 })
1317 };
1318 let (replies_state, replies_id) = (state.clone(), channel_id.clone());
1319 submenu
1320 .item(level_item(
1321 "Banner and activity",
1322 ChannelNotificationLevel::BannerAndFeed,
1323 ))
1324 .item(level_item("Activity only", ChannelNotificationLevel::Feed))
1325 .item(level_item("Off", ChannelNotificationLevel::Off))
1326 .separator()
1327 .item(
1328 PopupMenuItem::new("Include thread replies")
1329 .checked(notifications.include_replies)
1330 .disabled(notifications.level == ChannelNotificationLevel::Off)
1331 .on_click(move |_, _, cx| {
1332 let changed = ChannelNotifications {
1333 level: notifications.level,
1334 include_replies: !notifications.include_replies,
1335 };
1336 replies_state.update(cx, |state, cx| {
1337 state.set_channel_notifications(&replies_id, changed, cx)
1338 });
1339 }),
1340 )
1341 },
1342 )
1284 1343 }
1285 1344
1286 1345 fn team_expanded(team_id: &str, collapsed_teams: &HashSet<String>) -> bool {
@@ -8,10 +8,12 @@ use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenu, PopupMenuItem};
8use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
8use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
9use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
10use gpui_kit::*;
11use store::{ChannelRecord, SidebarTeam, Store, TeamRecord};
11use store::{
12 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,
13};
12
14
13use super::avatar::{spec_avatar, square_avatar, with_presence};
15use super::avatar::{spec_avatar, square_avatar, with_presence};
14use super::widgets::{count_badge, dot, icon, symbol, unread_marker};
16use super::widgets::{count_badge, dot, icon, unread_marker};
15use crate::app_state::{AppEvent, AppState, Selection};
17use crate::app_state::{AppEvent, AppState, Selection};
16use crate::chat_actions::TITLE_LIMIT;
18use crate::chat_actions::TITLE_LIMIT;
17use crate::data::{Directory, FolderKind};
19use crate::data::{Directory, FolderKind};
@@ -43,6 +45,7 @@ const REVEAL_ROW_HEIGHT: f32 = 32.;
43const NEW_CHAT_BUTTON_SIZE: f32 = 34.;
45const NEW_CHAT_BUTTON_SIZE: f32 = 34.;
44const MENU_ICON_SIZE: f32 = 15.;
46const MENU_ICON_SIZE: f32 = 15.;
45const MUTED_ICON_SIZE: f32 = 13.;
47const MUTED_ICON_SIZE: f32 = 13.;
48const NOTIFICATION_ICON_SIZE: f32 = 13.;
46
49
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48enum SidebarTab {
51enum SidebarTab {
@@ -883,7 +886,7 @@ impl SidebarView {
883 team: &TeamRecord,
886 team: &TeamRecord,
884 channel: &ChannelRecord,
887 channel: &ChannelRecord,
885 selected: bool,
888 selected: bool,
886 followed: bool,
889 notifications: ChannelNotifications,
887 ) -> AnyElement {
890 ) -> AnyElement {
888 let unread = channel.unread;
891 let unread = channel.unread;
889 let state = self.state.clone();
892 let state = self.state.clone();
@@ -933,7 +936,7 @@ impl SidebarView {
933 .text_color(theme::text())
936 .text_color(theme::text())
934 .child(format!("{} / {}", team.name, channel.name)),
937 .child(format!("{} / {}", team.name, channel.name)),
935 )
938 )
936 .when(followed, |line| line.child(followed_bell()))
939 .children(notification_badge(notifications.level))
937 .child(
940 .child(
938 div()
941 div()
939 .flex_none()
942 .flex_none()
@@ -966,12 +969,15 @@ impl SidebarView {
966 let selection = selection.clone();
969 let selection = selection.clone();
967 state.update(cx, |state, cx| state.select(selection, cx));
970 state.update(cx, |state, cx| state.select(selection, cx));
968 })
971 })
969 .context_menu(move |popup, _, _| {
972 .context_menu(move |popup, window, cx| {
970 popup.item(follow_item(
973 channel_menu(
974 popup,
975 window,
976 cx,
971 menu_state.clone(),
977 menu_state.clone(),
972 menu_channel_id.clone(),
978 &menu_channel_id,
973 followed,
979 notifications,
974 ))
980 )
975 })
981 })
976 .into_any_element()
982 .into_any_element()
977 }
983 }
@@ -996,7 +1002,6 @@ impl SidebarView {
996 selected: Option<&Selection>,
1002 selected: Option<&Selection>,
997 cx: &mut Context<Self>,
1003 cx: &mut Context<Self>,
998 ) -> Div {
1004 ) -> Div {
999 let followed = self.state.read(cx).followed_channels.clone();
1000 let team_id = entry.team.id.clone();
1005 let team_id = entry.team.id.clone();
1001 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1006 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1002 let unread = entry.channels.iter().any(|channel| channel.unread);
1007 let unread = entry.channels.iter().any(|channel| channel.unread);
@@ -1059,7 +1064,7 @@ impl SidebarView {
1059 list = list.child(self.team_channel_row(
1064 list = list.child(self.team_channel_row(
1060 channel,
1065 channel,
1061 is_selected(channel),
1066 is_selected(channel),
1062 followed.contains(&channel.id),
1067 entry.channel_notifications(&channel.id),
1063 ));
1068 ));
1064 }
1069 }
1065 let hidden: Vec<&ChannelRecord> = entry
1070 let hidden: Vec<&ChannelRecord> = entry
@@ -1089,7 +1094,7 @@ impl SidebarView {
1089 list = list.child(self.team_channel_row(
1094 list = list.child(self.team_channel_row(
1090 channel,
1095 channel,
1091 false,
1096 false,
1092 followed.contains(&channel.id),
1097 entry.channel_notifications(&channel.id),
1093 ));
1098 ));
1094 }
1099 }
1095 }
1100 }
@@ -1137,7 +1142,7 @@ impl SidebarView {
1137 &self,
1142 &self,
1138 channel: &ChannelRecord,
1143 channel: &ChannelRecord,
1139 is_selected: bool,
1144 is_selected: bool,
1140 followed: bool,
1145 notifications: ChannelNotifications,
1141 ) -> impl IntoElement {
1146 ) -> impl IntoElement {
1142 let state = self.state.clone();
1147 let state = self.state.clone();
1143 let menu_state = self.state.clone();
1148 let menu_state = self.state.clone();
@@ -1180,33 +1185,35 @@ impl SidebarView {
1180 .text_color(theme::text())
1185 .text_color(theme::text())
1181 .child(channel.name.clone()),
1186 .child(channel.name.clone()),
1182 )
1187 )
1183 .when(followed, |row| row.child(followed_bell()))
1188 .children(notification_badge(notifications.level))
1184 .when(channel.unread, |row| row.child(dot(7.)))
1189 .when(channel.unread, |row| row.child(dot(7.)))
1185 .on_click(move |_, _, cx| {
1190 .on_click(move |_, _, cx| {
1186 let selection = selection.clone();
1191 let selection = selection.clone();
1187 state.update(cx, |state, cx| state.select(selection, cx));
1192 state.update(cx, |state, cx| state.select(selection, cx));
1188 })
1193 })
1189 .context_menu(move |popup, _, _| {
1194 .context_menu(move |popup, window, cx| {
1190 popup.item(follow_item(
1195 channel_menu(
1196 popup,
1197 window,
1198 cx,
1191 menu_state.clone(),
1199 menu_state.clone(),
1192 menu_channel_id.clone(),
1200 &menu_channel_id,
1193 followed,
1201 notifications,
1194 ))
1202 )
1195 })
1203 })
1196 }
1204 }
1197
1205
1198 fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {
1206 fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {
1199 let (sidebar, pinned_ids, followed, selected) = {
1207 let (sidebar, pinned_ids, selected) = {
1200 let state = self.state.read(cx);
1208 let state = self.state.read(cx);
1201 (
1209 (
1202 state.sidebar.clone(),
1210 state.sidebar.clone(),
1203 state.directory.pinned_channels.clone(),
1211 state.directory.pinned_channels.clone(),
1204 state.followed_channels.clone(),
1205 state.selection.clone().filter(|_| !state.new_chat),
1212 state.selection.clone().filter(|_| !state.new_chat),
1206 )
1213 )
1207 };
1214 };
1208 let mut list = v_flex().w_full().pb(px(12.));
1215 let mut list = v_flex().w_full().pb(px(12.));
1209 let pinned: Vec<(&TeamRecord, &ChannelRecord)> = pinned_ids
1216 let pinned: Vec<(&SidebarTeam, &ChannelRecord)> = pinned_ids
1210 .iter()
1217 .iter()
1211 .filter_map(|id| {
1218 .filter_map(|id| {
1212 sidebar.teams.iter().find_map(|entry| {
1219 sidebar.teams.iter().find_map(|entry| {
@@ -1214,20 +1221,20 @@ impl SidebarView {
1214 .channels
1221 .channels
1215 .iter()
1222 .iter()
1216 .find(|channel| &channel.id == id)
1223 .find(|channel| &channel.id == id)
1217 .map(|channel| (&entry.team, channel))
1224 .map(|channel| (entry, channel))
1218 })
1225 })
1219 })
1226 })
1220 .collect();
1227 .collect();
1221 if !pinned.is_empty() {
1228 if !pinned.is_empty() {
1222 list = list.child(self.plain_header(PINNED_LABEL));
1229 list = list.child(self.plain_header(PINNED_LABEL));
1223 for (team, channel) in pinned {
1230 for (entry, channel) in pinned {
1224 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
1231 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
1225 list = list.child(self.channel_row(
1232 list = list.child(self.channel_row(
1226 &channel.id,
1233 &channel.id,
1227 team,
1234 &entry.team,
1228 channel,
1235 channel,
1229 is_selected,
1236 is_selected,
1230 followed.contains(&channel.id),
1237 entry.channel_notifications(&channel.id),
1231 ));
1238 ));
1232 }
1239 }
1233 }
1240 }
@@ -1269,18 +1276,70 @@ impl SidebarView {
1269 }
1276 }
1270}
1277}
1271
1278
1272fn followed_bell() -> impl IntoElement {
1279fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1273 symbol("notifications", 12., theme::text_muted())
1280 let name = match level {
1281 ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
1282 ChannelNotificationLevel::Off => IconName::BellOff,
1283 ChannelNotificationLevel::Feed => return None,
1284 };
1285 Some(icon(name, NOTIFICATION_ICON_SIZE, theme::text_muted()))
1274}
1286}
1275
1287
1276fn follow_item(state: Entity<AppState>, channel_id: String, followed: bool) -> PopupMenuItem {
1288fn channel_menu(
1277 PopupMenuItem::new("Notify on all posts")
1289 popup: PopupMenu,
1278 .checked(followed)
1290 window: &mut Window,
1279 .on_click(move |_, _, cx| {
1291 cx: &mut Context<PopupMenu>,
1280 state.update(cx, |state, cx| {
1292 state: Entity<AppState>,
1281 state.toggle_followed_channel(&channel_id, cx)
1293 channel_id: &str,
1282 });
1294 notifications: ChannelNotifications,
1283 })
1295) -> PopupMenu {
1296 let channel_id = channel_id.to_owned();
1297 popup.submenu_with_icon(
1298 Some(menu_icon(IconName::Bell)),
1299 "Notifications",
1300 window,
1301 cx,
1302 move |submenu, _, _| {
1303 let level_item = |label: &'static str, level: ChannelNotificationLevel| {
1304 let (state, channel_id) = (state.clone(), channel_id.clone());
1305 PopupMenuItem::new(label)
1306 .checked(notifications.level == level)
1307 .on_click(move |_, _, cx| {
1308 let changed = ChannelNotifications {
1309 level,
1310 include_replies: notifications.include_replies
1311 && level != ChannelNotificationLevel::Off,
1312 };
1313 state.update(cx, |state, cx| {
1314 state.set_channel_notifications(&channel_id, changed, cx)
1315 });
1316 })
1317 };
1318 let (replies_state, replies_id) = (state.clone(), channel_id.clone());
1319 submenu
1320 .item(level_item(
1321 "Banner and activity",
1322 ChannelNotificationLevel::BannerAndFeed,
1323 ))
1324 .item(level_item("Activity only", ChannelNotificationLevel::Feed))
1325 .item(level_item("Off", ChannelNotificationLevel::Off))
1326 .separator()
1327 .item(
1328 PopupMenuItem::new("Include thread replies")
1329 .checked(notifications.include_replies)
1330 .disabled(notifications.level == ChannelNotificationLevel::Off)
1331 .on_click(move |_, _, cx| {
1332 let changed = ChannelNotifications {
1333 level: notifications.level,
1334 include_replies: !notifications.include_replies,
1335 };
1336 replies_state.update(cx, |state, cx| {
1337 state.set_channel_notifications(&replies_id, changed, cx)
1338 });
1339 }),
1340 )
1341 },
1342 )
1284}
1343}
1285
1344
1286fn team_expanded(team_id: &str, collapsed_teams: &HashSet<String>) -> bool {
1345fn team_expanded(team_id: &str, collapsed_teams: &HashSet<String>) -> bool {
crates/chatsvc/src/channel_notifications.rs added +324 −0
@@ -0,0 +1,324 @@
1 use std::collections::HashMap;
2
3 use serde_json::{Value, json};
4 use session::{Method, Request, Scope, Session};
5
6 use crate::error::{Error, Result};
7 use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
9 pub const NSS_RESOURCE: &str = "https://uis.teams.microsoft.com";
10 const NSS_SCOPE: &str = "user_impersonation";
11 pub(crate) const PROPERTY_NAME: &str = "channelNotificationSettings";
12 const NSS_BATCH_LIMIT: usize = 100;
13
14 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15 pub enum ChannelNotificationLevel {
16 BannerAndFeed,
17 #[default]
18 Feed,
19 Off,
20 }
21
22 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23 pub struct ChannelNotifications {
24 pub level: ChannelNotificationLevel,
25 pub include_replies: bool,
26 }
27
28 impl ChannelNotifications {
29 pub fn from_followed(followed: bool) -> Self {
30 if followed {
31 ChannelNotifications {
32 level: ChannelNotificationLevel::BannerAndFeed,
33 include_replies: true,
34 }
35 } else {
36 ChannelNotifications::default()
37 }
38 }
39
40 pub fn property_value(self) -> String {
41 let mut settings = match self.level {
42 ChannelNotificationLevel::BannerAndFeed => {
43 json!({"allNewPosts": "On", "dskNotif": "On"})
44 }
45 ChannelNotificationLevel::Feed => json!({"allNewPosts": "On"}),
46 ChannelNotificationLevel::Off => json!({"allNewPosts": "Off"}),
47 };
48 settings["includeReplies"] =
49 json!(self.include_replies && self.level != ChannelNotificationLevel::Off);
50 settings.to_string()
51 }
52 }
53
54 pub fn parse_property(raw: &str) -> Option<ChannelNotifications> {
55 let settings: Value = serde_json::from_str(raw).ok()?;
56 let level = match (
57 settings.get("allNewPosts").and_then(Value::as_str)?,
58 settings.get("dskNotif").and_then(Value::as_str),
59 ) {
60 ("On", Some("On")) => ChannelNotificationLevel::BannerAndFeed,
61 ("On", _) => ChannelNotificationLevel::Feed,
62 _ => ChannelNotificationLevel::Off,
63 };
64 Some(ChannelNotifications {
65 level,
66 include_replies: settings
67 .get("includeReplies")
68 .and_then(Value::as_bool)
69 .unwrap_or(false),
70 })
71 }
72
73 pub fn parse_nss_batch(body: &Value) -> HashMap<String, ChannelNotifications> {
74 body.get("results")
75 .and_then(Value::as_array)
76 .into_iter()
77 .flatten()
78 .filter_map(|result| {
79 let settings = result
80 .get("settings")
81 .filter(|settings| settings.is_object())?;
82 let level = match settings.get("allNewPosts").and_then(Value::as_str)? {
83 "BannerAndFeed" => ChannelNotificationLevel::BannerAndFeed,
84 "Feed" => ChannelNotificationLevel::Feed,
85 _ => ChannelNotificationLevel::Off,
86 };
87 Some((
88 result.get("channelId")?.as_str()?.to_owned(),
89 ChannelNotifications {
90 level,
91 include_replies: settings
92 .get("includeReplies")
93 .and_then(Value::as_bool)
94 .unwrap_or(false),
95 },
96 ))
97 })
98 .collect()
99 }
100
101 pub struct ChannelSettings<T: CsaTransport = SessionTransport> {
102 transport: T,
103 url: String,
104 }
105
106 impl ChannelSettings<SessionTransport> {
107 pub fn new(session: &Session) -> Self {
108 ChannelSettings::with_transport(
109 SessionTransport::with_scope(session, Scope::new(NSS_RESOURCE, NSS_SCOPE)),
110 DEFAULT_REGION,
111 )
112 }
113 }
114
115 impl<T: CsaTransport> ChannelSettings<T> {
116 pub fn with_transport(transport: T, region: &str) -> Self {
117 ChannelSettings {
118 transport,
119 url: format!(
120 "https://teams.cloud.microsoft/api/nss/{region}/v1/me/notificationSettings/channels/batch"
121 ),
122 }
123 }
124
125 pub async fn fetch(
126 &self,
127 channel_ids: &[String],
128 ) -> Result<HashMap<String, ChannelNotifications>> {
129 let mut settings = HashMap::new();
130 for batch in channel_ids.chunks(NSS_BATCH_LIMIT) {
131 let answer = self
132 .transport
133 .send(Request::with_body(
134 Method::Post,
135 &self.url,
136 json!({"channelIds": batch}),
137 ))
138 .await?;
139 if !answer.is_success() {
140 return Err(Error::UnexpectedAnswer(format!(
141 "channel settings answered {}",
142 answer.status
143 )));
144 }
145 settings.extend(parse_nss_batch(&answer.body));
146 }
147 Ok(settings)
148 }
149 }
150
151 #[cfg(test)]
152 mod tests {
153 use std::collections::VecDeque;
154 use std::sync::Mutex;
155
156 use session::ApiResponse;
157
158 use super::*;
159 use crate::conversations::Conversations;
160 use crate::messages::MessageTransport;
161
162 struct Canned {
163 answers: Mutex<VecDeque<(u16, Value)>>,
164 requests: Mutex<Vec<Request>>,
165 }
166
167 impl CsaTransport for &Canned {
168 async fn send(&self, request: Request) -> Result<ApiResponse> {
169 self.requests.lock().unwrap().push(request);
170 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
171 Ok(ApiResponse {
172 status,
173 body,
174 retry_after: None,
175 })
176 }
177 }
178
179 impl MessageTransport for &Canned {
180 async fn send(&self, request: Request) -> Result<ApiResponse> {
181 CsaTransport::send(self, request).await
182 }
183 }
184
185 fn canned(answers: Vec<(u16, Value)>) -> Canned {
186 Canned {
187 answers: Mutex::new(answers.into()),
188 requests: Mutex::new(Vec::new()),
189 }
190 }
191
192 #[test]
193 fn property_maps_the_three_levels() {
194 let banner =
195 parse_property(r#"{"allNewPosts":"On","dskNotif":"On","includeReplies":true}"#);
196 assert_eq!(
197 banner,
198 Some(ChannelNotifications {
199 level: ChannelNotificationLevel::BannerAndFeed,
200 include_replies: true
201 })
202 );
203 let feed = parse_property(r#"{"allNewPosts":"On","latestCnsVersion":1}"#).unwrap();
204 assert_eq!(feed.level, ChannelNotificationLevel::Feed);
205 assert!(!feed.include_replies);
206 let off = parse_property(r#"{"allNewPosts":"Off","includeReplies":false}"#).unwrap();
207 assert_eq!(off.level, ChannelNotificationLevel::Off);
208 }
209
210 #[test]
211 fn unreadable_property_is_missing() {
212 assert_eq!(parse_property("not json"), None);
213 assert_eq!(parse_property(r#"{"includeReplies":true}"#), None);
214 }
215
216 #[test]
217 fn followed_without_a_value_means_banner_with_replies() {
218 assert_eq!(
219 ChannelNotifications::from_followed(true),
220 ChannelNotifications {
221 level: ChannelNotificationLevel::BannerAndFeed,
222 include_replies: true
223 }
224 );
225 assert_eq!(
226 ChannelNotifications::from_followed(false).level,
227 ChannelNotificationLevel::Feed
228 );
229 }
230
231 #[test]
232 fn nss_batch_skips_channels_without_settings() {
233 let body = json!({"results": [
234 {"channelId": "19:a", "success": true, "settings": {"allNewPosts": "BannerAndFeed", "includeReplies": true}},
235 {"channelId": "19:b", "success": true, "settings": {"allNewPosts": "Feed"}},
236 {"channelId": "19:c", "success": true, "settings": {"allNewPosts": "Off"}},
237 {"channelId": "19:d", "success": true, "settings": null},
238 {"channelId": "19:e", "success": false, "settings": null, "errorMessage": "x"},
239 ]});
240 let parsed = parse_nss_batch(&body);
241 assert_eq!(parsed.len(), 3);
242 assert_eq!(
243 parsed["19:a"].level,
244 ChannelNotificationLevel::BannerAndFeed
245 );
246 assert!(parsed["19:a"].include_replies);
247 assert_eq!(parsed["19:b"].level, ChannelNotificationLevel::Feed);
248 assert_eq!(parsed["19:c"].level, ChannelNotificationLevel::Off);
249 }
250
251 #[tokio::test]
252 async fn fetch_splits_into_batches_of_one_hundred() {
253 let transport = canned(vec![
254 (200, json!({"results": []})),
255 (200, json!({"results": []})),
256 ]);
257 let ids: Vec<String> = (0..101).map(|index| format!("19:{index}")).collect();
258 ChannelSettings::with_transport(&transport, "emea")
259 .fetch(&ids)
260 .await
261 .unwrap();
262 let requests = transport.requests.lock().unwrap();
263 let sizes: Vec<usize> = requests
264 .iter()
265 .map(|request| {
266 request.body.as_ref().unwrap()["channelIds"]
267 .as_array()
268 .unwrap()
269 .len()
270 })
271 .collect();
272 assert_eq!(sizes, [100, 1]);
273 }
274
275 #[tokio::test]
276 async fn write_puts_the_settings_as_a_json_string() {
277 let transport = canned(vec![
278 (200, Value::Null),
279 (200, Value::Null),
280 (200, Value::Null),
281 ]);
282 let conversations = Conversations::with_transport(&transport, "emea");
283 for (level, include_replies) in [
284 (ChannelNotificationLevel::BannerAndFeed, false),
285 (ChannelNotificationLevel::Feed, true),
286 (ChannelNotificationLevel::Off, true),
287 ] {
288 conversations
289 .set_channel_notifications(
290 "19:a@thread.tacv2",
291 ChannelNotifications {
292 level,
293 include_replies,
294 },
295 )
296 .await
297 .unwrap();
298 }
299 let requests = transport.requests.lock().unwrap();
300 assert_eq!(requests[0].method, Method::Put);
301 assert_eq!(
302 requests[0].url,
303 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Aa%40thread.tacv2/properties?name=channelNotificationSettings"
304 );
305 assert_eq!(
306 requests[0].body,
307 Some(
308 json!({"channelNotificationSettings": "{\"allNewPosts\":\"On\",\"dskNotif\":\"On\",\"includeReplies\":false}"})
309 )
310 );
311 assert_eq!(
312 requests[1].body,
313 Some(
314 json!({"channelNotificationSettings": "{\"allNewPosts\":\"On\",\"includeReplies\":true}"})
315 )
316 );
317 assert_eq!(
318 requests[2].body,
319 Some(
320 json!({"channelNotificationSettings": "{\"allNewPosts\":\"Off\",\"includeReplies\":false}"})
321 )
322 );
323 }
324 }
@@ -0,0 +1,324 @@
1use std::collections::HashMap;
2
3use serde_json::{Value, json};
4use session::{Method, Request, Scope, Session};
5
6use crate::error::{Error, Result};
7use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
9pub const NSS_RESOURCE: &str = "https://uis.teams.microsoft.com";
10const NSS_SCOPE: &str = "user_impersonation";
11pub(crate) const PROPERTY_NAME: &str = "channelNotificationSettings";
12const NSS_BATCH_LIMIT: usize = 100;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum ChannelNotificationLevel {
16 BannerAndFeed,
17 #[default]
18 Feed,
19 Off,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub struct ChannelNotifications {
24 pub level: ChannelNotificationLevel,
25 pub include_replies: bool,
26}
27
28impl ChannelNotifications {
29 pub fn from_followed(followed: bool) -> Self {
30 if followed {
31 ChannelNotifications {
32 level: ChannelNotificationLevel::BannerAndFeed,
33 include_replies: true,
34 }
35 } else {
36 ChannelNotifications::default()
37 }
38 }
39
40 pub fn property_value(self) -> String {
41 let mut settings = match self.level {
42 ChannelNotificationLevel::BannerAndFeed => {
43 json!({"allNewPosts": "On", "dskNotif": "On"})
44 }
45 ChannelNotificationLevel::Feed => json!({"allNewPosts": "On"}),
46 ChannelNotificationLevel::Off => json!({"allNewPosts": "Off"}),
47 };
48 settings["includeReplies"] =
49 json!(self.include_replies && self.level != ChannelNotificationLevel::Off);
50 settings.to_string()
51 }
52}
53
54pub fn parse_property(raw: &str) -> Option<ChannelNotifications> {
55 let settings: Value = serde_json::from_str(raw).ok()?;
56 let level = match (
57 settings.get("allNewPosts").and_then(Value::as_str)?,
58 settings.get("dskNotif").and_then(Value::as_str),
59 ) {
60 ("On", Some("On")) => ChannelNotificationLevel::BannerAndFeed,
61 ("On", _) => ChannelNotificationLevel::Feed,
62 _ => ChannelNotificationLevel::Off,
63 };
64 Some(ChannelNotifications {
65 level,
66 include_replies: settings
67 .get("includeReplies")
68 .and_then(Value::as_bool)
69 .unwrap_or(false),
70 })
71}
72
73pub fn parse_nss_batch(body: &Value) -> HashMap<String, ChannelNotifications> {
74 body.get("results")
75 .and_then(Value::as_array)
76 .into_iter()
77 .flatten()
78 .filter_map(|result| {
79 let settings = result
80 .get("settings")
81 .filter(|settings| settings.is_object())?;
82 let level = match settings.get("allNewPosts").and_then(Value::as_str)? {
83 "BannerAndFeed" => ChannelNotificationLevel::BannerAndFeed,
84 "Feed" => ChannelNotificationLevel::Feed,
85 _ => ChannelNotificationLevel::Off,
86 };
87 Some((
88 result.get("channelId")?.as_str()?.to_owned(),
89 ChannelNotifications {
90 level,
91 include_replies: settings
92 .get("includeReplies")
93 .and_then(Value::as_bool)
94 .unwrap_or(false),
95 },
96 ))
97 })
98 .collect()
99}
100
101pub struct ChannelSettings<T: CsaTransport = SessionTransport> {
102 transport: T,
103 url: String,
104}
105
106impl ChannelSettings<SessionTransport> {
107 pub fn new(session: &Session) -> Self {
108 ChannelSettings::with_transport(
109 SessionTransport::with_scope(session, Scope::new(NSS_RESOURCE, NSS_SCOPE)),
110 DEFAULT_REGION,
111 )
112 }
113}
114
115impl<T: CsaTransport> ChannelSettings<T> {
116 pub fn with_transport(transport: T, region: &str) -> Self {
117 ChannelSettings {
118 transport,
119 url: format!(
120 "https://teams.cloud.microsoft/api/nss/{region}/v1/me/notificationSettings/channels/batch"
121 ),
122 }
123 }
124
125 pub async fn fetch(
126 &self,
127 channel_ids: &[String],
128 ) -> Result<HashMap<String, ChannelNotifications>> {
129 let mut settings = HashMap::new();
130 for batch in channel_ids.chunks(NSS_BATCH_LIMIT) {
131 let answer = self
132 .transport
133 .send(Request::with_body(
134 Method::Post,
135 &self.url,
136 json!({"channelIds": batch}),
137 ))
138 .await?;
139 if !answer.is_success() {
140 return Err(Error::UnexpectedAnswer(format!(
141 "channel settings answered {}",
142 answer.status
143 )));
144 }
145 settings.extend(parse_nss_batch(&answer.body));
146 }
147 Ok(settings)
148 }
149}
150
151#[cfg(test)]
152mod tests {
153 use std::collections::VecDeque;
154 use std::sync::Mutex;
155
156 use session::ApiResponse;
157
158 use super::*;
159 use crate::conversations::Conversations;
160 use crate::messages::MessageTransport;
161
162 struct Canned {
163 answers: Mutex<VecDeque<(u16, Value)>>,
164 requests: Mutex<Vec<Request>>,
165 }
166
167 impl CsaTransport for &Canned {
168 async fn send(&self, request: Request) -> Result<ApiResponse> {
169 self.requests.lock().unwrap().push(request);
170 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
171 Ok(ApiResponse {
172 status,
173 body,
174 retry_after: None,
175 })
176 }
177 }
178
179 impl MessageTransport for &Canned {
180 async fn send(&self, request: Request) -> Result<ApiResponse> {
181 CsaTransport::send(self, request).await
182 }
183 }
184
185 fn canned(answers: Vec<(u16, Value)>) -> Canned {
186 Canned {
187 answers: Mutex::new(answers.into()),
188 requests: Mutex::new(Vec::new()),
189 }
190 }
191
192 #[test]
193 fn property_maps_the_three_levels() {
194 let banner =
195 parse_property(r#"{"allNewPosts":"On","dskNotif":"On","includeReplies":true}"#);
196 assert_eq!(
197 banner,
198 Some(ChannelNotifications {
199 level: ChannelNotificationLevel::BannerAndFeed,
200 include_replies: true
201 })
202 );
203 let feed = parse_property(r#"{"allNewPosts":"On","latestCnsVersion":1}"#).unwrap();
204 assert_eq!(feed.level, ChannelNotificationLevel::Feed);
205 assert!(!feed.include_replies);
206 let off = parse_property(r#"{"allNewPosts":"Off","includeReplies":false}"#).unwrap();
207 assert_eq!(off.level, ChannelNotificationLevel::Off);
208 }
209
210 #[test]
211 fn unreadable_property_is_missing() {
212 assert_eq!(parse_property("not json"), None);
213 assert_eq!(parse_property(r#"{"includeReplies":true}"#), None);
214 }
215
216 #[test]
217 fn followed_without_a_value_means_banner_with_replies() {
218 assert_eq!(
219 ChannelNotifications::from_followed(true),
220 ChannelNotifications {
221 level: ChannelNotificationLevel::BannerAndFeed,
222 include_replies: true
223 }
224 );
225 assert_eq!(
226 ChannelNotifications::from_followed(false).level,
227 ChannelNotificationLevel::Feed
228 );
229 }
230
231 #[test]
232 fn nss_batch_skips_channels_without_settings() {
233 let body = json!({"results": [
234 {"channelId": "19:a", "success": true, "settings": {"allNewPosts": "BannerAndFeed", "includeReplies": true}},
235 {"channelId": "19:b", "success": true, "settings": {"allNewPosts": "Feed"}},
236 {"channelId": "19:c", "success": true, "settings": {"allNewPosts": "Off"}},
237 {"channelId": "19:d", "success": true, "settings": null},
238 {"channelId": "19:e", "success": false, "settings": null, "errorMessage": "x"},
239 ]});
240 let parsed = parse_nss_batch(&body);
241 assert_eq!(parsed.len(), 3);
242 assert_eq!(
243 parsed["19:a"].level,
244 ChannelNotificationLevel::BannerAndFeed
245 );
246 assert!(parsed["19:a"].include_replies);
247 assert_eq!(parsed["19:b"].level, ChannelNotificationLevel::Feed);
248 assert_eq!(parsed["19:c"].level, ChannelNotificationLevel::Off);
249 }
250
251 #[tokio::test]
252 async fn fetch_splits_into_batches_of_one_hundred() {
253 let transport = canned(vec![
254 (200, json!({"results": []})),
255 (200, json!({"results": []})),
256 ]);
257 let ids: Vec<String> = (0..101).map(|index| format!("19:{index}")).collect();
258 ChannelSettings::with_transport(&transport, "emea")
259 .fetch(&ids)
260 .await
261 .unwrap();
262 let requests = transport.requests.lock().unwrap();
263 let sizes: Vec<usize> = requests
264 .iter()
265 .map(|request| {
266 request.body.as_ref().unwrap()["channelIds"]
267 .as_array()
268 .unwrap()
269 .len()
270 })
271 .collect();
272 assert_eq!(sizes, [100, 1]);
273 }
274
275 #[tokio::test]
276 async fn write_puts_the_settings_as_a_json_string() {
277 let transport = canned(vec![
278 (200, Value::Null),
279 (200, Value::Null),
280 (200, Value::Null),
281 ]);
282 let conversations = Conversations::with_transport(&transport, "emea");
283 for (level, include_replies) in [
284 (ChannelNotificationLevel::BannerAndFeed, false),
285 (ChannelNotificationLevel::Feed, true),
286 (ChannelNotificationLevel::Off, true),
287 ] {
288 conversations
289 .set_channel_notifications(
290 "19:a@thread.tacv2",
291 ChannelNotifications {
292 level,
293 include_replies,
294 },
295 )
296 .await
297 .unwrap();
298 }
299 let requests = transport.requests.lock().unwrap();
300 assert_eq!(requests[0].method, Method::Put);
301 assert_eq!(
302 requests[0].url,
303 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Aa%40thread.tacv2/properties?name=channelNotificationSettings"
304 );
305 assert_eq!(
306 requests[0].body,
307 Some(
308 json!({"channelNotificationSettings": "{\"allNewPosts\":\"On\",\"dskNotif\":\"On\",\"includeReplies\":false}"})
309 )
310 );
311 assert_eq!(
312 requests[1].body,
313 Some(
314 json!({"channelNotificationSettings": "{\"allNewPosts\":\"On\",\"includeReplies\":true}"})
315 )
316 );
317 assert_eq!(
318 requests[2].body,
319 Some(
320 json!({"channelNotificationSettings": "{\"allNewPosts\":\"Off\",\"includeReplies\":false}"})
321 )
322 );
323 }
324}
crates/chatsvc/src/conversations.rs +19 −0
@@ -1,6 +1,7 @@
1 1 use serde_json::{Value, json};
2 2 use session::{Method, Request, Session};
3 3
4 use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};
4 5 use crate::error::{Error, Result};
5 6 use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
6 7 use crate::pins::DEFAULT_REGION;
@@ -73,6 +74,24 @@ impl<T: MessageTransport> Conversations<T> {
73 74 .await?;
74 75 ensure_success(&answer)
75 76 }
77
78 pub async fn set_channel_notifications(
79 &self,
80 channel_id: &str,
81 notifications: ChannelNotifications,
82 ) -> Result<()> {
83 let url = format!(
84 "{}/{}/properties?name={PROPERTY_NAME}",
85 self.base_url,
86 encode(channel_id)
87 );
88 let body = json!({ PROPERTY_NAME: notifications.property_value() });
89 let answer = self
90 .transport
91 .send(Request::with_body(Method::Put, url, body))
92 .await?;
93 ensure_success(&answer)
94 }
76 95 }
77 96
78 97 fn backward_link(body: &Value) -> Option<String> {
@@ -1,6 +1,7 @@
1use serde_json::{Value, json};
1use serde_json::{Value, json};
2use session::{Method, Request, Session};
2use session::{Method, Request, Session};
3
3
4use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};
4use crate::error::{Error, Result};
5use crate::error::{Error, Result};
5use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
6use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
6use crate::pins::DEFAULT_REGION;
7use crate::pins::DEFAULT_REGION;
@@ -73,6 +74,24 @@ impl<T: MessageTransport> Conversations<T> {
73 .await?;
74 .await?;
74 ensure_success(&answer)
75 ensure_success(&answer)
75 }
76 }
77
78 pub async fn set_channel_notifications(
79 &self,
80 channel_id: &str,
81 notifications: ChannelNotifications,
82 ) -> Result<()> {
83 let url = format!(
84 "{}/{}/properties?name={PROPERTY_NAME}",
85 self.base_url,
86 encode(channel_id)
87 );
88 let body = json!({ PROPERTY_NAME: notifications.property_value() });
89 let answer = self
90 .transport
91 .send(Request::with_body(Method::Put, url, body))
92 .await?;
93 ensure_success(&answer)
94 }
76}
95}
77
96
78fn backward_link(body: &Value) -> Option<String> {
97fn backward_link(body: &Value) -> Option<String> {
crates/chatsvc/src/lib.rs +4 −2
@@ -1,4 +1,5 @@
1 1 pub mod cards;
2 pub mod channel_notifications;
2 3 pub mod conversations;
3 4 pub mod drafts;
4 5 mod error;
@@ -18,6 +19,7 @@ pub mod settings;
18 19 pub use cards::{
19 20 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
20 21 };
22 pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
21 23 pub use conversations::Conversations;
22 24 pub use drafts::{ScheduledDraft, ScheduledDrafts};
23 25 pub use error::{Error, Result};
@@ -27,8 +29,8 @@ pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
27 29 pub use mask::mask_conversation_id;
28 30 pub use messages::{ConversationRef, Messages};
29 31 pub use pins::{
30 ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, PinnedMessage, Pins,
31 TeamLayout,
32 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
33 PinnedMessage, Pins, TeamLayout,
32 34 };
33 35 pub use presence::{
34 36 ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
@@ -1,4 +1,5 @@
1pub mod cards;
1pub mod cards;
2pub mod channel_notifications;
2pub mod conversations;
3pub mod conversations;
3pub mod drafts;
4pub mod drafts;
4mod error;
5mod error;
@@ -18,6 +19,7 @@ pub mod settings;
18pub use cards::{
19pub use cards::{
19 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
20 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
20};
21};
22pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
21pub use conversations::Conversations;
23pub use conversations::Conversations;
22pub use drafts::{ScheduledDraft, ScheduledDrafts};
24pub use drafts::{ScheduledDraft, ScheduledDrafts};
23pub use error::{Error, Result};
25pub use error::{Error, Result};
@@ -27,8 +29,8 @@ pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
27pub use mask::mask_conversation_id;
29pub use mask::mask_conversation_id;
28pub use messages::{ConversationRef, Messages};
30pub use messages::{ConversationRef, Messages};
29pub use pins::{
31pub use pins::{
30 ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, PinnedMessage, Pins,
32 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
31 TeamLayout,
33 PinnedMessage, Pins, TeamLayout,
32};
34};
33pub use presence::{
35pub use presence::{
34 ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
36 ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
crates/chatsvc/src/pins/mod.rs +1 −1
@@ -11,7 +11,7 @@ use session::Session;
11 11 pub use folders::{Folder, FolderKind, Folders};
12 12 pub use pinbar::PinnedMessage;
13 13 pub use state::{PinnedChannels, PinnedChats};
14 pub use teams::{ChannelLayout, TeamLayout};
14 pub use teams::{ChannelLayout, ChannelTab, TeamLayout};
15 15 pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};
16 16
17 17 pub const DEFAULT_REGION: &str = "emea";
@@ -11,7 +11,7 @@ use session::Session;
11pub use folders::{Folder, FolderKind, Folders};
11pub use folders::{Folder, FolderKind, Folders};
12pub use pinbar::PinnedMessage;
12pub use pinbar::PinnedMessage;
13pub use state::{PinnedChannels, PinnedChats};
13pub use state::{PinnedChannels, PinnedChats};
14pub use teams::{ChannelLayout, TeamLayout};
14pub use teams::{ChannelLayout, ChannelTab, TeamLayout};
15pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};
15pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};
16
16
17pub const DEFAULT_REGION: &str = "emea";
17pub const DEFAULT_REGION: &str = "emea";
crates/chatsvc/src/pins/teams.rs +124 −2
@@ -4,15 +4,29 @@ use session::Request;
4 4 use super::Pins;
5 5 use super::chats::ensure_success;
6 6 use super::transport::CsaTransport;
7 use crate::channel_notifications::{ChannelNotifications, parse_property};
7 8 use crate::error::{Error, Result};
8 9
9 10 const TEAMS_QUERY: &str = "isPrefetch=false&enableMembershipSummary=true";
11 const WIKI_DEFINITION_ID: &str = "com.microsoft.teamspace.tab.wiki";
12 const TAB_URL_KEYS: [&str; 3] = ["websiteUrl", "componentUrl", "url"];
13
14 #[derive(Debug, Clone, PartialEq, Eq)]
15 pub struct ChannelTab {
16 pub id: String,
17 pub name: String,
18 pub definition_id: String,
19 pub open_url: Option<String>,
20 }
10 21
11 22 #[derive(Debug, Clone, PartialEq, Eq)]
12 23 pub struct ChannelLayout {
13 24 pub channel_id: String,
14 25 pub general: bool,
15 26 pub hidden: bool,
27 pub tabs: Vec<ChannelTab>,
28 pub notifications: Option<ChannelNotifications>,
29 pub followed: bool,
16 30 }
17 31
18 32 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -45,6 +59,46 @@ fn flag(value: &Value, key: &str) -> Option<bool> {
45 59 value.get(key).and_then(Value::as_bool)
46 60 }
47 61
62 fn tab_open_url(settings: &Value) -> Option<String> {
63 TAB_URL_KEYS
64 .iter()
65 .filter_map(|key| settings.get(key).and_then(Value::as_str))
66 .map(str::trim)
67 .find(|url| url.starts_with("http") && !url.contains('{'))
68 .map(str::to_owned)
69 }
70
71 fn parse_tab(tab: &Value) -> Option<(i64, ChannelTab)> {
72 let definition_id = tab.get("definitionId")?.as_str()?;
73 if definition_id == WIKI_DEFINITION_ID {
74 return None;
75 }
76 let order = tab
77 .get("order")
78 .and_then(|order| order.as_i64().or_else(|| order.as_str()?.parse().ok()))
79 .unwrap_or(i64::MAX);
80 let settings = tab.get("settings").unwrap_or(&Value::Null);
81 Some((
82 order,
83 ChannelTab {
84 id: tab.get("id")?.as_str()?.to_owned(),
85 name: tab.get("name")?.as_str()?.to_owned(),
86 definition_id: definition_id.to_owned(),
87 open_url: tab_open_url(settings),
88 },
89 ))
90 }
91
92 pub fn parse_channel_tabs(channel: &Value) -> Vec<ChannelTab> {
93 let mut tabs: Vec<(i64, ChannelTab)> = channel
94 .get("tabs")
95 .and_then(Value::as_array)
96 .map(|tabs| tabs.iter().filter_map(parse_tab).collect())
97 .unwrap_or_default();
98 tabs.sort_by_key(|(order, _)| *order);
99 tabs.into_iter().map(|(_, tab)| tab).collect()
100 }
101
48 102 fn parse_team(team: &Value) -> Option<TeamLayout> {
49 103 if flag(team, "isDeleted") == Some(true) {
50 104 return None;
@@ -68,6 +122,12 @@ fn parse_team(team: &Value) -> Option<TeamLayout> {
68 122 channel_id: channel.get("id")?.as_str()?.to_owned(),
69 123 general,
70 124 hidden: !shown,
125 tabs: parse_channel_tabs(channel),
126 notifications: channel
127 .get("channelNotificationSettings")
128 .and_then(Value::as_str)
129 .and_then(parse_property),
130 followed: flag(channel, "isFollowed").unwrap_or(false),
71 131 })
72 132 })
73 133 .collect()
@@ -129,12 +189,18 @@ mod tests {
129 189 ChannelLayout {
130 190 channel_id: "19:b2@thread.tacv2".into(),
131 191 general: false,
132 hidden: true
192 hidden: true,
193 tabs: Vec::new(),
194 notifications: None,
195 followed: false,
133 196 },
134 197 ChannelLayout {
135 198 channel_id: "19:b@thread.tacv2".into(),
136 199 general: true,
137 hidden: false
200 hidden: false,
201 tabs: Vec::new(),
202 notifications: None,
203 followed: false,
138 204 },
139 205 ]
140 206 );
@@ -142,6 +208,62 @@ mod tests {
142 208 assert!(!layout[1].channels[1].hidden);
143 209 }
144 210
211 #[test]
212 fn tabs_follow_the_order_field_and_hide_wiki() {
213 let channel = json!({"id": "19:a@thread.tacv2", "tabs": [
214 {"id": "t3", "name": "Notes", "definitionId": "0d820ecd-def2-4297-adad-78056cde7c78",
215 "order": 30, "settings": {
216 "url": "https://onenote.example/{tid}/content",
217 "websiteUrl": "https://onenote.example/web"}},
218 {"id": "t0", "name": "Wiki", "definitionId": "com.microsoft.teamspace.tab.wiki", "order": 5},
219 {"id": "t1", "name": "Docs", "definitionId": "com.microsoft.teamspace.tab.web",
220 "order": 10, "settings": {"url": "https://docs.example", "websiteUrl": "https://docs.example"}},
221 {"id": "t2", "name": "Plan", "definitionId": "com.microsoft.teamspace.tab.planner",
222 "order": "20", "settings": {"url": "https://tasks.example/{locale}"}}
223 ]});
224 let tabs = parse_channel_tabs(&channel);
225 let names: Vec<&str> = tabs.iter().map(|tab| tab.name.as_str()).collect();
226 assert_eq!(names, ["Docs", "Plan", "Notes"]);
227 assert_eq!(tabs[0].open_url.as_deref(), Some("https://docs.example"));
228 assert_eq!(tabs[1].open_url, None);
229 assert_eq!(
230 tabs[2].open_url.as_deref(),
231 Some("https://onenote.example/web")
232 );
233 }
234
235 #[test]
236 fn reads_the_notification_string_and_the_followed_flag() {
237 let body = json!({"teams": [
238 {"id": "19:a@thread.tacv2", "channels": [
239 {"id": "19:a1", "channelNotificationSettings": "{\"allNewPosts\":\"On\",\"dskNotif\":\"On\",\"includeReplies\":true}", "isFollowed": true},
240 {"id": "19:a2", "channelNotificationSettings": null, "isFollowed": true},
241 {"id": "19:a3"}
242 ]}
243 ]});
244 let channels = &parse_team_layout(&body).unwrap()[0].channels;
245 assert_eq!(
246 channels[0].notifications,
247 Some(ChannelNotifications {
248 level: crate::ChannelNotificationLevel::BannerAndFeed,
249 include_replies: true
250 })
251 );
252 assert_eq!(
253 (channels[1].notifications, channels[1].followed),
254 (None, true)
255 );
256 assert_eq!(
257 (channels[2].notifications, channels[2].followed),
258 (None, false)
259 );
260 }
261
262 #[test]
263 fn a_channel_without_tabs_has_none() {
264 assert!(parse_channel_tabs(&json!({"id": "19:a@thread.tacv2"})).is_empty());
265 }
266
145 267 #[test]
146 268 fn rejects_an_answer_without_teams() {
147 269 assert!(parse_team_layout(&json!({"chats": []})).is_err());
@@ -4,15 +4,29 @@ use session::Request;
4use super::Pins;
4use super::Pins;
5use super::chats::ensure_success;
5use super::chats::ensure_success;
6use super::transport::CsaTransport;
6use super::transport::CsaTransport;
7use crate::channel_notifications::{ChannelNotifications, parse_property};
7use crate::error::{Error, Result};
8use crate::error::{Error, Result};
8
9
9const TEAMS_QUERY: &str = "isPrefetch=false&enableMembershipSummary=true";
10const TEAMS_QUERY: &str = "isPrefetch=false&enableMembershipSummary=true";
11const WIKI_DEFINITION_ID: &str = "com.microsoft.teamspace.tab.wiki";
12const TAB_URL_KEYS: [&str; 3] = ["websiteUrl", "componentUrl", "url"];
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct ChannelTab {
16 pub id: String,
17 pub name: String,
18 pub definition_id: String,
19 pub open_url: Option<String>,
20}
10
21
11#[derive(Debug, Clone, PartialEq, Eq)]
22#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct ChannelLayout {
23pub struct ChannelLayout {
13 pub channel_id: String,
24 pub channel_id: String,
14 pub general: bool,
25 pub general: bool,
15 pub hidden: bool,
26 pub hidden: bool,
27 pub tabs: Vec<ChannelTab>,
28 pub notifications: Option<ChannelNotifications>,
29 pub followed: bool,
16}
30}
17
31
18#[derive(Debug, Clone, PartialEq, Eq)]
32#[derive(Debug, Clone, PartialEq, Eq)]
@@ -45,6 +59,46 @@ fn flag(value: &Value, key: &str) -> Option<bool> {
45 value.get(key).and_then(Value::as_bool)
59 value.get(key).and_then(Value::as_bool)
46}
60}
47
61
62fn tab_open_url(settings: &Value) -> Option<String> {
63 TAB_URL_KEYS
64 .iter()
65 .filter_map(|key| settings.get(key).and_then(Value::as_str))
66 .map(str::trim)
67 .find(|url| url.starts_with("http") && !url.contains('{'))
68 .map(str::to_owned)
69}
70
71fn parse_tab(tab: &Value) -> Option<(i64, ChannelTab)> {
72 let definition_id = tab.get("definitionId")?.as_str()?;
73 if definition_id == WIKI_DEFINITION_ID {
74 return None;
75 }
76 let order = tab
77 .get("order")
78 .and_then(|order| order.as_i64().or_else(|| order.as_str()?.parse().ok()))
79 .unwrap_or(i64::MAX);
80 let settings = tab.get("settings").unwrap_or(&Value::Null);
81 Some((
82 order,
83 ChannelTab {
84 id: tab.get("id")?.as_str()?.to_owned(),
85 name: tab.get("name")?.as_str()?.to_owned(),
86 definition_id: definition_id.to_owned(),
87 open_url: tab_open_url(settings),
88 },
89 ))
90}
91
92pub fn parse_channel_tabs(channel: &Value) -> Vec<ChannelTab> {
93 let mut tabs: Vec<(i64, ChannelTab)> = channel
94 .get("tabs")
95 .and_then(Value::as_array)
96 .map(|tabs| tabs.iter().filter_map(parse_tab).collect())
97 .unwrap_or_default();
98 tabs.sort_by_key(|(order, _)| *order);
99 tabs.into_iter().map(|(_, tab)| tab).collect()
100}
101
48fn parse_team(team: &Value) -> Option<TeamLayout> {
102fn parse_team(team: &Value) -> Option<TeamLayout> {
49 if flag(team, "isDeleted") == Some(true) {
103 if flag(team, "isDeleted") == Some(true) {
50 return None;
104 return None;
@@ -68,6 +122,12 @@ fn parse_team(team: &Value) -> Option<TeamLayout> {
68 channel_id: channel.get("id")?.as_str()?.to_owned(),
122 channel_id: channel.get("id")?.as_str()?.to_owned(),
69 general,
123 general,
70 hidden: !shown,
124 hidden: !shown,
125 tabs: parse_channel_tabs(channel),
126 notifications: channel
127 .get("channelNotificationSettings")
128 .and_then(Value::as_str)
129 .and_then(parse_property),
130 followed: flag(channel, "isFollowed").unwrap_or(false),
71 })
131 })
72 })
132 })
73 .collect()
133 .collect()
@@ -129,12 +189,18 @@ mod tests {
129 ChannelLayout {
189 ChannelLayout {
130 channel_id: "19:b2@thread.tacv2".into(),
190 channel_id: "19:b2@thread.tacv2".into(),
131 general: false,
191 general: false,
132 hidden: true
192 hidden: true,
193 tabs: Vec::new(),
194 notifications: None,
195 followed: false,
133 },
196 },
134 ChannelLayout {
197 ChannelLayout {
135 channel_id: "19:b@thread.tacv2".into(),
198 channel_id: "19:b@thread.tacv2".into(),
136 general: true,
199 general: true,
137 hidden: false
200 hidden: false,
201 tabs: Vec::new(),
202 notifications: None,
203 followed: false,
138 },
204 },
139 ]
205 ]
140 );
206 );
@@ -142,6 +208,62 @@ mod tests {
142 assert!(!layout[1].channels[1].hidden);
208 assert!(!layout[1].channels[1].hidden);
143 }
209 }
144
210
211 #[test]
212 fn tabs_follow_the_order_field_and_hide_wiki() {
213 let channel = json!({"id": "19:a@thread.tacv2", "tabs": [
214 {"id": "t3", "name": "Notes", "definitionId": "0d820ecd-def2-4297-adad-78056cde7c78",
215 "order": 30, "settings": {
216 "url": "https://onenote.example/{tid}/content",
217 "websiteUrl": "https://onenote.example/web"}},
218 {"id": "t0", "name": "Wiki", "definitionId": "com.microsoft.teamspace.tab.wiki", "order": 5},
219 {"id": "t1", "name": "Docs", "definitionId": "com.microsoft.teamspace.tab.web",
220 "order": 10, "settings": {"url": "https://docs.example", "websiteUrl": "https://docs.example"}},
221 {"id": "t2", "name": "Plan", "definitionId": "com.microsoft.teamspace.tab.planner",
222 "order": "20", "settings": {"url": "https://tasks.example/{locale}"}}
223 ]});
224 let tabs = parse_channel_tabs(&channel);
225 let names: Vec<&str> = tabs.iter().map(|tab| tab.name.as_str()).collect();
226 assert_eq!(names, ["Docs", "Plan", "Notes"]);
227 assert_eq!(tabs[0].open_url.as_deref(), Some("https://docs.example"));
228 assert_eq!(tabs[1].open_url, None);
229 assert_eq!(
230 tabs[2].open_url.as_deref(),
231 Some("https://onenote.example/web")
232 );
233 }
234
235 #[test]
236 fn reads_the_notification_string_and_the_followed_flag() {
237 let body = json!({"teams": [
238 {"id": "19:a@thread.tacv2", "channels": [
239 {"id": "19:a1", "channelNotificationSettings": "{\"allNewPosts\":\"On\",\"dskNotif\":\"On\",\"includeReplies\":true}", "isFollowed": true},
240 {"id": "19:a2", "channelNotificationSettings": null, "isFollowed": true},
241 {"id": "19:a3"}
242 ]}
243 ]});
244 let channels = &parse_team_layout(&body).unwrap()[0].channels;
245 assert_eq!(
246 channels[0].notifications,
247 Some(ChannelNotifications {
248 level: crate::ChannelNotificationLevel::BannerAndFeed,
249 include_replies: true
250 })
251 );
252 assert_eq!(
253 (channels[1].notifications, channels[1].followed),
254 (None, true)
255 );
256 assert_eq!(
257 (channels[2].notifications, channels[2].followed),
258 (None, false)
259 );
260 }
261
262 #[test]
263 fn a_channel_without_tabs_has_none() {
264 assert!(parse_channel_tabs(&json!({"id": "19:a@thread.tacv2"})).is_empty());
265 }
266
145 #[test]
267 #[test]
146 fn rejects_an_answer_without_teams() {
268 fn rejects_an_answer_without_teams() {
147 assert!(parse_team_layout(&json!({"chats": []})).is_err());
269 assert!(parse_team_layout(&json!({"chats": []})).is_err());
crates/chatsvc/src/pins/transport.rs +5 −1
@@ -16,9 +16,13 @@ pub struct SessionTransport {
16 16
17 17 impl SessionTransport {
18 18 pub fn new(session: &Session) -> Self {
19 SessionTransport::with_scope(session, Scope::new(CSA_RESOURCE, CSA_SCOPE))
20 }
21
22 pub fn with_scope(session: &Session, scope: Scope) -> Self {
19 23 SessionTransport {
20 24 session: session.clone(),
21 scope: Scope::new(CSA_RESOURCE, CSA_SCOPE),
25 scope,
22 26 }
23 27 }
24 28 }
@@ -16,9 +16,13 @@ pub struct SessionTransport {
16
16
17impl SessionTransport {
17impl SessionTransport {
18 pub fn new(session: &Session) -> Self {
18 pub fn new(session: &Session) -> Self {
19 SessionTransport::with_scope(session, Scope::new(CSA_RESOURCE, CSA_SCOPE))
20 }
21
22 pub fn with_scope(session: &Session, scope: Scope) -> Self {
19 SessionTransport {
23 SessionTransport {
20 session: session.clone(),
24 session: session.clone(),
21 scope: Scope::new(CSA_RESOURCE, CSA_SCOPE),
25 scope,
22 }
26 }
23 }
27 }
24}
28}
crates/core/src/actions.rs +14 −0
@@ -402,6 +402,20 @@ impl<R: Remote> SyncEngine<R> {
402 402 Ok(())
403 403 }
404 404
405 pub async fn set_channel_notifications(
406 &self,
407 channel_id: &str,
408 notifications: store::ChannelNotifications,
409 ) -> Result<()> {
410 self.remote
411 .set_channel_notifications(channel_id, notifications)
412 .await?;
413 self.store
414 .set_channel_notifications(channel_id, notifications)?;
415 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
416 Ok(())
417 }
418
405 419 pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
406 420 let user_id = self.my_user_id().await?;
407 421 let tenant_id = self.my_tenant_id(chat_id).await?;
@@ -402,6 +402,20 @@ impl<R: Remote> SyncEngine<R> {
402 Ok(())
402 Ok(())
403 }
403 }
404
404
405 pub async fn set_channel_notifications(
406 &self,
407 channel_id: &str,
408 notifications: store::ChannelNotifications,
409 ) -> Result<()> {
410 self.remote
411 .set_channel_notifications(channel_id, notifications)
412 .await?;
413 self.store
414 .set_channel_notifications(channel_id, notifications)?;
415 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
416 Ok(())
417 }
418
405 pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
419 pub async fn hide_chat(&self, chat_id: &str) -> Result<()> {
406 let user_id = self.my_user_id().await?;
420 let user_id = self.my_user_id().await?;
407 let tenant_id = self.my_tenant_id(chat_id).await?;
421 let tenant_id = self.my_tenant_id(chat_id).await?;
crates/core/src/download.rs +40 −0
@@ -4,6 +4,15 @@ use crate::engine::SyncEngine;
4 4 use crate::error::Result;
5 5 use crate::remote::Remote;
6 6
7 #[derive(Debug, Clone, PartialEq, Eq)]
8 pub struct LibraryFile {
9 pub drive_id: String,
10 pub item_id: String,
11 pub name: String,
12 pub size: u64,
13 pub cached_url: Option<String>,
14 }
15
7 16 impl<R: Remote> SyncEngine<R> {
8 17 /// Streams the file behind a OneDrive or SharePoint link chunk by chunk into `write`.
9 18 pub async fn download_file(
@@ -13,6 +22,37 @@ impl<R: Remote> SyncEngine<R> {
13 22 progress: impl Fn(u8) + Send + Sync,
14 23 ) -> Result<SharedFile> {
15 24 let shared = self.remote.resolve_share(open_url).await?;
25 self.stream_file(shared, &mut write, &progress).await
26 }
27
28 /// Like `download_file` for a library entry. A `cached_url` from the listing skips the lookup.
29 pub async fn download_library_file(
30 &self,
31 file: &LibraryFile,
32 mut write: impl FnMut(&[u8]) -> std::io::Result<()> + Send,
33 progress: impl Fn(u8) + Send + Sync,
34 ) -> Result<SharedFile> {
35 let shared = match &file.cached_url {
36 Some(download_url) => SharedFile {
37 name: file.name.clone(),
38 size: file.size,
39 download_url: download_url.clone(),
40 },
41 None => {
42 self.remote
43 .resolve_drive_item(&file.drive_id, &file.item_id)
44 .await?
45 }
46 };
47 self.stream_file(shared, &mut write, &progress).await
48 }
49
50 async fn stream_file(
51 &self,
52 shared: SharedFile,
53 write: &mut (impl FnMut(&[u8]) -> std::io::Result<()> + Send),
54 progress: &(impl Fn(u8) + Send + Sync),
55 ) -> Result<SharedFile> {
16 56 progress(0);
17 57 let ranges = download_ranges(shared.size, DOWNLOAD_CHUNK_BYTES);
18 58 let last = ranges.len().saturating_sub(1);
@@ -4,6 +4,15 @@ use crate::engine::SyncEngine;
4use crate::error::Result;
4use crate::error::Result;
5use crate::remote::Remote;
5use crate::remote::Remote;
6
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct LibraryFile {
9 pub drive_id: String,
10 pub item_id: String,
11 pub name: String,
12 pub size: u64,
13 pub cached_url: Option<String>,
14}
15
7impl<R: Remote> SyncEngine<R> {
16impl<R: Remote> SyncEngine<R> {
8 /// Streams the file behind a OneDrive or SharePoint link chunk by chunk into `write`.
17 /// Streams the file behind a OneDrive or SharePoint link chunk by chunk into `write`.
9 pub async fn download_file(
18 pub async fn download_file(
@@ -13,6 +22,37 @@ impl<R: Remote> SyncEngine<R> {
13 progress: impl Fn(u8) + Send + Sync,
22 progress: impl Fn(u8) + Send + Sync,
14 ) -> Result<SharedFile> {
23 ) -> Result<SharedFile> {
15 let shared = self.remote.resolve_share(open_url).await?;
24 let shared = self.remote.resolve_share(open_url).await?;
25 self.stream_file(shared, &mut write, &progress).await
26 }
27
28 /// Like `download_file` for a library entry. A `cached_url` from the listing skips the lookup.
29 pub async fn download_library_file(
30 &self,
31 file: &LibraryFile,
32 mut write: impl FnMut(&[u8]) -> std::io::Result<()> + Send,
33 progress: impl Fn(u8) + Send + Sync,
34 ) -> Result<SharedFile> {
35 let shared = match &file.cached_url {
36 Some(download_url) => SharedFile {
37 name: file.name.clone(),
38 size: file.size,
39 download_url: download_url.clone(),
40 },
41 None => {
42 self.remote
43 .resolve_drive_item(&file.drive_id, &file.item_id)
44 .await?
45 }
46 };
47 self.stream_file(shared, &mut write, &progress).await
48 }
49
50 async fn stream_file(
51 &self,
52 shared: SharedFile,
53 write: &mut (impl FnMut(&[u8]) -> std::io::Result<()> + Send),
54 progress: &(impl Fn(u8) + Send + Sync),
55 ) -> Result<SharedFile> {
16 progress(0);
56 progress(0);
17 let ranges = download_ranges(shared.size, DOWNLOAD_CHUNK_BYTES);
57 let ranges = download_ranges(shared.size, DOWNLOAD_CHUNK_BYTES);
18 let last = ranges.len().saturating_sub(1);
58 let last = ranges.len().saturating_sub(1);
crates/core/src/folders.rs +127 −8
@@ -1,11 +1,15 @@
1 use std::collections::HashMap;
1 2 use std::future::Future;
2 3 use std::pin::Pin;
3 4 use std::sync::Arc;
4 5
5 use chatsvc::{ChatSection, ChatSectionSettings, Pins, UserSettings, pins::SessionTransport};
6 use chatsvc::{
7 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection,
8 ChatSectionSettings, Pins, UserSettings, pins::SessionTransport,
9 };
6 10 use chrono::Utc;
7 11 use session::Session;
8 use store::{ChannelLayoutRecord, FolderRecord, Store, TeamLayoutRecord};
12 use store::{ChannelLayoutRecord, ChannelTabRecord, FolderRecord, Store, TeamLayoutRecord};
9 13
10 14 use crate::engine::SyncEngine;
11 15 use crate::error::{Error, Result};
@@ -59,6 +63,7 @@ pub trait FolderSource: Send + Sync {
59 63 pub struct ChatsvcFolderSource {
60 64 pins: Pins<SessionTransport>,
61 65 settings: UserSettings,
66 channel_settings: ChannelSettings,
62 67 }
63 68
64 69 impl ChatsvcFolderSource {
@@ -66,6 +71,7 @@ impl ChatsvcFolderSource {
66 71 ChatsvcFolderSource {
67 72 pins: Pins::new(session),
68 73 settings: UserSettings::new(session),
74 channel_settings: ChannelSettings::new(session),
69 75 }
70 76 }
71 77 }
@@ -81,12 +87,24 @@ impl FolderSource for ChatsvcFolderSource {
81 87
82 88 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
83 89 Box::pin(async {
84 Ok(self
85 .pins
86 .team_layout()
87 .await?
90 let layout = self.pins.team_layout().await?;
91 let unknown: Vec<String> = layout
92 .iter()
93 .flat_map(|team| &team.channels)
94 .filter(|channel| channel.notifications.is_none())
95 .map(|channel| channel.channel_id.clone())
96 .collect();
97 let fallback = if unknown.is_empty() {
98 HashMap::new()
99 } else {
100 self.channel_settings
101 .fetch(&unknown)
102 .await
103 .unwrap_or_default()
104 };
105 Ok(layout
88 106 .into_iter()
89 .map(layout_record)
107 .map(|team| layout_record(team, &fallback))
90 108 .collect())
91 109 })
92 110 }
@@ -160,7 +178,48 @@ fn convert(folders: chatsvc::Folders) -> Vec<ChatFolder> {
160 178 .collect()
161 179 }
162 180
163 fn layout_record(team: chatsvc::TeamLayout) -> TeamLayoutRecord {
181 fn resolve_notifications(
182 channel: &chatsvc::ChannelLayout,
183 fallback: &HashMap<String, ChannelNotifications>,
184 ) -> ChannelNotifications {
185 channel
186 .notifications
187 .or_else(|| fallback.get(&channel.channel_id).copied())
188 .unwrap_or_else(|| ChannelNotifications::from_followed(channel.followed))
189 }
190
191 fn notification_record(notifications: ChannelNotifications) -> store::ChannelNotifications {
192 store::ChannelNotifications {
193 level: match notifications.level {
194 ChannelNotificationLevel::BannerAndFeed => {
195 store::ChannelNotificationLevel::BannerAndFeed
196 }
197 ChannelNotificationLevel::Feed => store::ChannelNotificationLevel::Feed,
198 ChannelNotificationLevel::Off => store::ChannelNotificationLevel::Off,
199 },
200 include_replies: notifications.include_replies,
201 }
202 }
203
204 pub(crate) fn chatsvc_notifications(
205 notifications: store::ChannelNotifications,
206 ) -> ChannelNotifications {
207 ChannelNotifications {
208 level: match notifications.level {
209 store::ChannelNotificationLevel::BannerAndFeed => {
210 ChannelNotificationLevel::BannerAndFeed
211 }
212 store::ChannelNotificationLevel::Feed => ChannelNotificationLevel::Feed,
213 store::ChannelNotificationLevel::Off => ChannelNotificationLevel::Off,
214 },
215 include_replies: notifications.include_replies,
216 }
217 }
218
219 fn layout_record(
220 team: chatsvc::TeamLayout,
221 fallback: &HashMap<String, ChannelNotifications>,
222 ) -> TeamLayoutRecord {
164 223 TeamLayoutRecord {
165 224 team_id: team.team_id,
166 225 hidden: team.hidden,
@@ -168,9 +227,20 @@ fn layout_record(team: chatsvc::TeamLayout) -> TeamLayoutRecord {
168 227 .channels
169 228 .into_iter()
170 229 .map(|channel| ChannelLayoutRecord {
230 notifications: notification_record(resolve_notifications(&channel, fallback)),
171 231 channel_id: channel.channel_id,
172 232 general: channel.general,
173 233 hidden: channel.hidden,
234 tabs: channel
235 .tabs
236 .into_iter()
237 .map(|tab| ChannelTabRecord {
238 tab_id: tab.id,
239 name: tab.name,
240 definition_id: tab.definition_id,
241 open_url: tab.open_url,
242 })
243 .collect(),
174 244 })
175 245 .collect(),
176 246 }
@@ -346,3 +416,52 @@ impl<R: Remote> SyncEngine<R> {
346 416 Ok(())
347 417 }
348 418 }
419
420 #[cfg(test)]
421 mod tests {
422 use super::*;
423
424 fn channel(
425 notifications: Option<ChannelNotifications>,
426 followed: bool,
427 ) -> chatsvc::ChannelLayout {
428 chatsvc::ChannelLayout {
429 channel_id: "19:a".into(),
430 general: false,
431 hidden: false,
432 tabs: Vec::new(),
433 notifications,
434 followed,
435 }
436 }
437
438 fn level(level: ChannelNotificationLevel, include_replies: bool) -> ChannelNotifications {
439 ChannelNotifications {
440 level,
441 include_replies,
442 }
443 }
444
445 #[test]
446 fn channel_value_beats_the_notification_service_beats_the_followed_flag() {
447 let off = level(ChannelNotificationLevel::Off, false);
448 let banner = level(ChannelNotificationLevel::BannerAndFeed, true);
449 let fallback = HashMap::from([("19:a".to_owned(), banner)]);
450 assert_eq!(
451 resolve_notifications(&channel(Some(off), true), &fallback),
452 off
453 );
454 assert_eq!(
455 resolve_notifications(&channel(None, false), &fallback),
456 banner
457 );
458 assert_eq!(
459 resolve_notifications(&channel(None, true), &HashMap::new()),
460 banner
461 );
462 assert_eq!(
463 resolve_notifications(&channel(None, false), &HashMap::new()),
464 ChannelNotifications::default()
465 );
466 }
467 }
@@ -1,11 +1,15 @@
1use std::collections::HashMap;
1use std::future::Future;
2use std::future::Future;
2use std::pin::Pin;
3use std::pin::Pin;
3use std::sync::Arc;
4use std::sync::Arc;
4
5
5use chatsvc::{ChatSection, ChatSectionSettings, Pins, UserSettings, pins::SessionTransport};
6use chatsvc::{
7 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection,
8 ChatSectionSettings, Pins, UserSettings, pins::SessionTransport,
9};
6use chrono::Utc;
10use chrono::Utc;
7use session::Session;
11use session::Session;
8use store::{ChannelLayoutRecord, FolderRecord, Store, TeamLayoutRecord};
12use store::{ChannelLayoutRecord, ChannelTabRecord, FolderRecord, Store, TeamLayoutRecord};
9
13
10use crate::engine::SyncEngine;
14use crate::engine::SyncEngine;
11use crate::error::{Error, Result};
15use crate::error::{Error, Result};
@@ -59,6 +63,7 @@ pub trait FolderSource: Send + Sync {
59pub struct ChatsvcFolderSource {
63pub struct ChatsvcFolderSource {
60 pins: Pins<SessionTransport>,
64 pins: Pins<SessionTransport>,
61 settings: UserSettings,
65 settings: UserSettings,
66 channel_settings: ChannelSettings,
62}
67}
63
68
64impl ChatsvcFolderSource {
69impl ChatsvcFolderSource {
@@ -66,6 +71,7 @@ impl ChatsvcFolderSource {
66 ChatsvcFolderSource {
71 ChatsvcFolderSource {
67 pins: Pins::new(session),
72 pins: Pins::new(session),
68 settings: UserSettings::new(session),
73 settings: UserSettings::new(session),
74 channel_settings: ChannelSettings::new(session),
69 }
75 }
70 }
76 }
71}
77}
@@ -81,12 +87,24 @@ impl FolderSource for ChatsvcFolderSource {
81
87
82 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
88 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
83 Box::pin(async {
89 Box::pin(async {
84 Ok(self
90 let layout = self.pins.team_layout().await?;
85 .pins
91 let unknown: Vec<String> = layout
86 .team_layout()
92 .iter()
87 .await?
93 .flat_map(|team| &team.channels)
94 .filter(|channel| channel.notifications.is_none())
95 .map(|channel| channel.channel_id.clone())
96 .collect();
97 let fallback = if unknown.is_empty() {
98 HashMap::new()
99 } else {
100 self.channel_settings
101 .fetch(&unknown)
102 .await
103 .unwrap_or_default()
104 };
105 Ok(layout
88 .into_iter()
106 .into_iter()
89 .map(layout_record)
107 .map(|team| layout_record(team, &fallback))
90 .collect())
108 .collect())
91 })
109 })
92 }
110 }
@@ -160,7 +178,48 @@ fn convert(folders: chatsvc::Folders) -> Vec<ChatFolder> {
160 .collect()
178 .collect()
161}
179}
162
180
163fn layout_record(team: chatsvc::TeamLayout) -> TeamLayoutRecord {
181fn resolve_notifications(
182 channel: &chatsvc::ChannelLayout,
183 fallback: &HashMap<String, ChannelNotifications>,
184) -> ChannelNotifications {
185 channel
186 .notifications
187 .or_else(|| fallback.get(&channel.channel_id).copied())
188 .unwrap_or_else(|| ChannelNotifications::from_followed(channel.followed))
189}
190
191fn notification_record(notifications: ChannelNotifications) -> store::ChannelNotifications {
192 store::ChannelNotifications {
193 level: match notifications.level {
194 ChannelNotificationLevel::BannerAndFeed => {
195 store::ChannelNotificationLevel::BannerAndFeed
196 }
197 ChannelNotificationLevel::Feed => store::ChannelNotificationLevel::Feed,
198 ChannelNotificationLevel::Off => store::ChannelNotificationLevel::Off,
199 },
200 include_replies: notifications.include_replies,
201 }
202}
203
204pub(crate) fn chatsvc_notifications(
205 notifications: store::ChannelNotifications,
206) -> ChannelNotifications {
207 ChannelNotifications {
208 level: match notifications.level {
209 store::ChannelNotificationLevel::BannerAndFeed => {
210 ChannelNotificationLevel::BannerAndFeed
211 }
212 store::ChannelNotificationLevel::Feed => ChannelNotificationLevel::Feed,
213 store::ChannelNotificationLevel::Off => ChannelNotificationLevel::Off,
214 },
215 include_replies: notifications.include_replies,
216 }
217}
218
219fn layout_record(
220 team: chatsvc::TeamLayout,
221 fallback: &HashMap<String, ChannelNotifications>,
222) -> TeamLayoutRecord {
164 TeamLayoutRecord {
223 TeamLayoutRecord {
165 team_id: team.team_id,
224 team_id: team.team_id,
166 hidden: team.hidden,
225 hidden: team.hidden,
@@ -168,9 +227,20 @@ fn layout_record(team: chatsvc::TeamLayout) -> TeamLayoutRecord {
168 .channels
227 .channels
169 .into_iter()
228 .into_iter()
170 .map(|channel| ChannelLayoutRecord {
229 .map(|channel| ChannelLayoutRecord {
230 notifications: notification_record(resolve_notifications(&channel, fallback)),
171 channel_id: channel.channel_id,
231 channel_id: channel.channel_id,
172 general: channel.general,
232 general: channel.general,
173 hidden: channel.hidden,
233 hidden: channel.hidden,
234 tabs: channel
235 .tabs
236 .into_iter()
237 .map(|tab| ChannelTabRecord {
238 tab_id: tab.id,
239 name: tab.name,
240 definition_id: tab.definition_id,
241 open_url: tab.open_url,
242 })
243 .collect(),
174 })
244 })
175 .collect(),
245 .collect(),
176 }
246 }
@@ -346,3 +416,52 @@ impl<R: Remote> SyncEngine<R> {
346 Ok(())
416 Ok(())
347 }
417 }
348}
418}
419
420#[cfg(test)]
421mod tests {
422 use super::*;
423
424 fn channel(
425 notifications: Option<ChannelNotifications>,
426 followed: bool,
427 ) -> chatsvc::ChannelLayout {
428 chatsvc::ChannelLayout {
429 channel_id: "19:a".into(),
430 general: false,
431 hidden: false,
432 tabs: Vec::new(),
433 notifications,
434 followed,
435 }
436 }
437
438 fn level(level: ChannelNotificationLevel, include_replies: bool) -> ChannelNotifications {
439 ChannelNotifications {
440 level,
441 include_replies,
442 }
443 }
444
445 #[test]
446 fn channel_value_beats_the_notification_service_beats_the_followed_flag() {
447 let off = level(ChannelNotificationLevel::Off, false);
448 let banner = level(ChannelNotificationLevel::BannerAndFeed, true);
449 let fallback = HashMap::from([("19:a".to_owned(), banner)]);
450 assert_eq!(
451 resolve_notifications(&channel(Some(off), true), &fallback),
452 off
453 );
454 assert_eq!(
455 resolve_notifications(&channel(None, false), &fallback),
456 banner
457 );
458 assert_eq!(
459 resolve_notifications(&channel(None, true), &HashMap::new()),
460 banner
461 );
462 assert_eq!(
463 resolve_notifications(&channel(None, false), &HashMap::new()),
464 ChannelNotifications::default()
465 );
466 }
467}
crates/core/src/lib.rs +8 −4
@@ -21,6 +21,7 @@ mod gifs;
21 21 mod image_size;
22 22 mod images;
23 23 mod italic;
24 mod library;
24 25 mod link_sync;
25 26 mod links;
26 27 mod mapping;
@@ -89,15 +90,18 @@ pub use folders::{
89 90 stored_section_settings,
90 91 };
91 92 pub use graph::{
92 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,
93 UploadedFile,
93 DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
94 MessageExtras, SharedFile, UploadedFile,
94 95 };
96 pub use download::LibraryFile;
95 97 pub use images::StoredImage;
96 pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};
98 pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, public_links};
97 99 pub use mapping::{chat_record, message_record};
98 100 pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};
99 101 pub use mentions::MentionInput;
100 pub use message_link::{ChannelLinkInput, channel_message_link, chat_message_link};
102 pub use message_link::{
103 ChannelLinkInput, channel_message_link, channel_tab_link, chat_message_link,
104 };
101 105 pub use people::{MentionCandidate, PersonCandidate, PersonSource};
102 106 pub use presence::{Availability, Presence};
103 107 pub use preview::preview_text;
@@ -21,6 +21,7 @@ mod gifs;
21mod image_size;
21mod image_size;
22mod images;
22mod images;
23mod italic;
23mod italic;
24mod library;
24mod link_sync;
25mod link_sync;
25mod links;
26mod links;
26mod mapping;
27mod mapping;
@@ -89,15 +90,18 @@ pub use folders::{
89 stored_section_settings,
90 stored_section_settings,
90};
91};
91pub use graph::{
92pub use graph::{
92 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,
93 DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
93 UploadedFile,
94 MessageExtras, SharedFile, UploadedFile,
94};
95};
96pub use download::LibraryFile;
95pub use images::StoredImage;
97pub use images::StoredImage;
96pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};
98pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, public_links};
97pub use mapping::{chat_record, message_record};
99pub use mapping::{chat_record, message_record};
98pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};
100pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};
99pub use mentions::MentionInput;
101pub use mentions::MentionInput;
100pub use message_link::{ChannelLinkInput, channel_message_link, chat_message_link};
102pub use message_link::{
103 ChannelLinkInput, channel_message_link, channel_tab_link, chat_message_link,
104};
101pub use people::{MentionCandidate, PersonCandidate, PersonSource};
105pub use people::{MentionCandidate, PersonCandidate, PersonSource};
102pub use presence::{Availability, Presence};
106pub use presence::{Availability, Presence};
103pub use preview::preview_text;
107pub use preview::preview_text;
crates/core/src/library.rs added +56 −0
@@ -0,0 +1,56 @@
1 use graph::{DriveEntry, DriveFolder, UploadDestination, UploadedFile};
2
3 use crate::engine::{Conversation, SyncEngine};
4 use crate::error::{Error, Result};
5 use crate::remote::Remote;
6
7 impl<R: Remote> SyncEngine<R> {
8 pub async fn channel_library_root(&self, channel_id: &str) -> Result<DriveEntry> {
9 let Conversation::Channel { team_id } = self.resolve(channel_id)? else {
10 return Err(Error::Unsupported("a library for a chat"));
11 };
12 self.remote.channel_files_root(&team_id, channel_id).await
13 }
14
15 pub async fn channel_tab_web_url(
16 &self,
17 channel_id: &str,
18 tab_id: &str,
19 ) -> Result<Option<String>> {
20 let Conversation::Channel { team_id } = self.resolve(channel_id)? else {
21 return Err(Error::Unsupported("a tab link for a chat"));
22 };
23 self.remote
24 .channel_tab_web_url(&team_id, channel_id, tab_id)
25 .await
26 }
27
28 pub async fn library_children(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {
29 self.remote.list_children(folder).await
30 }
31
32 pub async fn create_library_folder(
33 &self,
34 parent: &DriveFolder,
35 name: &str,
36 ) -> Result<DriveEntry> {
37 self.remote.create_folder(parent, name).await
38 }
39
40 pub async fn upload_to_library(
41 &self,
42 folder: &DriveFolder,
43 file_name: &str,
44 bytes: &[u8],
45 progress: impl Fn(u8) + Send + Sync,
46 ) -> Result<UploadedFile> {
47 self.remote
48 .upload_file(
49 &UploadDestination::Folder(folder.clone()),
50 file_name,
51 bytes,
52 &progress,
53 )
54 .await
55 }
56 }
@@ -0,0 +1,56 @@
1use graph::{DriveEntry, DriveFolder, UploadDestination, UploadedFile};
2
3use crate::engine::{Conversation, SyncEngine};
4use crate::error::{Error, Result};
5use crate::remote::Remote;
6
7impl<R: Remote> SyncEngine<R> {
8 pub async fn channel_library_root(&self, channel_id: &str) -> Result<DriveEntry> {
9 let Conversation::Channel { team_id } = self.resolve(channel_id)? else {
10 return Err(Error::Unsupported("a library for a chat"));
11 };
12 self.remote.channel_files_root(&team_id, channel_id).await
13 }
14
15 pub async fn channel_tab_web_url(
16 &self,
17 channel_id: &str,
18 tab_id: &str,
19 ) -> Result<Option<String>> {
20 let Conversation::Channel { team_id } = self.resolve(channel_id)? else {
21 return Err(Error::Unsupported("a tab link for a chat"));
22 };
23 self.remote
24 .channel_tab_web_url(&team_id, channel_id, tab_id)
25 .await
26 }
27
28 pub async fn library_children(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {
29 self.remote.list_children(folder).await
30 }
31
32 pub async fn create_library_folder(
33 &self,
34 parent: &DriveFolder,
35 name: &str,
36 ) -> Result<DriveEntry> {
37 self.remote.create_folder(parent, name).await
38 }
39
40 pub async fn upload_to_library(
41 &self,
42 folder: &DriveFolder,
43 file_name: &str,
44 bytes: &[u8],
45 progress: impl Fn(u8) + Send + Sync,
46 ) -> Result<UploadedFile> {
47 self.remote
48 .upload_file(
49 &UploadDestination::Folder(folder.clone()),
50 file_name,
51 bytes,
52 &progress,
53 )
54 .await
55 }
56}
crates/core/src/remote.rs +69 −1
@@ -6,7 +6,7 @@ use chatsvc::{
6 6 };
7 7 use chrono::{DateTime, Utc};
8 8 use graph::{
9 Channel, Chat, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
9 Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
10 10 OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,
11 11 };
12 12
@@ -121,6 +121,11 @@ pub trait Remote {
121 121 async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
122 122 async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>>;
123 123 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
124 async fn set_channel_notifications(
125 &self,
126 channel_id: &str,
127 notifications: store::ChannelNotifications,
128 ) -> Result<()>;
124 129 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()>;
125 130 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
126 131 async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
@@ -156,6 +161,27 @@ pub trait Remote {
156 161 Err(Error::Unsupported("a channel files folder"))
157 162 }
158 163
164 async fn channel_files_root(&self, _team_id: &str, _channel_id: &str) -> Result<DriveEntry> {
165 Err(Error::Unsupported("a channel library"))
166 }
167
168 async fn channel_tab_web_url(
169 &self,
170 _team_id: &str,
171 _channel_id: &str,
172 _tab_id: &str,
173 ) -> Result<Option<String>> {
174 Err(Error::Unsupported("a channel tab link"))
175 }
176
177 async fn list_children(&self, _folder: &DriveFolder) -> Result<Vec<DriveEntry>> {
178 Err(Error::Unsupported("a folder listing"))
179 }
180
181 async fn create_folder(&self, _parent: &DriveFolder, _name: &str) -> Result<DriveEntry> {
182 Err(Error::Unsupported("creating a folder"))
183 }
184
159 185 async fn upload_file(
160 186 &self,
161 187 _destination: &UploadDestination,
@@ -178,6 +204,10 @@ pub trait Remote {
178 204 Err(Error::Unsupported("resolving a shared file"))
179 205 }
180 206
207 async fn resolve_drive_item(&self, _drive_id: &str, _item_id: &str) -> Result<SharedFile> {
208 Err(Error::Unsupported("resolving a drive item"))
209 }
210
181 211 async fn download_range(
182 212 &self,
183 213 _download_url: &str,
@@ -527,6 +557,19 @@ impl Remote for Graph {
527 557 .await?)
528 558 }
529 559
560 async fn set_channel_notifications(
561 &self,
562 channel_id: &str,
563 notifications: store::ChannelNotifications,
564 ) -> Result<()> {
565 Ok(Conversations::new(self.session())
566 .set_channel_notifications(
567 channel_id,
568 crate::folders::chatsvc_notifications(notifications),
569 )
570 .await?)
571 }
572
530 573 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
531 574 Ok(Messages::new(self.session())
532 575 .send_typing(conversation, active)
@@ -617,6 +660,27 @@ impl Remote for Graph {
617 660 Ok(Graph::channel_files_folder(self, team_id, channel_id).await?)
618 661 }
619 662
663 async fn channel_files_root(&self, team_id: &str, channel_id: &str) -> Result<DriveEntry> {
664 Ok(Graph::channel_files_root(self, team_id, channel_id).await?)
665 }
666
667 async fn channel_tab_web_url(
668 &self,
669 team_id: &str,
670 channel_id: &str,
671 tab_id: &str,
672 ) -> Result<Option<String>> {
673 Ok(Graph::channel_tab_web_url(self, team_id, channel_id, tab_id).await?)
674 }
675
676 async fn list_children(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {
677 Ok(Graph::list_children(self, folder).await?)
678 }
679
680 async fn create_folder(&self, parent: &DriveFolder, name: &str) -> Result<DriveEntry> {
681 Ok(Graph::create_folder(self, parent, name).await?)
682 }
683
620 684 async fn upload_file(
621 685 &self,
622 686 destination: &UploadDestination,
@@ -639,6 +703,10 @@ impl Remote for Graph {
639 703 Ok(Graph::resolve_share(self, open_url).await?)
640 704 }
641 705
706 async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {
707 Ok(Graph::resolve_drive_item(self, drive_id, item_id).await?)
708 }
709
642 710 async fn download_range(
643 711 &self,
644 712 download_url: &str,
@@ -6,7 +6,7 @@ use chatsvc::{
6};
6};
7use chrono::{DateTime, Utc};
7use chrono::{DateTime, Utc};
8use graph::{
8use graph::{
9 Channel, Chat, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
9 Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
10 OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,
10 OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,
11};
11};
12
12
@@ -121,6 +121,11 @@ pub trait Remote {
121 async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
121 async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()>;
122 async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>>;
122 async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>>;
123 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
123 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
124 async fn set_channel_notifications(
125 &self,
126 channel_id: &str,
127 notifications: store::ChannelNotifications,
128 ) -> Result<()>;
124 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()>;
129 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()>;
125 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
130 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
126 async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
131 async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
@@ -156,6 +161,27 @@ pub trait Remote {
156 Err(Error::Unsupported("a channel files folder"))
161 Err(Error::Unsupported("a channel files folder"))
157 }
162 }
158
163
164 async fn channel_files_root(&self, _team_id: &str, _channel_id: &str) -> Result<DriveEntry> {
165 Err(Error::Unsupported("a channel library"))
166 }
167
168 async fn channel_tab_web_url(
169 &self,
170 _team_id: &str,
171 _channel_id: &str,
172 _tab_id: &str,
173 ) -> Result<Option<String>> {
174 Err(Error::Unsupported("a channel tab link"))
175 }
176
177 async fn list_children(&self, _folder: &DriveFolder) -> Result<Vec<DriveEntry>> {
178 Err(Error::Unsupported("a folder listing"))
179 }
180
181 async fn create_folder(&self, _parent: &DriveFolder, _name: &str) -> Result<DriveEntry> {
182 Err(Error::Unsupported("creating a folder"))
183 }
184
159 async fn upload_file(
185 async fn upload_file(
160 &self,
186 &self,
161 _destination: &UploadDestination,
187 _destination: &UploadDestination,
@@ -178,6 +204,10 @@ pub trait Remote {
178 Err(Error::Unsupported("resolving a shared file"))
204 Err(Error::Unsupported("resolving a shared file"))
179 }
205 }
180
206
207 async fn resolve_drive_item(&self, _drive_id: &str, _item_id: &str) -> Result<SharedFile> {
208 Err(Error::Unsupported("resolving a drive item"))
209 }
210
181 async fn download_range(
211 async fn download_range(
182 &self,
212 &self,
183 _download_url: &str,
213 _download_url: &str,
@@ -527,6 +557,19 @@ impl Remote for Graph {
527 .await?)
557 .await?)
528 }
558 }
529
559
560 async fn set_channel_notifications(
561 &self,
562 channel_id: &str,
563 notifications: store::ChannelNotifications,
564 ) -> Result<()> {
565 Ok(Conversations::new(self.session())
566 .set_channel_notifications(
567 channel_id,
568 crate::folders::chatsvc_notifications(notifications),
569 )
570 .await?)
571 }
572
530 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
573 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
531 Ok(Messages::new(self.session())
574 Ok(Messages::new(self.session())
532 .send_typing(conversation, active)
575 .send_typing(conversation, active)
@@ -617,6 +660,27 @@ impl Remote for Graph {
617 Ok(Graph::channel_files_folder(self, team_id, channel_id).await?)
660 Ok(Graph::channel_files_folder(self, team_id, channel_id).await?)
618 }
661 }
619
662
663 async fn channel_files_root(&self, team_id: &str, channel_id: &str) -> Result<DriveEntry> {
664 Ok(Graph::channel_files_root(self, team_id, channel_id).await?)
665 }
666
667 async fn channel_tab_web_url(
668 &self,
669 team_id: &str,
670 channel_id: &str,
671 tab_id: &str,
672 ) -> Result<Option<String>> {
673 Ok(Graph::channel_tab_web_url(self, team_id, channel_id, tab_id).await?)
674 }
675
676 async fn list_children(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {
677 Ok(Graph::list_children(self, folder).await?)
678 }
679
680 async fn create_folder(&self, parent: &DriveFolder, name: &str) -> Result<DriveEntry> {
681 Ok(Graph::create_folder(self, parent, name).await?)
682 }
683
620 async fn upload_file(
684 async fn upload_file(
621 &self,
685 &self,
622 destination: &UploadDestination,
686 destination: &UploadDestination,
@@ -639,6 +703,10 @@ impl Remote for Graph {
639 Ok(Graph::resolve_share(self, open_url).await?)
703 Ok(Graph::resolve_share(self, open_url).await?)
640 }
704 }
641
705
706 async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {
707 Ok(Graph::resolve_drive_item(self, drive_id, item_id).await?)
708 }
709
642 async fn download_range(
710 async fn download_range(
643 &self,
711 &self,
644 download_url: &str,
712 download_url: &str,
crates/core/tests/engine.rs +105 −0
@@ -448,6 +448,19 @@ impl Remote for Handle {
448 448 Ok(())
449 449 }
450 450
451 async fn set_channel_notifications(
452 &self,
453 channel_id: &str,
454 notifications: store::ChannelNotifications,
455 ) -> Result<()> {
456 self.record(format!(
457 "channel notifications {channel_id} {} {}",
458 notifications.level.key(),
459 notifications.include_replies
460 ));
461 Ok(())
462 }
463
451 464 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
452 465 self.record(format!(
453 466 "typing {} {active}",
@@ -572,6 +585,15 @@ impl Remote for Handle {
572 585 })
573 586 }
574 587
588 async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {
589 self.record(format!("resolve item {drive_id}/{item_id}"));
590 Ok(SharedFile {
591 name: "big.bin".into(),
592 size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3,
593 download_url: "https://dl.example/fresh".into(),
594 })
595 }
596
575 597 async fn download_range(
576 598 &self,
577 599 download_url: &str,
@@ -1590,6 +1612,45 @@ async fn download_streams_every_chunk_and_reports_progress() {
1590 1612 assert!(percents.windows(2).all(|pair| pair[0] <= pair[1]));
1591 1613 }
1592 1614
1615 #[tokio::test]
1616 async fn library_download_uses_the_listing_url_and_refetches_the_item_without_one() {
1617 let library_file = |cached_url: Option<&str>| teams_core::LibraryFile {
1618 drive_id: "drive".into(),
1619 item_id: "item".into(),
1620 name: "big.bin".into(),
1621 size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3,
1622 cached_url: cached_url.map(str::to_owned),
1623 };
1624 let fake = Arc::new(Fake::default());
1625 let engine = chat_engine(&fake, small_pages()).await;
1626 engine
1627 .download_library_file(
1628 &library_file(Some("https://dl.example/listed")),
1629 |_| Ok(()),
1630 |_| {},
1631 )
1632 .await
1633 .unwrap();
1634 let calls = fake.calls();
1635 assert!(!calls.iter().any(|call| call.starts_with("resolve")));
1636 assert!(
1637 calls
1638 .iter()
1639 .any(|call| call.starts_with("range https://dl.example/listed "))
1640 );
1641 engine
1642 .download_library_file(&library_file(None), |_| Ok(()), |_| {})
1643 .await
1644 .unwrap();
1645 let calls = fake.calls();
1646 assert!(calls.contains(&"resolve item drive/item".to_owned()));
1647 assert!(
1648 calls
1649 .iter()
1650 .any(|call| call.starts_with("range https://dl.example/fresh "))
1651 );
1652 }
1653
1593 1654 #[tokio::test]
1594 1655 async fn download_keeps_a_file_that_grew_past_the_reported_size() {
1595 1656 let fake = Arc::new(Fake::default());
@@ -2344,6 +2405,8 @@ async fn team_layout_from_teams_orders_and_hides_the_sidebar() {
2344 2405 channel_id: "zeta-old".into(),
2345 2406 general: false,
2346 2407 hidden: true,
2408 tabs: Vec::new(),
2409 notifications: Default::default(),
2347 2410 }],
2348 2411 },
2349 2412 TeamLayoutRecord {
@@ -2390,6 +2453,48 @@ async fn team_layout_from_teams_orders_and_hides_the_sidebar() {
2390 2453 assert!(received.contains(&CoreEvent::SidebarChanged));
2391 2454 }
2392 2455
2456 #[tokio::test]
2457 async fn channel_notifications_go_to_the_service_then_the_store() {
2458 let fake = Arc::new(Fake::default());
2459 let engine = engine_with(&fake, SyncConfig::default());
2460 engine
2461 .store()
2462 .upsert_teams(&[TeamRecord {
2463 id: "alpha".into(),
2464 name: "alpha".into(),
2465 }])
2466 .unwrap();
2467 engine
2468 .store()
2469 .upsert_channels(&[ChannelRecord {
2470 id: "alpha-news".into(),
2471 team_id: "alpha".into(),
2472 name: "News".into(),
2473 membership_type: None,
2474 last_message_at: None,
2475 unread: false,
2476 }])
2477 .unwrap();
2478 let mut events = engine.subscribe();
2479 let banner = store::ChannelNotifications {
2480 level: store::ChannelNotificationLevel::BannerAndFeed,
2481 include_replies: true,
2482 };
2483
2484 engine
2485 .set_channel_notifications("alpha-news", banner)
2486 .await
2487 .unwrap();
2488
2489 assert_eq!(
2490 fake.calls().last().unwrap(),
2491 "channel notifications alpha-news banner true"
2492 );
2493 let teams = engine.store().sidebar().unwrap().teams;
2494 assert_eq!(teams[0].channel_notifications("alpha-news"), banner);
2495 assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
2496 }
2497
2393 2498 #[tokio::test]
2394 2499 async fn folders_without_a_source_are_unsupported() {
2395 2500 let fake = Arc::new(Fake::default());
@@ -448,6 +448,19 @@ impl Remote for Handle {
448 Ok(())
448 Ok(())
449 }
449 }
450
450
451 async fn set_channel_notifications(
452 &self,
453 channel_id: &str,
454 notifications: store::ChannelNotifications,
455 ) -> Result<()> {
456 self.record(format!(
457 "channel notifications {channel_id} {} {}",
458 notifications.level.key(),
459 notifications.include_replies
460 ));
461 Ok(())
462 }
463
451 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
464 async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
452 self.record(format!(
465 self.record(format!(
453 "typing {} {active}",
466 "typing {} {active}",
@@ -572,6 +585,15 @@ impl Remote for Handle {
572 })
585 })
573 }
586 }
574
587
588 async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {
589 self.record(format!("resolve item {drive_id}/{item_id}"));
590 Ok(SharedFile {
591 name: "big.bin".into(),
592 size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3,
593 download_url: "https://dl.example/fresh".into(),
594 })
595 }
596
575 async fn download_range(
597 async fn download_range(
576 &self,
598 &self,
577 download_url: &str,
599 download_url: &str,
@@ -1590,6 +1612,45 @@ async fn download_streams_every_chunk_and_reports_progress() {
1590 assert!(percents.windows(2).all(|pair| pair[0] <= pair[1]));
1612 assert!(percents.windows(2).all(|pair| pair[0] <= pair[1]));
1591}
1613}
1592
1614
1615#[tokio::test]
1616async fn library_download_uses_the_listing_url_and_refetches_the_item_without_one() {
1617 let library_file = |cached_url: Option<&str>| teams_core::LibraryFile {
1618 drive_id: "drive".into(),
1619 item_id: "item".into(),
1620 name: "big.bin".into(),
1621 size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3,
1622 cached_url: cached_url.map(str::to_owned),
1623 };
1624 let fake = Arc::new(Fake::default());
1625 let engine = chat_engine(&fake, small_pages()).await;
1626 engine
1627 .download_library_file(
1628 &library_file(Some("https://dl.example/listed")),
1629 |_| Ok(()),
1630 |_| {},
1631 )
1632 .await
1633 .unwrap();
1634 let calls = fake.calls();
1635 assert!(!calls.iter().any(|call| call.starts_with("resolve")));
1636 assert!(
1637 calls
1638 .iter()
1639 .any(|call| call.starts_with("range https://dl.example/listed "))
1640 );
1641 engine
1642 .download_library_file(&library_file(None), |_| Ok(()), |_| {})
1643 .await
1644 .unwrap();
1645 let calls = fake.calls();
1646 assert!(calls.contains(&"resolve item drive/item".to_owned()));
1647 assert!(
1648 calls
1649 .iter()
1650 .any(|call| call.starts_with("range https://dl.example/fresh "))
1651 );
1652}
1653
1593#[tokio::test]
1654#[tokio::test]
1594async fn download_keeps_a_file_that_grew_past_the_reported_size() {
1655async fn download_keeps_a_file_that_grew_past_the_reported_size() {
1595 let fake = Arc::new(Fake::default());
1656 let fake = Arc::new(Fake::default());
@@ -2344,6 +2405,8 @@ async fn team_layout_from_teams_orders_and_hides_the_sidebar() {
2344 channel_id: "zeta-old".into(),
2405 channel_id: "zeta-old".into(),
2345 general: false,
2406 general: false,
2346 hidden: true,
2407 hidden: true,
2408 tabs: Vec::new(),
2409 notifications: Default::default(),
2347 }],
2410 }],
2348 },
2411 },
2349 TeamLayoutRecord {
2412 TeamLayoutRecord {
@@ -2390,6 +2453,48 @@ async fn team_layout_from_teams_orders_and_hides_the_sidebar() {
2390 assert!(received.contains(&CoreEvent::SidebarChanged));
2453 assert!(received.contains(&CoreEvent::SidebarChanged));
2391}
2454}
2392
2455
2456#[tokio::test]
2457async fn channel_notifications_go_to_the_service_then_the_store() {
2458 let fake = Arc::new(Fake::default());
2459 let engine = engine_with(&fake, SyncConfig::default());
2460 engine
2461 .store()
2462 .upsert_teams(&[TeamRecord {
2463 id: "alpha".into(),
2464 name: "alpha".into(),
2465 }])
2466 .unwrap();
2467 engine
2468 .store()
2469 .upsert_channels(&[ChannelRecord {
2470 id: "alpha-news".into(),
2471 team_id: "alpha".into(),
2472 name: "News".into(),
2473 membership_type: None,
2474 last_message_at: None,
2475 unread: false,
2476 }])
2477 .unwrap();
2478 let mut events = engine.subscribe();
2479 let banner = store::ChannelNotifications {
2480 level: store::ChannelNotificationLevel::BannerAndFeed,
2481 include_replies: true,
2482 };
2483
2484 engine
2485 .set_channel_notifications("alpha-news", banner)
2486 .await
2487 .unwrap();
2488
2489 assert_eq!(
2490 fake.calls().last().unwrap(),
2491 "channel notifications alpha-news banner true"
2492 );
2493 let teams = engine.store().sidebar().unwrap().teams;
2494 assert_eq!(teams[0].channel_notifications("alpha-news"), banner);
2495 assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged);
2496}
2497
2393#[tokio::test]
2498#[tokio::test]
2394async fn folders_without_a_source_are_unsupported() {
2499async fn folders_without_a_source_are_unsupported() {
2395 let fake = Arc::new(Fake::default());
2500 let fake = Arc::new(Fake::default());
crates/graph/src/client.rs +6 −2
@@ -234,7 +234,7 @@ impl Graph {
234 234 Ok(Some(self.get_page(link, page.scope.clone()).await?))
235 235 }
236 236
237 async fn get(&self, url: &str, scope: &Scope) -> Result<Value> {
237 pub(crate) async fn get(&self, url: &str, scope: &Scope) -> Result<Value> {
238 238 ensure_graph_url(url)?;
239 239 Ok(self
240 240 .session
@@ -266,7 +266,11 @@ impl Graph {
266 266 Ok(items)
267 267 }
268 268
269 async fn get_all<T: DeserializeOwned>(&self, url: &str, scope: Scope) -> Result<Vec<T>> {
269 pub(crate) async fn get_all<T: DeserializeOwned>(
270 &self,
271 url: &str,
272 scope: Scope,
273 ) -> Result<Vec<T>> {
270 274 let mut page: Page<T> = self.get_page(url, scope).await?;
271 275 let mut items = std::mem::take(&mut page.items);
272 276 while let Some(mut next) = self.next_page(&page).await? {
@@ -234,7 +234,7 @@ impl Graph {
234 Ok(Some(self.get_page(link, page.scope.clone()).await?))
234 Ok(Some(self.get_page(link, page.scope.clone()).await?))
235 }
235 }
236
236
237 async fn get(&self, url: &str, scope: &Scope) -> Result<Value> {
237 pub(crate) async fn get(&self, url: &str, scope: &Scope) -> Result<Value> {
238 ensure_graph_url(url)?;
238 ensure_graph_url(url)?;
239 Ok(self
239 Ok(self
240 .session
240 .session
@@ -266,7 +266,11 @@ impl Graph {
266 Ok(items)
266 Ok(items)
267 }
267 }
268
268
269 async fn get_all<T: DeserializeOwned>(&self, url: &str, scope: Scope) -> Result<Vec<T>> {
269 pub(crate) async fn get_all<T: DeserializeOwned>(
270 &self,
271 url: &str,
272 scope: Scope,
273 ) -> Result<Vec<T>> {
270 let mut page: Page<T> = self.get_page(url, scope).await?;
274 let mut page: Page<T> = self.get_page(url, scope).await?;
271 let mut items = std::mem::take(&mut page.items);
275 let mut items = std::mem::take(&mut page.items);
272 while let Some(mut next) = self.next_page(&page).await? {
276 while let Some(mut next) = self.next_page(&page).await? {
crates/graph/src/files.rs +47 −14
@@ -10,7 +10,7 @@ use crate::outgoing::FileReference;
10 10 use crate::people::decode_binary;
11 11 use crate::urls;
12 12
13 const FILES_SCOPE: &str = "Files.ReadWrite";
13 pub(crate) const FILES_SCOPE: &str = "Files.ReadWrite";
14 14 const CHUNK_UNIT_BYTES: u64 = 327_680;
15 15 pub const UPLOAD_CHUNK_BYTES: u64 = 4 * CHUNK_UNIT_BYTES;
16 16 pub const DOWNLOAD_CHUNK_BYTES: u64 = 4 * 1024 * 1024;
@@ -92,6 +92,22 @@ impl DriveItem {
92 92 }
93 93 }
94 94
95 fn shared_file(body: serde_json::Value) -> Result<SharedFile> {
96 let item: SharedItem = serde_json::from_value(body)?;
97 let download_url = item
98 .download_url
99 .filter(|url| !url.is_empty())
100 .ok_or_else(|| Error::Download("the file has no download link".into()))?;
101 let size = item
102 .size
103 .ok_or_else(|| Error::Download("size unknown".into()))?;
104 Ok(SharedFile {
105 name: item.name,
106 size,
107 download_url,
108 })
109 }
110
95 111 /// `"{GUID},3"` becomes `GUID`.
96 112 pub fn etag_guid(etag: &str) -> Option<String> {
97 113 let start = etag.find('{')? + 1;
@@ -351,19 +367,20 @@ impl Graph {
351 367 None,
352 368 )
353 369 .await?;
354 let item: SharedItem = serde_json::from_value(answer.body)?;
355 let download_url = item
356 .download_url
357 .filter(|url| !url.is_empty())
358 .ok_or_else(|| Error::Download("the file has no download link".into()))?;
359 let size = item
360 .size
361 .ok_or_else(|| Error::Download("size unknown".into()))?;
362 Ok(SharedFile {
363 name: item.name,
364 size,
365 download_url,
366 })
370 shared_file(answer.body)
371 }
372
373 pub async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {
374 let answer = self
375 .session()
376 .request(
377 Method::Get,
378 &urls::drive_item(drive_id, item_id),
379 &Scope::graph(FILES_SCOPE),
380 None,
381 )
382 .await?;
383 shared_file(answer.body)
367 384 }
368 385
369 386 pub async fn download_range(
@@ -498,6 +515,22 @@ mod tests {
498 515 assert_eq!(range_header(8_388_608, None), "bytes=8388608-");
499 516 }
500 517
518 #[test]
519 fn share_and_item_lookups_keep_the_download_url_by_not_selecting_fields() {
520 assert!(!urls::shared_drive_item("u!abc").contains("$select"));
521 assert!(!urls::drive_item("b!d", "01ABC").contains("$select"));
522 }
523
524 #[test]
525 fn a_file_without_a_download_link_is_an_error() {
526 assert!(shared_file(json!({"name": "a", "size": 1})).is_err());
527 let shared = shared_file(json!({
528 "name": "a", "size": 1, "@microsoft.graph.downloadUrl": "https://dl.example/a"
529 }))
530 .unwrap();
531 assert_eq!(shared.download_url, "https://dl.example/a");
532 }
533
501 534 #[test]
502 535 fn shared_item_reads_the_download_url() {
503 536 let item: SharedItem = serde_json::from_value(json!({
@@ -10,7 +10,7 @@ use crate::outgoing::FileReference;
10use crate::people::decode_binary;
10use crate::people::decode_binary;
11use crate::urls;
11use crate::urls;
12
12
13const FILES_SCOPE: &str = "Files.ReadWrite";
13pub(crate) const FILES_SCOPE: &str = "Files.ReadWrite";
14const CHUNK_UNIT_BYTES: u64 = 327_680;
14const CHUNK_UNIT_BYTES: u64 = 327_680;
15pub const UPLOAD_CHUNK_BYTES: u64 = 4 * CHUNK_UNIT_BYTES;
15pub const UPLOAD_CHUNK_BYTES: u64 = 4 * CHUNK_UNIT_BYTES;
16pub const DOWNLOAD_CHUNK_BYTES: u64 = 4 * 1024 * 1024;
16pub const DOWNLOAD_CHUNK_BYTES: u64 = 4 * 1024 * 1024;
@@ -92,6 +92,22 @@ impl DriveItem {
92 }
92 }
93}
93}
94
94
95fn shared_file(body: serde_json::Value) -> Result<SharedFile> {
96 let item: SharedItem = serde_json::from_value(body)?;
97 let download_url = item
98 .download_url
99 .filter(|url| !url.is_empty())
100 .ok_or_else(|| Error::Download("the file has no download link".into()))?;
101 let size = item
102 .size
103 .ok_or_else(|| Error::Download("size unknown".into()))?;
104 Ok(SharedFile {
105 name: item.name,
106 size,
107 download_url,
108 })
109}
110
95/// `"{GUID},3"` becomes `GUID`.
111/// `"{GUID},3"` becomes `GUID`.
96pub fn etag_guid(etag: &str) -> Option<String> {
112pub fn etag_guid(etag: &str) -> Option<String> {
97 let start = etag.find('{')? + 1;
113 let start = etag.find('{')? + 1;
@@ -351,19 +367,20 @@ impl Graph {
351 None,
367 None,
352 )
368 )
353 .await?;
369 .await?;
354 let item: SharedItem = serde_json::from_value(answer.body)?;
370 shared_file(answer.body)
355 let download_url = item
371 }
356 .download_url
372
357 .filter(|url| !url.is_empty())
373 pub async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> {
358 .ok_or_else(|| Error::Download("the file has no download link".into()))?;
374 let answer = self
359 let size = item
375 .session()
360 .size
376 .request(
361 .ok_or_else(|| Error::Download("size unknown".into()))?;
377 Method::Get,
362 Ok(SharedFile {
378 &urls::drive_item(drive_id, item_id),
363 name: item.name,
379 &Scope::graph(FILES_SCOPE),
364 size,
380 None,
365 download_url,
381 )
366 })
382 .await?;
383 shared_file(answer.body)
367 }
384 }
368
385
369 pub async fn download_range(
386 pub async fn download_range(
@@ -498,6 +515,22 @@ mod tests {
498 assert_eq!(range_header(8_388_608, None), "bytes=8388608-");
515 assert_eq!(range_header(8_388_608, None), "bytes=8388608-");
499 }
516 }
500
517
518 #[test]
519 fn share_and_item_lookups_keep_the_download_url_by_not_selecting_fields() {
520 assert!(!urls::shared_drive_item("u!abc").contains("$select"));
521 assert!(!urls::drive_item("b!d", "01ABC").contains("$select"));
522 }
523
524 #[test]
525 fn a_file_without_a_download_link_is_an_error() {
526 assert!(shared_file(json!({"name": "a", "size": 1})).is_err());
527 let shared = shared_file(json!({
528 "name": "a", "size": 1, "@microsoft.graph.downloadUrl": "https://dl.example/a"
529 }))
530 .unwrap();
531 assert_eq!(shared.download_url, "https://dl.example/a");
532 }
533
501 #[test]
534 #[test]
502 fn shared_item_reads_the_download_url() {
535 fn shared_item_reads_the_download_url() {
503 let item: SharedItem = serde_json::from_value(json!({
536 let item: SharedItem = serde_json::from_value(json!({
crates/graph/src/lib.rs +3 −0
@@ -2,11 +2,13 @@ mod client;
2 2 mod content;
3 3 mod error;
4 4 mod files;
5 mod library;
5 6 mod models;
6 7 mod outgoing;
7 8 mod page;
8 9 mod people;
9 10 mod profile;
11 mod tabs;
10 12 mod target;
11 13 mod urls;
12 14 mod writes;
@@ -18,6 +20,7 @@ pub use files::{
18 20 UploadedFile, chunk_range_at, chunk_ranges, download_ranges, etag_guid, next_expected_start,
19 21 percent_done, share_id,
20 22 };
23 pub use library::DriveEntry;
21 24 pub use models::{
22 25 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
23 26 Presence, Reaction, Sender, Team, User,
@@ -2,11 +2,13 @@ mod client;
2mod content;
2mod content;
3mod error;
3mod error;
4mod files;
4mod files;
5mod library;
5mod models;
6mod models;
6mod outgoing;
7mod outgoing;
7mod page;
8mod page;
8mod people;
9mod people;
9mod profile;
10mod profile;
11mod tabs;
10mod target;
12mod target;
11mod urls;
13mod urls;
12mod writes;
14mod writes;
@@ -18,6 +20,7 @@ pub use files::{
18 UploadedFile, chunk_range_at, chunk_ranges, download_ranges, etag_guid, next_expected_start,
20 UploadedFile, chunk_range_at, chunk_ranges, download_ranges, etag_guid, next_expected_start,
19 percent_done, share_id,
21 percent_done, share_id,
20};
22};
23pub use library::DriveEntry;
21pub use models::{
24pub use models::{
22 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
25 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
23 Presence, Reaction, Sender, Team, User,
26 Presence, Reaction, Sender, Team, User,
crates/graph/src/library.rs added +214 −0
@@ -0,0 +1,214 @@
1 use chrono::{DateTime, Utc};
2 use serde::Deserialize;
3 use serde_json::json;
4 use session::{Method, Scope};
5
6 use crate::client::Graph;
7 use crate::error::{Error, Result};
8 use crate::files::{DriveFolder, FILES_SCOPE};
9 use crate::urls;
10
11 #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
12 #[serde(from = "RawEntry")]
13 pub struct DriveEntry {
14 pub drive_id: String,
15 pub id: String,
16 pub name: String,
17 pub web_url: String,
18 pub size: u64,
19 pub modified_at: Option<DateTime<Utc>>,
20 pub modified_by: Option<String>,
21 pub child_count: Option<u64>,
22 pub download_url: Option<String>,
23 }
24
25 impl DriveEntry {
26 pub fn is_folder(&self) -> bool {
27 self.child_count.is_some()
28 }
29
30 pub fn folder(&self) -> DriveFolder {
31 DriveFolder {
32 drive_id: self.drive_id.clone(),
33 item_id: self.id.clone(),
34 }
35 }
36 }
37
38 #[derive(Deserialize)]
39 #[serde(rename_all = "camelCase")]
40 struct RawEntry {
41 id: String,
42 name: String,
43 #[serde(default)]
44 web_url: String,
45 #[serde(default)]
46 size: u64,
47 last_modified_date_time: Option<DateTime<Utc>>,
48 last_modified_by: Option<RawActor>,
49 folder: Option<RawFolder>,
50 #[serde(default, rename = "@microsoft.graph.downloadUrl")]
51 download_url: Option<String>,
52 parent_reference: Option<RawParent>,
53 }
54
55 #[derive(Deserialize)]
56 struct RawActor {
57 user: Option<RawIdentity>,
58 application: Option<RawIdentity>,
59 }
60
61 #[derive(Deserialize)]
62 #[serde(rename_all = "camelCase")]
63 struct RawIdentity {
64 display_name: Option<String>,
65 }
66
67 #[derive(Deserialize)]
68 #[serde(rename_all = "camelCase")]
69 struct RawFolder {
70 #[serde(default)]
71 child_count: u64,
72 }
73
74 #[derive(Deserialize)]
75 #[serde(rename_all = "camelCase")]
76 struct RawParent {
77 drive_id: Option<String>,
78 }
79
80 impl From<RawEntry> for DriveEntry {
81 fn from(raw: RawEntry) -> Self {
82 let modified_by = raw.last_modified_by.and_then(|actor| {
83 actor
84 .user
85 .or(actor.application)
86 .and_then(|identity| identity.display_name)
87 });
88 DriveEntry {
89 drive_id: raw
90 .parent_reference
91 .and_then(|parent| parent.drive_id)
92 .unwrap_or_default(),
93 id: raw.id,
94 name: raw.name,
95 web_url: raw.web_url,
96 size: raw.size,
97 modified_at: raw.last_modified_date_time,
98 modified_by,
99 child_count: raw.folder.map(|folder| folder.child_count),
100 download_url: raw.download_url.filter(|url| !url.is_empty()),
101 }
102 }
103 }
104
105 impl Graph {
106 pub async fn channel_files_root(&self, team_id: &str, channel_id: &str) -> Result<DriveEntry> {
107 let body = self
108 .get(
109 &urls::channel_files_folder(team_id, channel_id),
110 &Scope::graph(FILES_SCOPE),
111 )
112 .await?;
113 let entry: DriveEntry = serde_json::from_value(body)?;
114 if entry.drive_id.is_empty() {
115 return Err(Error::Upload("the channel folder has no drive".into()));
116 }
117 Ok(entry)
118 }
119
120 pub async fn list_children(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {
121 self.get_all(
122 &urls::folder_children(&folder.drive_id, &folder.item_id),
123 Scope::graph(FILES_SCOPE),
124 )
125 .await
126 }
127
128 pub async fn create_folder(&self, parent: &DriveFolder, name: &str) -> Result<DriveEntry> {
129 let answer = self
130 .session()
131 .request(
132 Method::Post,
133 &urls::folder_create(&parent.drive_id, &parent.item_id),
134 &Scope::graph(FILES_SCOPE),
135 Some(json!({
136 "name": name,
137 "folder": {},
138 "@microsoft.graph.conflictBehavior": "rename",
139 })),
140 )
141 .await?;
142 let mut entry: DriveEntry = serde_json::from_value(answer.body)?;
143 if entry.drive_id.is_empty() {
144 entry.drive_id.clone_from(&parent.drive_id);
145 }
146 Ok(entry)
147 }
148 }
149
150 #[cfg(test)]
151 mod tests {
152 use serde_json::json;
153 use session::Scope;
154
155 use super::*;
156 use crate::page::Page;
157
158 fn page(body: serde_json::Value) -> Page<DriveEntry> {
159 Page::parse(body, Scope::graph(FILES_SCOPE)).unwrap()
160 }
161
162 #[test]
163 fn children_parse_files_and_folders() {
164 let parsed = page(json!({"value": [
165 {
166 "id": "f1", "name": "Plans", "webUrl": "https://x/Plans", "size": 0,
167 "folder": {"childCount": 3},
168 "lastModifiedDateTime": "2026-10-01T08:30:00Z",
169 "lastModifiedBy": {"user": {"displayName": "Mara Lindqvist"}},
170 "parentReference": {"driveId": "b!d"}
171 },
172 {
173 "id": "i1", "name": "Plan.pdf", "webUrl": "https://x/Plan.pdf", "size": 2048,
174 "file": {"mimeType": "application/pdf"},
175 "@microsoft.graph.downloadUrl": "https://dl.example/plan",
176 "lastModifiedBy": {"application": {"displayName": "Flow"}},
177 "parentReference": {"driveId": "b!d"}
178 }
179 ]}));
180 let [folder, file] = parsed.items.as_slice() else {
181 panic!("two entries");
182 };
183 assert!(folder.is_folder());
184 assert_eq!(folder.child_count, Some(3));
185 assert_eq!(folder.modified_by.as_deref(), Some("Mara Lindqvist"));
186 assert_eq!(folder.folder().drive_id, "b!d");
187 assert!(!file.is_folder());
188 assert_eq!(file.size, 2048);
189 assert_eq!(file.modified_by.as_deref(), Some("Flow"));
190 assert_eq!(
191 file.download_url.as_deref(),
192 Some("https://dl.example/plan")
193 );
194 assert_eq!(file.modified_at, None);
195 }
196
197 #[test]
198 fn a_next_link_continues_the_listing() {
199 let first = page(json!({
200 "value": [{"id": "1", "name": "a"}],
201 "@odata.nextLink": "https://graph.microsoft.com/v1.0/drives/d/items/i/children?$skiptoken=x"
202 }));
203 let last = page(json!({"value": [{"id": "2", "name": "b"}]}));
204 assert!(first.next_link.is_some());
205 assert!(last.next_link.is_none());
206 }
207
208 #[test]
209 fn listing_keeps_the_download_url_by_not_selecting_fields() {
210 let url = urls::folder_children("b!d", "01ABC");
211 assert!(url.ends_with("/children?$top=200"));
212 assert!(!url.contains("$select"));
213 }
214 }
@@ -0,0 +1,214 @@
1use chrono::{DateTime, Utc};
2use serde::Deserialize;
3use serde_json::json;
4use session::{Method, Scope};
5
6use crate::client::Graph;
7use crate::error::{Error, Result};
8use crate::files::{DriveFolder, FILES_SCOPE};
9use crate::urls;
10
11#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
12#[serde(from = "RawEntry")]
13pub struct DriveEntry {
14 pub drive_id: String,
15 pub id: String,
16 pub name: String,
17 pub web_url: String,
18 pub size: u64,
19 pub modified_at: Option<DateTime<Utc>>,
20 pub modified_by: Option<String>,
21 pub child_count: Option<u64>,
22 pub download_url: Option<String>,
23}
24
25impl DriveEntry {
26 pub fn is_folder(&self) -> bool {
27 self.child_count.is_some()
28 }
29
30 pub fn folder(&self) -> DriveFolder {
31 DriveFolder {
32 drive_id: self.drive_id.clone(),
33 item_id: self.id.clone(),
34 }
35 }
36}
37
38#[derive(Deserialize)]
39#[serde(rename_all = "camelCase")]
40struct RawEntry {
41 id: String,
42 name: String,
43 #[serde(default)]
44 web_url: String,
45 #[serde(default)]
46 size: u64,
47 last_modified_date_time: Option<DateTime<Utc>>,
48 last_modified_by: Option<RawActor>,
49 folder: Option<RawFolder>,
50 #[serde(default, rename = "@microsoft.graph.downloadUrl")]
51 download_url: Option<String>,
52 parent_reference: Option<RawParent>,
53}
54
55#[derive(Deserialize)]
56struct RawActor {
57 user: Option<RawIdentity>,
58 application: Option<RawIdentity>,
59}
60
61#[derive(Deserialize)]
62#[serde(rename_all = "camelCase")]
63struct RawIdentity {
64 display_name: Option<String>,
65}
66
67#[derive(Deserialize)]
68#[serde(rename_all = "camelCase")]
69struct RawFolder {
70 #[serde(default)]
71 child_count: u64,
72}
73
74#[derive(Deserialize)]
75#[serde(rename_all = "camelCase")]
76struct RawParent {
77 drive_id: Option<String>,
78}
79
80impl From<RawEntry> for DriveEntry {
81 fn from(raw: RawEntry) -> Self {
82 let modified_by = raw.last_modified_by.and_then(|actor| {
83 actor
84 .user
85 .or(actor.application)
86 .and_then(|identity| identity.display_name)
87 });
88 DriveEntry {
89 drive_id: raw
90 .parent_reference
91 .and_then(|parent| parent.drive_id)
92 .unwrap_or_default(),
93 id: raw.id,
94 name: raw.name,
95 web_url: raw.web_url,
96 size: raw.size,
97 modified_at: raw.last_modified_date_time,
98 modified_by,
99 child_count: raw.folder.map(|folder| folder.child_count),
100 download_url: raw.download_url.filter(|url| !url.is_empty()),
101 }
102 }
103}
104
105impl Graph {
106 pub async fn channel_files_root(&self, team_id: &str, channel_id: &str) -> Result<DriveEntry> {
107 let body = self
108 .get(
109 &urls::channel_files_folder(team_id, channel_id),
110 &Scope::graph(FILES_SCOPE),
111 )
112 .await?;
113 let entry: DriveEntry = serde_json::from_value(body)?;
114 if entry.drive_id.is_empty() {
115 return Err(Error::Upload("the channel folder has no drive".into()));
116 }
117 Ok(entry)
118 }
119
120 pub async fn list_children(&self, folder: &DriveFolder) -> Result<Vec<DriveEntry>> {
121 self.get_all(
122 &urls::folder_children(&folder.drive_id, &folder.item_id),
123 Scope::graph(FILES_SCOPE),
124 )
125 .await
126 }
127
128 pub async fn create_folder(&self, parent: &DriveFolder, name: &str) -> Result<DriveEntry> {
129 let answer = self
130 .session()
131 .request(
132 Method::Post,
133 &urls::folder_create(&parent.drive_id, &parent.item_id),
134 &Scope::graph(FILES_SCOPE),
135 Some(json!({
136 "name": name,
137 "folder": {},
138 "@microsoft.graph.conflictBehavior": "rename",
139 })),
140 )
141 .await?;
142 let mut entry: DriveEntry = serde_json::from_value(answer.body)?;
143 if entry.drive_id.is_empty() {
144 entry.drive_id.clone_from(&parent.drive_id);
145 }
146 Ok(entry)
147 }
148}
149
150#[cfg(test)]
151mod tests {
152 use serde_json::json;
153 use session::Scope;
154
155 use super::*;
156 use crate::page::Page;
157
158 fn page(body: serde_json::Value) -> Page<DriveEntry> {
159 Page::parse(body, Scope::graph(FILES_SCOPE)).unwrap()
160 }
161
162 #[test]
163 fn children_parse_files_and_folders() {
164 let parsed = page(json!({"value": [
165 {
166 "id": "f1", "name": "Plans", "webUrl": "https://x/Plans", "size": 0,
167 "folder": {"childCount": 3},
168 "lastModifiedDateTime": "2026-10-01T08:30:00Z",
169 "lastModifiedBy": {"user": {"displayName": "Mara Lindqvist"}},
170 "parentReference": {"driveId": "b!d"}
171 },
172 {
173 "id": "i1", "name": "Plan.pdf", "webUrl": "https://x/Plan.pdf", "size": 2048,
174 "file": {"mimeType": "application/pdf"},
175 "@microsoft.graph.downloadUrl": "https://dl.example/plan",
176 "lastModifiedBy": {"application": {"displayName": "Flow"}},
177 "parentReference": {"driveId": "b!d"}
178 }
179 ]}));
180 let [folder, file] = parsed.items.as_slice() else {
181 panic!("two entries");
182 };
183 assert!(folder.is_folder());
184 assert_eq!(folder.child_count, Some(3));
185 assert_eq!(folder.modified_by.as_deref(), Some("Mara Lindqvist"));
186 assert_eq!(folder.folder().drive_id, "b!d");
187 assert!(!file.is_folder());
188 assert_eq!(file.size, 2048);
189 assert_eq!(file.modified_by.as_deref(), Some("Flow"));
190 assert_eq!(
191 file.download_url.as_deref(),
192 Some("https://dl.example/plan")
193 );
194 assert_eq!(file.modified_at, None);
195 }
196
197 #[test]
198 fn a_next_link_continues_the_listing() {
199 let first = page(json!({
200 "value": [{"id": "1", "name": "a"}],
201 "@odata.nextLink": "https://graph.microsoft.com/v1.0/drives/d/items/i/children?$skiptoken=x"
202 }));
203 let last = page(json!({"value": [{"id": "2", "name": "b"}]}));
204 assert!(first.next_link.is_some());
205 assert!(last.next_link.is_none());
206 }
207
208 #[test]
209 fn listing_keeps_the_download_url_by_not_selecting_fields() {
210 let url = urls::folder_children("b!d", "01ABC");
211 assert!(url.ends_with("/children?$top=200"));
212 assert!(!url.contains("$select"));
213 }
214}
crates/graph/src/tabs.rs added +62 −0
@@ -0,0 +1,62 @@
1 use serde_json::Value;
2 use session::Scope;
3
4 use crate::client::Graph;
5 use crate::error::Result;
6 use crate::urls;
7
8 const TABS_SCOPE: &str = "TeamsTab.ReadWrite.All";
9
10 fn web_url(tab: &Value) -> Option<String> {
11 tab.get("webUrl")
12 .and_then(Value::as_str)
13 .filter(|url| url.starts_with("https://"))
14 .map(str::to_owned)
15 }
16
17 impl Graph {
18 pub async fn channel_tab_web_url(
19 &self,
20 team_id: &str,
21 channel_id: &str,
22 tab_id: &str,
23 ) -> Result<Option<String>> {
24 let tab = self
25 .get(
26 &urls::channel_tab(team_id, channel_id, tab_id),
27 &Scope::graph(TABS_SCOPE),
28 )
29 .await?;
30 Ok(web_url(&tab))
31 }
32 }
33
34 #[cfg(test)]
35 mod tests {
36 use serde_json::json;
37
38 use super::*;
39
40 #[test]
41 fn the_tab_deep_link_is_its_web_url() {
42 let tab = json!({"id": "t1", "displayName": "Plan", "webUrl": "https://teams.microsoft.com/l/channel/19%3Ac/tab%3A%3At1?groupId=g&tenantId=t"});
43 assert_eq!(
44 web_url(&tab).as_deref(),
45 Some("https://teams.microsoft.com/l/channel/19%3Ac/tab%3A%3At1?groupId=g&tenantId=t")
46 );
47 }
48
49 #[test]
50 fn a_tab_without_a_usable_web_url_has_none() {
51 assert_eq!(web_url(&json!({"id": "t1"})), None);
52 assert_eq!(web_url(&json!({"webUrl": "javascript:alert(1)"})), None);
53 }
54
55 #[test]
56 fn the_tab_url_names_team_channel_and_tab() {
57 assert_eq!(
58 urls::channel_tab("team", "19:c@thread.tacv2", "tab-1"),
59 "https://graph.microsoft.com/v1.0/teams/team/channels/19%3Ac%40thread.tacv2/tabs/tab-1"
60 );
61 }
62 }
@@ -0,0 +1,62 @@
1use serde_json::Value;
2use session::Scope;
3
4use crate::client::Graph;
5use crate::error::Result;
6use crate::urls;
7
8const TABS_SCOPE: &str = "TeamsTab.ReadWrite.All";
9
10fn web_url(tab: &Value) -> Option<String> {
11 tab.get("webUrl")
12 .and_then(Value::as_str)
13 .filter(|url| url.starts_with("https://"))
14 .map(str::to_owned)
15}
16
17impl Graph {
18 pub async fn channel_tab_web_url(
19 &self,
20 team_id: &str,
21 channel_id: &str,
22 tab_id: &str,
23 ) -> Result<Option<String>> {
24 let tab = self
25 .get(
26 &urls::channel_tab(team_id, channel_id, tab_id),
27 &Scope::graph(TABS_SCOPE),
28 )
29 .await?;
30 Ok(web_url(&tab))
31 }
32}
33
34#[cfg(test)]
35mod tests {
36 use serde_json::json;
37
38 use super::*;
39
40 #[test]
41 fn the_tab_deep_link_is_its_web_url() {
42 let tab = json!({"id": "t1", "displayName": "Plan", "webUrl": "https://teams.microsoft.com/l/channel/19%3Ac/tab%3A%3At1?groupId=g&tenantId=t"});
43 assert_eq!(
44 web_url(&tab).as_deref(),
45 Some("https://teams.microsoft.com/l/channel/19%3Ac/tab%3A%3At1?groupId=g&tenantId=t")
46 );
47 }
48
49 #[test]
50 fn a_tab_without_a_usable_web_url_has_none() {
51 assert_eq!(web_url(&json!({"id": "t1"})), None);
52 assert_eq!(web_url(&json!({"webUrl": "javascript:alert(1)"})), None);
53 }
54
55 #[test]
56 fn the_tab_url_names_team_channel_and_tab() {
57 assert_eq!(
58 urls::channel_tab("team", "19:c@thread.tacv2", "tab-1"),
59 "https://graph.microsoft.com/v1.0/teams/team/channels/19%3Ac%40thread.tacv2/tabs/tab-1"
60 );
61 }
62}
crates/graph/src/urls.rs +28 −1
@@ -158,6 +158,33 @@ pub fn channel_files_folder(team_id: &str, channel_id: &str) -> String {
158 158 )
159 159 }
160 160
161 pub fn channel_tab(team_id: &str, channel_id: &str, tab_id: &str) -> String {
162 format!(
163 "{GRAPH}/v1.0/teams/{}/channels/{}/tabs/{}",
164 segment(team_id),
165 segment(channel_id),
166 segment(tab_id)
167 )
168 }
169
170 pub const CHILDREN_PAGE_SIZE: usize = 200;
171
172 pub fn folder_children(drive_id: &str, folder_id: &str) -> String {
173 format!(
174 "{GRAPH}/v1.0/drives/{}/items/{}/children?$top={CHILDREN_PAGE_SIZE}",
175 segment(drive_id),
176 segment(folder_id)
177 )
178 }
179
180 pub fn folder_create(drive_id: &str, folder_id: &str) -> String {
181 format!(
182 "{GRAPH}/v1.0/drives/{}/items/{}/children",
183 segment(drive_id),
184 segment(folder_id)
185 )
186 }
187
161 188 pub fn drive_item(drive_id: &str, item_id: &str) -> String {
162 189 format!(
163 190 "{GRAPH}/v1.0/drives/{}/items/{}",
@@ -168,7 +195,7 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {
168 195
169 196 pub fn shared_drive_item(share_id: &str) -> String {
170 197 format!(
171 "{GRAPH}/v1.0/shares/{}/driveItem?$select=id,name,size,@microsoft.graph.downloadUrl",
198 "{GRAPH}/v1.0/shares/{}/driveItem",
172 199 segment(share_id)
173 200 )
174 201 }
@@ -158,6 +158,33 @@ pub fn channel_files_folder(team_id: &str, channel_id: &str) -> String {
158 )
158 )
159}
159}
160
160
161pub fn channel_tab(team_id: &str, channel_id: &str, tab_id: &str) -> String {
162 format!(
163 "{GRAPH}/v1.0/teams/{}/channels/{}/tabs/{}",
164 segment(team_id),
165 segment(channel_id),
166 segment(tab_id)
167 )
168}
169
170pub const CHILDREN_PAGE_SIZE: usize = 200;
171
172pub fn folder_children(drive_id: &str, folder_id: &str) -> String {
173 format!(
174 "{GRAPH}/v1.0/drives/{}/items/{}/children?$top={CHILDREN_PAGE_SIZE}",
175 segment(drive_id),
176 segment(folder_id)
177 )
178}
179
180pub fn folder_create(drive_id: &str, folder_id: &str) -> String {
181 format!(
182 "{GRAPH}/v1.0/drives/{}/items/{}/children",
183 segment(drive_id),
184 segment(folder_id)
185 )
186}
187
161pub fn drive_item(drive_id: &str, item_id: &str) -> String {
188pub fn drive_item(drive_id: &str, item_id: &str) -> String {
162 format!(
189 format!(
163 "{GRAPH}/v1.0/drives/{}/items/{}",
190 "{GRAPH}/v1.0/drives/{}/items/{}",
@@ -168,7 +195,7 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {
168
195
169pub fn shared_drive_item(share_id: &str) -> String {
196pub fn shared_drive_item(share_id: &str) -> String {
170 format!(
197 format!(
171 "{GRAPH}/v1.0/shares/{}/driveItem?$select=id,name,size,@microsoft.graph.downloadUrl",
198 "{GRAPH}/v1.0/shares/{}/driveItem",
172 segment(share_id)
199 segment(share_id)
173 )
200 )
174}
201}
crates/store/src/lib.rs +4 −4
@@ -24,10 +24,10 @@ mod time;
24 24 pub use error::{Error, Result};
25 25 pub use image_files::ImageFileCache;
26 26 pub use models::{
27 ActivityRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelRecord, ChatPreview,
28 ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,
29 MessageRecord, OutboxRecord, OutboxState, OutboxTarget, SearchHit, Sidebar, SidebarTeam,
30 SyncState, TeamLayoutRecord, TeamRecord,
27 ActivityRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel,
28 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, ConversationHit,
29 DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord, OutboxRecord, OutboxState,
30 OutboxTarget, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,
31 31 };
32 32 pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
33 33 pub use store::{DATA_DIR_NAME, Store, default_database_path};
@@ -24,10 +24,10 @@ mod time;
24pub use error::{Error, Result};
24pub use error::{Error, Result};
25pub use image_files::ImageFileCache;
25pub use image_files::ImageFileCache;
26pub use models::{
26pub use models::{
27 ActivityRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelRecord, ChatPreview,
27 ActivityRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel,
28 ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,
28 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, ConversationHit,
29 MessageRecord, OutboxRecord, OutboxState, OutboxTarget, SearchHit, Sidebar, SidebarTeam,
29 DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord, OutboxRecord, OutboxState,
30 SyncState, TeamLayoutRecord, TeamRecord,
30 OutboxTarget, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,
31};
31};
32pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
32pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
33pub use store::{DATA_DIR_NAME, Store, default_database_path};
33pub use store::{DATA_DIR_NAME, Store, default_database_path};
crates/store/src/migrations.rs +8 −0
@@ -65,6 +65,14 @@ const MIGRATIONS: &[Migration] = &[
65 65 script: include_str!("migrations/0014_folder_expanded.sql"),
66 66 after: None,
67 67 },
68 Migration {
69 script: include_str!("migrations/0015_channel_tabs.sql"),
70 after: None,
71 },
72 Migration {
73 script: include_str!("migrations/0016_channel_notifications.sql"),
74 after: None,
75 },
68 76 ];
69 77
70 78 pub fn latest_version() -> i64 {
@@ -65,6 +65,14 @@ const MIGRATIONS: &[Migration] = &[
65 script: include_str!("migrations/0014_folder_expanded.sql"),
65 script: include_str!("migrations/0014_folder_expanded.sql"),
66 after: None,
66 after: None,
67 },
67 },
68 Migration {
69 script: include_str!("migrations/0015_channel_tabs.sql"),
70 after: None,
71 },
72 Migration {
73 script: include_str!("migrations/0016_channel_notifications.sql"),
74 after: None,
75 },
68];
76];
69
77
70pub fn latest_version() -> i64 {
78pub fn latest_version() -> i64 {
crates/store/src/migrations/0015_channel_tabs.sql added +9 −0
@@ -0,0 +1,9 @@
1 CREATE TABLE channel_tabs (
2 channel_id TEXT NOT NULL,
3 position INTEGER NOT NULL,
4 tab_id TEXT NOT NULL,
5 name TEXT NOT NULL,
6 definition_id TEXT NOT NULL,
7 open_url TEXT,
8 PRIMARY KEY (channel_id, position)
9 ) WITHOUT ROWID;
@@ -0,0 +1,9 @@
1CREATE TABLE channel_tabs (
2 channel_id TEXT NOT NULL,
3 position INTEGER NOT NULL,
4 tab_id TEXT NOT NULL,
5 name TEXT NOT NULL,
6 definition_id TEXT NOT NULL,
7 open_url TEXT,
8 PRIMARY KEY (channel_id, position)
9) WITHOUT ROWID;
crates/store/src/migrations/0016_channel_notifications.sql added +2 −0
@@ -0,0 +1,2 @@
1 ALTER TABLE channel_layout ADD COLUMN notification_level TEXT NOT NULL DEFAULT 'feed';
2 ALTER TABLE channel_layout ADD COLUMN include_replies INTEGER NOT NULL DEFAULT 0;
@@ -0,0 +1,2 @@
1ALTER TABLE channel_layout ADD COLUMN notification_level TEXT NOT NULL DEFAULT 'feed';
2ALTER TABLE channel_layout ADD COLUMN include_replies INTEGER NOT NULL DEFAULT 0;
crates/store/src/models.rs +62 −0
@@ -1,3 +1,5 @@
1 use std::collections::HashMap;
2
1 3 use chrono::{DateTime, Utc};
2 4
3 5 #[derive(Debug, Clone, PartialEq, Default)]
@@ -103,6 +105,64 @@ pub struct SidebarTeam {
103 105 pub channels: Vec<ChannelRecord>,
104 106 pub hidden: bool,
105 107 pub hidden_channel_ids: Vec<String>,
108 pub notifications: HashMap<String, ChannelNotifications>,
109 }
110
111 impl SidebarTeam {
112 pub fn channel_notifications(&self, channel_id: &str) -> ChannelNotifications {
113 self.notifications
114 .get(channel_id)
115 .copied()
116 .unwrap_or_default()
117 }
118 }
119
120 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
121 pub enum ChannelNotificationLevel {
122 BannerAndFeed,
123 #[default]
124 Feed,
125 Off,
126 }
127
128 impl ChannelNotificationLevel {
129 pub fn key(self) -> &'static str {
130 match self {
131 ChannelNotificationLevel::BannerAndFeed => "banner",
132 ChannelNotificationLevel::Feed => "feed",
133 ChannelNotificationLevel::Off => "off",
134 }
135 }
136
137 pub fn from_key(key: &str) -> Self {
138 match key {
139 "banner" => ChannelNotificationLevel::BannerAndFeed,
140 "off" => ChannelNotificationLevel::Off,
141 _ => ChannelNotificationLevel::Feed,
142 }
143 }
144 }
145
146 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
147 pub struct ChannelNotifications {
148 pub level: ChannelNotificationLevel,
149 pub include_replies: bool,
150 }
151
152 #[derive(Debug, Clone, PartialEq, Eq)]
153 pub struct ChannelTabRecord {
154 pub tab_id: String,
155 pub name: String,
156 pub definition_id: String,
157 pub open_url: Option<String>,
158 }
159
160 const WEBSITE_DEFINITION_ID: &str = "com.microsoft.teamspace.tab.web";
161
162 impl ChannelTabRecord {
163 pub fn is_website(&self) -> bool {
164 self.definition_id == WEBSITE_DEFINITION_ID && self.open_url.is_some()
165 }
106 166 }
107 167
108 168 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -110,6 +170,8 @@ pub struct ChannelLayoutRecord {
110 170 pub channel_id: String,
111 171 pub general: bool,
112 172 pub hidden: bool,
173 pub tabs: Vec<ChannelTabRecord>,
174 pub notifications: ChannelNotifications,
113 175 }
114 176
115 177 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -1,3 +1,5 @@
1use std::collections::HashMap;
2
1use chrono::{DateTime, Utc};
3use chrono::{DateTime, Utc};
2
4
3#[derive(Debug, Clone, PartialEq, Default)]
5#[derive(Debug, Clone, PartialEq, Default)]
@@ -103,6 +105,64 @@ pub struct SidebarTeam {
103 pub channels: Vec<ChannelRecord>,
105 pub channels: Vec<ChannelRecord>,
104 pub hidden: bool,
106 pub hidden: bool,
105 pub hidden_channel_ids: Vec<String>,
107 pub hidden_channel_ids: Vec<String>,
108 pub notifications: HashMap<String, ChannelNotifications>,
109}
110
111impl SidebarTeam {
112 pub fn channel_notifications(&self, channel_id: &str) -> ChannelNotifications {
113 self.notifications
114 .get(channel_id)
115 .copied()
116 .unwrap_or_default()
117 }
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
121pub enum ChannelNotificationLevel {
122 BannerAndFeed,
123 #[default]
124 Feed,
125 Off,
126}
127
128impl ChannelNotificationLevel {
129 pub fn key(self) -> &'static str {
130 match self {
131 ChannelNotificationLevel::BannerAndFeed => "banner",
132 ChannelNotificationLevel::Feed => "feed",
133 ChannelNotificationLevel::Off => "off",
134 }
135 }
136
137 pub fn from_key(key: &str) -> Self {
138 match key {
139 "banner" => ChannelNotificationLevel::BannerAndFeed,
140 "off" => ChannelNotificationLevel::Off,
141 _ => ChannelNotificationLevel::Feed,
142 }
143 }
144}
145
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
147pub struct ChannelNotifications {
148 pub level: ChannelNotificationLevel,
149 pub include_replies: bool,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct ChannelTabRecord {
154 pub tab_id: String,
155 pub name: String,
156 pub definition_id: String,
157 pub open_url: Option<String>,
158}
159
160const WEBSITE_DEFINITION_ID: &str = "com.microsoft.teamspace.tab.web";
161
162impl ChannelTabRecord {
163 pub fn is_website(&self) -> bool {
164 self.definition_id == WEBSITE_DEFINITION_ID && self.open_url.is_some()
165 }
106}
166}
107
167
108#[derive(Debug, Clone, PartialEq, Eq)]
168#[derive(Debug, Clone, PartialEq, Eq)]
@@ -110,6 +170,8 @@ pub struct ChannelLayoutRecord {
110 pub channel_id: String,
170 pub channel_id: String,
111 pub general: bool,
171 pub general: bool,
112 pub hidden: bool,
172 pub hidden: bool,
173 pub tabs: Vec<ChannelTabRecord>,
174 pub notifications: ChannelNotifications,
113}
175}
114
176
115#[derive(Debug, Clone, PartialEq, Eq)]
177#[derive(Debug, Clone, PartialEq, Eq)]
crates/store/src/sidebar.rs +81 −4
@@ -1,9 +1,13 @@
1 1 use std::cmp::Ordering;
2 use std::collections::HashMap;
2 3
3 4 use rusqlite::params;
4 5
5 6 use crate::error::Result;
6 use crate::models::{ChannelRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord};
7 use crate::models::{
8 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, Sidebar,
9 SidebarTeam, TeamLayoutRecord, TeamRecord,
10 };
7 11 use crate::store::Store;
8 12 use crate::teams::channel_from_row;
9 13
@@ -19,6 +23,7 @@ struct ChannelRow {
19 23 channel: ChannelRecord,
20 24 general: bool,
21 25 hidden: bool,
26 notifications: ChannelNotifications,
22 27 }
23 28
24 29 impl Store {
@@ -54,7 +59,9 @@ impl Store {
54 59 let mut channel_rows: Vec<ChannelRow> = connection
55 60 .prepare_cached(
56 61 "SELECT id, team_id, name, membership_type, last_message_at, unread,
57 COALESCE(channel_layout.general, name = ?1), COALESCE(channel_layout.hidden, 0)
62 COALESCE(channel_layout.general, name = ?1), COALESCE(channel_layout.hidden, 0),
63 COALESCE(channel_layout.notification_level, 'feed'),
64 COALESCE(channel_layout.include_replies, 0)
58 65 FROM channels LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id",
59 66 )?
60 67 .query_map(params![GENERAL_FALLBACK_NAME], |row| {
@@ -62,6 +69,10 @@ impl Store {
62 69 channel: channel_from_row(row)?,
63 70 general: row.get(6)?,
64 71 hidden: row.get(7)?,
72 notifications: ChannelNotifications {
73 level: ChannelNotificationLevel::from_key(&row.get::<_, String>(8)?),
74 include_replies: row.get(9)?,
75 },
65 76 })
66 77 })?
67 78 .collect::<rusqlite::Result<_>>()?;
@@ -79,6 +90,7 @@ impl Store {
79 90 channels: Vec::new(),
80 91 hidden: row.hidden,
81 92 hidden_channel_ids: Vec::new(),
93 notifications: HashMap::new(),
82 94 })
83 95 .collect();
84 96 for row in channel_rows {
@@ -89,6 +101,10 @@ impl Store {
89 101 if row.hidden {
90 102 team.hidden_channel_ids.push(row.channel.id.clone());
91 103 }
104 if row.notifications != ChannelNotifications::default() {
105 team.notifications
106 .insert(row.channel.id.clone(), row.notifications);
107 }
92 108 team.channels.push(row.channel);
93 109 }
94 110 }
@@ -100,12 +116,19 @@ impl Store {
100 116 let transaction = connection.transaction()?;
101 117 transaction.execute("DELETE FROM team_layout", [])?;
102 118 transaction.execute("DELETE FROM channel_layout", [])?;
119 transaction.execute("DELETE FROM channel_tabs", [])?;
103 120 {
104 121 let mut team_insert = transaction.prepare_cached(
105 122 "INSERT OR REPLACE INTO team_layout (team_id, position, hidden) VALUES (?1, ?2, ?3)",
106 123 )?;
107 124 let mut channel_insert = transaction.prepare_cached(
108 "INSERT OR REPLACE INTO channel_layout (channel_id, general, hidden) VALUES (?1, ?2, ?3)",
125 "INSERT OR REPLACE INTO channel_layout
126 (channel_id, general, hidden, notification_level, include_replies)
127 VALUES (?1, ?2, ?3, ?4, ?5)",
128 )?;
129 let mut tab_insert = transaction.prepare_cached(
130 "INSERT OR REPLACE INTO channel_tabs (channel_id, position, tab_id, name, definition_id, open_url)
131 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
109 132 )?;
110 133 for (position, team) in layout.iter().enumerate() {
111 134 team_insert.execute(params![team.team_id, position as i64, team.hidden])?;
@@ -113,13 +136,67 @@ impl Store {
113 136 channel_insert.execute(params![
114 137 channel.channel_id,
115 138 channel.general,
116 channel.hidden
139 channel.hidden,
140 channel.notifications.level.key(),
141 channel.notifications.include_replies
117 142 ])?;
143 for (tab_position, tab) in channel.tabs.iter().enumerate() {
144 tab_insert.execute(params![
145 channel.channel_id,
146 tab_position as i64,
147 tab.tab_id,
148 tab.name,
149 tab.definition_id,
150 tab.open_url
151 ])?;
152 }
118 153 }
119 154 }
120 155 }
121 156 Ok(transaction.commit()?)
122 157 }
158
159 pub fn set_channel_notifications(
160 &self,
161 channel_id: &str,
162 notifications: ChannelNotifications,
163 ) -> Result<()> {
164 self.lock()?.execute(
165 "INSERT INTO channel_layout (channel_id, general, notification_level, include_replies)
166 SELECT id, name = ?2, ?3, ?4 FROM channels WHERE id = ?1
167 ON CONFLICT (channel_id) DO UPDATE SET
168 notification_level = excluded.notification_level,
169 include_replies = excluded.include_replies",
170 params![
171 channel_id,
172 GENERAL_FALLBACK_NAME,
173 notifications.level.key(),
174 notifications.include_replies
175 ],
176 )?;
177 Ok(())
178 }
179 }
180
181 impl Store {
182 pub fn channel_tabs(&self, channel_id: &str) -> Result<Vec<ChannelTabRecord>> {
183 let connection = self.lock()?;
184 let tabs = connection
185 .prepare_cached(
186 "SELECT tab_id, name, definition_id, open_url FROM channel_tabs
187 WHERE channel_id = ?1 ORDER BY position",
188 )?
189 .query_map(params![channel_id], |row| {
190 Ok(ChannelTabRecord {
191 tab_id: row.get(0)?,
192 name: row.get(1)?,
193 definition_id: row.get(2)?,
194 open_url: row.get(3)?,
195 })
196 })?
197 .collect::<rusqlite::Result<_>>()?;
198 Ok(tabs)
199 }
123 200 }
124 201
125 202 fn compare_names(left: &str, right: &str) -> Ordering {
@@ -1,9 +1,13 @@
1use std::cmp::Ordering;
1use std::cmp::Ordering;
2use std::collections::HashMap;
2
3
3use rusqlite::params;
4use rusqlite::params;
4
5
5use crate::error::Result;
6use crate::error::Result;
6use crate::models::{ChannelRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord};
7use crate::models::{
8 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, Sidebar,
9 SidebarTeam, TeamLayoutRecord, TeamRecord,
10};
7use crate::store::Store;
11use crate::store::Store;
8use crate::teams::channel_from_row;
12use crate::teams::channel_from_row;
9
13
@@ -19,6 +23,7 @@ struct ChannelRow {
19 channel: ChannelRecord,
23 channel: ChannelRecord,
20 general: bool,
24 general: bool,
21 hidden: bool,
25 hidden: bool,
26 notifications: ChannelNotifications,
22}
27}
23
28
24impl Store {
29impl Store {
@@ -54,7 +59,9 @@ impl Store {
54 let mut channel_rows: Vec<ChannelRow> = connection
59 let mut channel_rows: Vec<ChannelRow> = connection
55 .prepare_cached(
60 .prepare_cached(
56 "SELECT id, team_id, name, membership_type, last_message_at, unread,
61 "SELECT id, team_id, name, membership_type, last_message_at, unread,
57 COALESCE(channel_layout.general, name = ?1), COALESCE(channel_layout.hidden, 0)
62 COALESCE(channel_layout.general, name = ?1), COALESCE(channel_layout.hidden, 0),
63 COALESCE(channel_layout.notification_level, 'feed'),
64 COALESCE(channel_layout.include_replies, 0)
58 FROM channels LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id",
65 FROM channels LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id",
59 )?
66 )?
60 .query_map(params![GENERAL_FALLBACK_NAME], |row| {
67 .query_map(params![GENERAL_FALLBACK_NAME], |row| {
@@ -62,6 +69,10 @@ impl Store {
62 channel: channel_from_row(row)?,
69 channel: channel_from_row(row)?,
63 general: row.get(6)?,
70 general: row.get(6)?,
64 hidden: row.get(7)?,
71 hidden: row.get(7)?,
72 notifications: ChannelNotifications {
73 level: ChannelNotificationLevel::from_key(&row.get::<_, String>(8)?),
74 include_replies: row.get(9)?,
75 },
65 })
76 })
66 })?
77 })?
67 .collect::<rusqlite::Result<_>>()?;
78 .collect::<rusqlite::Result<_>>()?;
@@ -79,6 +90,7 @@ impl Store {
79 channels: Vec::new(),
90 channels: Vec::new(),
80 hidden: row.hidden,
91 hidden: row.hidden,
81 hidden_channel_ids: Vec::new(),
92 hidden_channel_ids: Vec::new(),
93 notifications: HashMap::new(),
82 })
94 })
83 .collect();
95 .collect();
84 for row in channel_rows {
96 for row in channel_rows {
@@ -89,6 +101,10 @@ impl Store {
89 if row.hidden {
101 if row.hidden {
90 team.hidden_channel_ids.push(row.channel.id.clone());
102 team.hidden_channel_ids.push(row.channel.id.clone());
91 }
103 }
104 if row.notifications != ChannelNotifications::default() {
105 team.notifications
106 .insert(row.channel.id.clone(), row.notifications);
107 }
92 team.channels.push(row.channel);
108 team.channels.push(row.channel);
93 }
109 }
94 }
110 }
@@ -100,12 +116,19 @@ impl Store {
100 let transaction = connection.transaction()?;
116 let transaction = connection.transaction()?;
101 transaction.execute("DELETE FROM team_layout", [])?;
117 transaction.execute("DELETE FROM team_layout", [])?;
102 transaction.execute("DELETE FROM channel_layout", [])?;
118 transaction.execute("DELETE FROM channel_layout", [])?;
119 transaction.execute("DELETE FROM channel_tabs", [])?;
103 {
120 {
104 let mut team_insert = transaction.prepare_cached(
121 let mut team_insert = transaction.prepare_cached(
105 "INSERT OR REPLACE INTO team_layout (team_id, position, hidden) VALUES (?1, ?2, ?3)",
122 "INSERT OR REPLACE INTO team_layout (team_id, position, hidden) VALUES (?1, ?2, ?3)",
106 )?;
123 )?;
107 let mut channel_insert = transaction.prepare_cached(
124 let mut channel_insert = transaction.prepare_cached(
108 "INSERT OR REPLACE INTO channel_layout (channel_id, general, hidden) VALUES (?1, ?2, ?3)",
125 "INSERT OR REPLACE INTO channel_layout
126 (channel_id, general, hidden, notification_level, include_replies)
127 VALUES (?1, ?2, ?3, ?4, ?5)",
128 )?;
129 let mut tab_insert = transaction.prepare_cached(
130 "INSERT OR REPLACE INTO channel_tabs (channel_id, position, tab_id, name, definition_id, open_url)
131 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
109 )?;
132 )?;
110 for (position, team) in layout.iter().enumerate() {
133 for (position, team) in layout.iter().enumerate() {
111 team_insert.execute(params![team.team_id, position as i64, team.hidden])?;
134 team_insert.execute(params![team.team_id, position as i64, team.hidden])?;
@@ -113,13 +136,67 @@ impl Store {
113 channel_insert.execute(params![
136 channel_insert.execute(params![
114 channel.channel_id,
137 channel.channel_id,
115 channel.general,
138 channel.general,
116 channel.hidden
139 channel.hidden,
140 channel.notifications.level.key(),
141 channel.notifications.include_replies
117 ])?;
142 ])?;
143 for (tab_position, tab) in channel.tabs.iter().enumerate() {
144 tab_insert.execute(params![
145 channel.channel_id,
146 tab_position as i64,
147 tab.tab_id,
148 tab.name,
149 tab.definition_id,
150 tab.open_url
151 ])?;
152 }
118 }
153 }
119 }
154 }
120 }
155 }
121 Ok(transaction.commit()?)
156 Ok(transaction.commit()?)
122 }
157 }
158
159 pub fn set_channel_notifications(
160 &self,
161 channel_id: &str,
162 notifications: ChannelNotifications,
163 ) -> Result<()> {
164 self.lock()?.execute(
165 "INSERT INTO channel_layout (channel_id, general, notification_level, include_replies)
166 SELECT id, name = ?2, ?3, ?4 FROM channels WHERE id = ?1
167 ON CONFLICT (channel_id) DO UPDATE SET
168 notification_level = excluded.notification_level,
169 include_replies = excluded.include_replies",
170 params![
171 channel_id,
172 GENERAL_FALLBACK_NAME,
173 notifications.level.key(),
174 notifications.include_replies
175 ],
176 )?;
177 Ok(())
178 }
179}
180
181impl Store {
182 pub fn channel_tabs(&self, channel_id: &str) -> Result<Vec<ChannelTabRecord>> {
183 let connection = self.lock()?;
184 let tabs = connection
185 .prepare_cached(
186 "SELECT tab_id, name, definition_id, open_url FROM channel_tabs
187 WHERE channel_id = ?1 ORDER BY position",
188 )?
189 .query_map(params![channel_id], |row| {
190 Ok(ChannelTabRecord {
191 tab_id: row.get(0)?,
192 name: row.get(1)?,
193 definition_id: row.get(2)?,
194 open_url: row.get(3)?,
195 })
196 })?
197 .collect::<rusqlite::Result<_>>()?;
198 Ok(tabs)
199 }
123}
200}
124
201
125fn compare_names(left: &str, right: &str) -> Ordering {
202fn compare_names(left: &str, right: &str) -> Ordering {
crates/store/tests/store.rs +104 −8
@@ -1,8 +1,9 @@
1 1 use chrono::{DateTime, TimeZone, Utc};
2 2 use rusqlite::Connection;
3 3 use store::{
4 AvatarRecord, ChannelRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
5 MessageRecord, Store, SyncState, TeamRecord,
4 AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,
5 ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
6 MessageRecord, Store, SyncState, TeamLayoutRecord, TeamRecord,
6 7 };
7 8
8 9 #[test]
@@ -469,11 +470,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
469 470 let path = directory.path().join("nested").join("cache.sqlite3");
470 471 {
471 472 let store = Store::open(&path).unwrap();
472 assert_eq!(store.schema_version().unwrap(), 14);
473 assert_eq!(store.schema_version().unwrap(), 16);
473 474 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
474 475 }
475 476 let reopened = Store::open(&path).unwrap();
476 assert_eq!(reopened.schema_version().unwrap(), 14);
477 assert_eq!(reopened.schema_version().unwrap(), 16);
477 478 assert_eq!(reopened.message_count("c").unwrap(), 1);
478 479 drop(reopened);
479 480 let mode: String = rusqlite_open(&path)
@@ -502,10 +503,10 @@ fn old_schema_is_upgraded_in_place() {
502 503 let path = directory.path().join("cache.sqlite3");
503 504 drop(Store::open(&path).unwrap());
504 505 let connection = rusqlite_open(&path);
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();
506 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 channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();
506 507 drop(connection);
507 508 let store = Store::open(&path).unwrap();
508 assert_eq!(store.schema_version().unwrap(), 14);
509 assert_eq!(store.schema_version().unwrap(), 16);
509 510 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
510 511 }
511 512
@@ -571,7 +572,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
571 572 let store = Store::open(&path).unwrap();
572 573 let state = store.sync_state("c").unwrap().unwrap();
573 574 assert_eq!(state.delta_link, None);
574 assert_eq!(store.schema_version().unwrap(), 14);
575 assert_eq!(store.schema_version().unwrap(), 16);
575 576 }
576 577
577 578 #[test]
@@ -589,6 +590,9 @@ fn migration_to_v13_clears_channel_delta_links_only() {
589 590 INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
590 591 ALTER TABLE messages DROP COLUMN subject;
591 592 ALTER TABLE folders DROP COLUMN expanded;
593 DROP TABLE channel_tabs;
594 ALTER TABLE channel_layout DROP COLUMN notification_level;
595 ALTER TABLE channel_layout DROP COLUMN include_replies;
592 596 PRAGMA user_version = 12",
593 597 )
594 598 .unwrap();
@@ -837,7 +841,7 @@ fn migration_indexes_rows_that_predate_search() {
837 841 "DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
838 842 DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
839 843 DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
840 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images;
844 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images;
841 845 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
842 846 ALTER TABLE messages DROP COLUMN sender_application_id;
843 847 ALTER TABLE messages DROP COLUMN links_json;
@@ -1095,3 +1099,95 @@ fn display_names_prefer_members_then_latest_sender_name() {
1095 1099 assert_eq!(names["user-sam"], "Sam New");
1096 1100 assert!(store.display_names(&[]).unwrap().is_empty());
1097 1101 }
1102
1103 #[test]
1104 fn channel_tabs_keep_their_saved_order_and_are_replaced_on_refresh() {
1105 let store = Store::open_in_memory().unwrap();
1106 let tab = |tab_id: &str, open_url: Option<&str>| ChannelTabRecord {
1107 tab_id: tab_id.to_owned(),
1108 name: format!("Tab {tab_id}"),
1109 definition_id: "com.microsoft.teamspace.tab.web".to_owned(),
1110 open_url: open_url.map(str::to_owned),
1111 };
1112 let layout = |tabs: Vec<ChannelTabRecord>| {
1113 vec![TeamLayoutRecord {
1114 team_id: "team".to_owned(),
1115 hidden: false,
1116 channels: vec![ChannelLayoutRecord {
1117 channel_id: "channel".to_owned(),
1118 general: false,
1119 hidden: false,
1120 tabs,
1121 notifications: ChannelNotifications::default(),
1122 }],
1123 }]
1124 };
1125 store
1126 .replace_team_layout(&layout(vec![
1127 tab("b", Some("https://b.example")),
1128 tab("a", None),
1129 ]))
1130 .unwrap();
1131 let tabs = store.channel_tabs("channel").unwrap();
1132 let ids: Vec<&str> = tabs.iter().map(|tab| tab.tab_id.as_str()).collect();
1133 assert_eq!(ids, ["b", "a"]);
1134 assert_eq!(tabs[0].open_url.as_deref(), Some("https://b.example"));
1135 assert!(store.channel_tabs("other").unwrap().is_empty());
1136 store.replace_team_layout(&layout(Vec::new())).unwrap();
1137 assert!(store.channel_tabs("channel").unwrap().is_empty());
1138 }
1139
1140 #[test]
1141 fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {
1142 let store = Store::open_in_memory().unwrap();
1143 store
1144 .upsert_teams(&[TeamRecord {
1145 id: "t1".to_owned(),
1146 name: "Alpha".to_owned(),
1147 }])
1148 .unwrap();
1149 let channel = |id: &str, name: &str| ChannelRecord {
1150 id: id.to_owned(),
1151 team_id: "t1".to_owned(),
1152 name: name.to_owned(),
1153 membership_type: None,
1154 last_message_at: None,
1155 unread: false,
1156 };
1157 store
1158 .upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1159 .unwrap();
1160 let team = || store.sidebar().unwrap().teams.remove(0);
1161 assert_eq!(
1162 team().channel_notifications("c2"),
1163 ChannelNotifications::default()
1164 );
1165
1166 let banner = ChannelNotifications {
1167 level: ChannelNotificationLevel::BannerAndFeed,
1168 include_replies: true,
1169 };
1170 store.set_channel_notifications("c2", banner).unwrap();
1171 let sidebar_team = team();
1172 assert_eq!(sidebar_team.channel_notifications("c2"), banner);
1173 assert_eq!(sidebar_team.channels[0].name, "General");
1174
1175 let off = ChannelNotifications {
1176 level: ChannelNotificationLevel::Off,
1177 include_replies: false,
1178 };
1179 store
1180 .replace_team_layout(&[TeamLayoutRecord {
1181 team_id: "t1".to_owned(),
1182 hidden: false,
1183 channels: vec![ChannelLayoutRecord {
1184 channel_id: "c2".to_owned(),
1185 general: false,
1186 hidden: false,
1187 tabs: Vec::new(),
1188 notifications: off,
1189 }],
1190 }])
1191 .unwrap();
1192 assert_eq!(team().channel_notifications("c2"), off);
1193 }
@@ -1,8 +1,9 @@
1use chrono::{DateTime, TimeZone, Utc};
1use chrono::{DateTime, TimeZone, Utc};
2use rusqlite::Connection;
2use rusqlite::Connection;
3use store::{
3use store::{
4 AvatarRecord, ChannelRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
4 AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,
5 MessageRecord, Store, SyncState, TeamRecord,
5 ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
6 MessageRecord, Store, SyncState, TeamLayoutRecord, TeamRecord,
6};
7};
7
8
8#[test]
9#[test]
@@ -469,11 +470,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
469 let path = directory.path().join("nested").join("cache.sqlite3");
470 let path = directory.path().join("nested").join("cache.sqlite3");
470 {
471 {
471 let store = Store::open(&path).unwrap();
472 let store = Store::open(&path).unwrap();
472 assert_eq!(store.schema_version().unwrap(), 14);
473 assert_eq!(store.schema_version().unwrap(), 16);
473 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
474 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
474 }
475 }
475 let reopened = Store::open(&path).unwrap();
476 let reopened = Store::open(&path).unwrap();
476 assert_eq!(reopened.schema_version().unwrap(), 14);
477 assert_eq!(reopened.schema_version().unwrap(), 16);
477 assert_eq!(reopened.message_count("c").unwrap(), 1);
478 assert_eq!(reopened.message_count("c").unwrap(), 1);
478 drop(reopened);
479 drop(reopened);
479 let mode: String = rusqlite_open(&path)
480 let mode: String = rusqlite_open(&path)
@@ -502,10 +503,10 @@ fn old_schema_is_upgraded_in_place() {
502 let path = directory.path().join("cache.sqlite3");
503 let path = directory.path().join("cache.sqlite3");
503 drop(Store::open(&path).unwrap());
504 drop(Store::open(&path).unwrap());
504 let connection = rusqlite_open(&path);
505 let connection = rusqlite_open(&path);
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();
506 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 channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();
506 drop(connection);
507 drop(connection);
507 let store = Store::open(&path).unwrap();
508 let store = Store::open(&path).unwrap();
508 assert_eq!(store.schema_version().unwrap(), 14);
509 assert_eq!(store.schema_version().unwrap(), 16);
509 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
510 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
510}
511}
511
512
@@ -571,7 +572,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
571 let store = Store::open(&path).unwrap();
572 let store = Store::open(&path).unwrap();
572 let state = store.sync_state("c").unwrap().unwrap();
573 let state = store.sync_state("c").unwrap().unwrap();
573 assert_eq!(state.delta_link, None);
574 assert_eq!(state.delta_link, None);
574 assert_eq!(store.schema_version().unwrap(), 14);
575 assert_eq!(store.schema_version().unwrap(), 16);
575}
576}
576
577
577#[test]
578#[test]
@@ -589,6 +590,9 @@ fn migration_to_v13_clears_channel_delta_links_only() {
589 INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
590 INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
590 ALTER TABLE messages DROP COLUMN subject;
591 ALTER TABLE messages DROP COLUMN subject;
591 ALTER TABLE folders DROP COLUMN expanded;
592 ALTER TABLE folders DROP COLUMN expanded;
593 DROP TABLE channel_tabs;
594 ALTER TABLE channel_layout DROP COLUMN notification_level;
595 ALTER TABLE channel_layout DROP COLUMN include_replies;
592 PRAGMA user_version = 12",
596 PRAGMA user_version = 12",
593 )
597 )
594 .unwrap();
598 .unwrap();
@@ -837,7 +841,7 @@ fn migration_indexes_rows_that_predate_search() {
837 "DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
841 "DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
838 DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
842 DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
839 DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
843 DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
840 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images;
844 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images;
841 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
845 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
842 ALTER TABLE messages DROP COLUMN sender_application_id;
846 ALTER TABLE messages DROP COLUMN sender_application_id;
843 ALTER TABLE messages DROP COLUMN links_json;
847 ALTER TABLE messages DROP COLUMN links_json;
@@ -1095,3 +1099,95 @@ fn display_names_prefer_members_then_latest_sender_name() {
1095 assert_eq!(names["user-sam"], "Sam New");
1099 assert_eq!(names["user-sam"], "Sam New");
1096 assert!(store.display_names(&[]).unwrap().is_empty());
1100 assert!(store.display_names(&[]).unwrap().is_empty());
1097}
1101}
1102
1103#[test]
1104fn channel_tabs_keep_their_saved_order_and_are_replaced_on_refresh() {
1105 let store = Store::open_in_memory().unwrap();
1106 let tab = |tab_id: &str, open_url: Option<&str>| ChannelTabRecord {
1107 tab_id: tab_id.to_owned(),
1108 name: format!("Tab {tab_id}"),
1109 definition_id: "com.microsoft.teamspace.tab.web".to_owned(),
1110 open_url: open_url.map(str::to_owned),
1111 };
1112 let layout = |tabs: Vec<ChannelTabRecord>| {
1113 vec![TeamLayoutRecord {
1114 team_id: "team".to_owned(),
1115 hidden: false,
1116 channels: vec![ChannelLayoutRecord {
1117 channel_id: "channel".to_owned(),
1118 general: false,
1119 hidden: false,
1120 tabs,
1121 notifications: ChannelNotifications::default(),
1122 }],
1123 }]
1124 };
1125 store
1126 .replace_team_layout(&layout(vec![
1127 tab("b", Some("https://b.example")),
1128 tab("a", None),
1129 ]))
1130 .unwrap();
1131 let tabs = store.channel_tabs("channel").unwrap();
1132 let ids: Vec<&str> = tabs.iter().map(|tab| tab.tab_id.as_str()).collect();
1133 assert_eq!(ids, ["b", "a"]);
1134 assert_eq!(tabs[0].open_url.as_deref(), Some("https://b.example"));
1135 assert!(store.channel_tabs("other").unwrap().is_empty());
1136 store.replace_team_layout(&layout(Vec::new())).unwrap();
1137 assert!(store.channel_tabs("channel").unwrap().is_empty());
1138}
1139
1140#[test]
1141fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {
1142 let store = Store::open_in_memory().unwrap();
1143 store
1144 .upsert_teams(&[TeamRecord {
1145 id: "t1".to_owned(),
1146 name: "Alpha".to_owned(),
1147 }])
1148 .unwrap();
1149 let channel = |id: &str, name: &str| ChannelRecord {
1150 id: id.to_owned(),
1151 team_id: "t1".to_owned(),
1152 name: name.to_owned(),
1153 membership_type: None,
1154 last_message_at: None,
1155 unread: false,
1156 };
1157 store
1158 .upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1159 .unwrap();
1160 let team = || store.sidebar().unwrap().teams.remove(0);
1161 assert_eq!(
1162 team().channel_notifications("c2"),
1163 ChannelNotifications::default()
1164 );
1165
1166 let banner = ChannelNotifications {
1167 level: ChannelNotificationLevel::BannerAndFeed,
1168 include_replies: true,
1169 };
1170 store.set_channel_notifications("c2", banner).unwrap();
1171 let sidebar_team = team();
1172 assert_eq!(sidebar_team.channel_notifications("c2"), banner);
1173 assert_eq!(sidebar_team.channels[0].name, "General");
1174
1175 let off = ChannelNotifications {
1176 level: ChannelNotificationLevel::Off,
1177 include_replies: false,
1178 };
1179 store
1180 .replace_team_layout(&[TeamLayoutRecord {
1181 team_id: "t1".to_owned(),
1182 hidden: false,
1183 channels: vec![ChannelLayoutRecord {
1184 channel_id: "c2".to_owned(),
1185 general: false,
1186 hidden: false,
1187 tabs: Vec::new(),
1188 notifications: off,
1189 }],
1190 }])
1191 .unwrap();
1192 assert_eq!(team().channel_notifications("c2"), off);
1193}
crates/webview/src/embed.rs added +68 −0
@@ -0,0 +1,68 @@
1 use std::sync::{Arc, mpsc};
2
3 use crate::transport::UiRequest;
4
5 #[derive(Debug, Clone)]
6 pub struct EmbedSpec {
7 pub parent: isize,
8 pub url: String,
9 pub background: u32,
10 }
11
12 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
13 pub struct EmbedBounds {
14 pub x: i32,
15 pub y: i32,
16 pub width: i32,
17 pub height: i32,
18 }
19
20 #[derive(Debug, Clone, PartialEq, Eq)]
21 pub enum EmbedEvent {
22 Navigated(String),
23 NewWindow(String),
24 Closed,
25 }
26
27 #[derive(Debug)]
28 pub(crate) enum EmbedCommand {
29 Bounds(EmbedBounds),
30 Visible(bool),
31 Navigate(String),
32 Close,
33 }
34
35 #[derive(Clone)]
36 pub struct EmbedHandle {
37 pub(crate) id: u64,
38 pub(crate) requests: mpsc::Sender<UiRequest>,
39 pub(crate) waker: Arc<dyn Fn() + Send + Sync>,
40 }
41
42 impl EmbedHandle {
43 pub fn set_bounds(&self, bounds: EmbedBounds) {
44 self.send(EmbedCommand::Bounds(bounds));
45 }
46
47 pub fn set_visible(&self, visible: bool) {
48 self.send(EmbedCommand::Visible(visible));
49 }
50
51 pub fn navigate(&self, url: String) {
52 self.send(EmbedCommand::Navigate(url));
53 }
54
55 pub fn close(&self) {
56 self.send(EmbedCommand::Close);
57 }
58
59 fn send(&self, command: EmbedCommand) {
60 let request = UiRequest::Embed {
61 id: self.id,
62 command,
63 };
64 if self.requests.send(request).is_ok() {
65 (self.waker)();
66 }
67 }
68 }
@@ -0,0 +1,68 @@
1use std::sync::{Arc, mpsc};
2
3use crate::transport::UiRequest;
4
5#[derive(Debug, Clone)]
6pub struct EmbedSpec {
7 pub parent: isize,
8 pub url: String,
9 pub background: u32,
10}
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct EmbedBounds {
14 pub x: i32,
15 pub y: i32,
16 pub width: i32,
17 pub height: i32,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum EmbedEvent {
22 Navigated(String),
23 NewWindow(String),
24 Closed,
25}
26
27#[derive(Debug)]
28pub(crate) enum EmbedCommand {
29 Bounds(EmbedBounds),
30 Visible(bool),
31 Navigate(String),
32 Close,
33}
34
35#[derive(Clone)]
36pub struct EmbedHandle {
37 pub(crate) id: u64,
38 pub(crate) requests: mpsc::Sender<UiRequest>,
39 pub(crate) waker: Arc<dyn Fn() + Send + Sync>,
40}
41
42impl EmbedHandle {
43 pub fn set_bounds(&self, bounds: EmbedBounds) {
44 self.send(EmbedCommand::Bounds(bounds));
45 }
46
47 pub fn set_visible(&self, visible: bool) {
48 self.send(EmbedCommand::Visible(visible));
49 }
50
51 pub fn navigate(&self, url: String) {
52 self.send(EmbedCommand::Navigate(url));
53 }
54
55 pub fn close(&self) {
56 self.send(EmbedCommand::Close);
57 }
58
59 fn send(&self, command: EmbedCommand) {
60 let request = UiRequest::Embed {
61 id: self.id,
62 command,
63 };
64 if self.requests.send(request).is_ok() {
65 (self.waker)();
66 }
67 }
68}
crates/webview/src/host.rs +6 −0
@@ -23,6 +23,7 @@ use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};
23 23
24 24 use crate::fanout::Subscribers;
25 25 use crate::host_dialog::{self, Dialog};
26 use crate::host_embed::{self, Embed};
26 27 use crate::transport::{HostState, UiRequest, WebViewTransport};
27 28 use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};
28 29
@@ -54,6 +55,7 @@ pub(crate) struct Shared {
54 55 views: RefCell<HashMap<App, View>>,
55 56 pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,
56 57 pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,
58 pub(crate) embeds: RefCell<HashMap<u64, Embed>>,
57 59 subscribers: RefCell<Subscribers>,
58 60 state: watch::Sender<HostState>,
59 61 requests: mpsc::Receiver<UiRequest>,
@@ -114,6 +116,7 @@ fn run(
114 116 views: RefCell::new(HashMap::new()),
115 117 environment: RefCell::new(None),
116 118 dialogs: RefCell::new(HashMap::new()),
119 embeds: RefCell::new(HashMap::new()),
117 120 subscribers: RefCell::new(Subscribers::default()),
118 121 state,
119 122 requests,
@@ -431,6 +434,8 @@ fn drain(shared: &Rc<Shared>) {
431 434 host_dialog::open(shared, id, spec, events)
432 435 }
433 436 UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),
437 UiRequest::OpenEmbed { id, spec, events } => host_embed::open(shared, id, spec, events),
438 UiRequest::Embed { id, command } => host_embed::run(shared, id, command),
434 439 }
435 440 }
436 441 }
@@ -520,6 +525,7 @@ fn restart(shared: &Rc<Shared>) {
520 525 shared.state.send_modify(|state| state.ready = false);
521 526 shared.subscribers.borrow_mut().clear();
522 527 host_dialog::close_all(shared);
528 host_embed::close_all(shared);
523 529 let views: Vec<View> = shared
524 530 .views
525 531 .borrow_mut()
@@ -23,6 +23,7 @@ use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};
23
23
24use crate::fanout::Subscribers;
24use crate::fanout::Subscribers;
25use crate::host_dialog::{self, Dialog};
25use crate::host_dialog::{self, Dialog};
26use crate::host_embed::{self, Embed};
26use crate::transport::{HostState, UiRequest, WebViewTransport};
27use crate::transport::{HostState, UiRequest, WebViewTransport};
27use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};
28use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};
28
29
@@ -54,6 +55,7 @@ pub(crate) struct Shared {
54 views: RefCell<HashMap<App, View>>,
55 views: RefCell<HashMap<App, View>>,
55 pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,
56 pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,
56 pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,
57 pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,
58 pub(crate) embeds: RefCell<HashMap<u64, Embed>>,
57 subscribers: RefCell<Subscribers>,
59 subscribers: RefCell<Subscribers>,
58 state: watch::Sender<HostState>,
60 state: watch::Sender<HostState>,
59 requests: mpsc::Receiver<UiRequest>,
61 requests: mpsc::Receiver<UiRequest>,
@@ -114,6 +116,7 @@ fn run(
114 views: RefCell::new(HashMap::new()),
116 views: RefCell::new(HashMap::new()),
115 environment: RefCell::new(None),
117 environment: RefCell::new(None),
116 dialogs: RefCell::new(HashMap::new()),
118 dialogs: RefCell::new(HashMap::new()),
119 embeds: RefCell::new(HashMap::new()),
117 subscribers: RefCell::new(Subscribers::default()),
120 subscribers: RefCell::new(Subscribers::default()),
118 state,
121 state,
119 requests,
122 requests,
@@ -431,6 +434,8 @@ fn drain(shared: &Rc<Shared>) {
431 host_dialog::open(shared, id, spec, events)
434 host_dialog::open(shared, id, spec, events)
432 }
435 }
433 UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),
436 UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),
437 UiRequest::OpenEmbed { id, spec, events } => host_embed::open(shared, id, spec, events),
438 UiRequest::Embed { id, command } => host_embed::run(shared, id, command),
434 }
439 }
435 }
440 }
436}
441}
@@ -520,6 +525,7 @@ fn restart(shared: &Rc<Shared>) {
520 shared.state.send_modify(|state| state.ready = false);
525 shared.state.send_modify(|state| state.ready = false);
521 shared.subscribers.borrow_mut().clear();
526 shared.subscribers.borrow_mut().clear();
522 host_dialog::close_all(shared);
527 host_dialog::close_all(shared);
528 host_embed::close_all(shared);
523 let views: Vec<View> = shared
529 let views: Vec<View> = shared
524 .views
530 .views
525 .borrow_mut()
531 .borrow_mut()
crates/webview/src/host_embed.rs added +222 −0
@@ -0,0 +1,222 @@
1 use std::rc::Rc;
2
3 use tokio::sync::mpsc::UnboundedSender;
4 use webview2_com::Microsoft::Web::WebView2::Win32::*;
5 use webview2_com::{
6 CreateCoreWebView2ControllerCompletedHandler, NewWindowRequestedEventHandler,
7 SourceChangedEventHandler, take_pwstr,
8 };
9 use windows::Win32::Foundation::{HWND, RECT};
10 use windows::core::{HSTRING, Interface, PWSTR};
11
12 use crate::embed::{EmbedBounds, EmbedCommand, EmbedEvent, EmbedSpec};
13 use crate::host::{Shared, shared as running_host};
14
15 struct EmbedView {
16 controller: ICoreWebView2Controller,
17 webview: ICoreWebView2,
18 }
19
20 pub(crate) struct Embed {
21 view: Option<EmbedView>,
22 bounds: Option<EmbedBounds>,
23 visible: bool,
24 events: UnboundedSender<EmbedEvent>,
25 }
26
27 pub(crate) fn open(
28 shared: &Rc<Shared>,
29 id: u64,
30 spec: EmbedSpec,
31 events: UnboundedSender<EmbedEvent>,
32 ) {
33 let Some(environment) = shared.environment.borrow().clone() else {
34 let _ = events.send(EmbedEvent::Closed);
35 return;
36 };
37 shared.embeds.borrow_mut().insert(
38 id,
39 Embed {
40 view: None,
41 bounds: None,
42 visible: false,
43 events,
44 },
45 );
46 let parent = HWND(spec.parent as *mut _);
47 let handler =
48 CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |code, controller| {
49 let Some(shared) = running_host() else {
50 return Ok(());
51 };
52 let attached = code
53 .and_then(|()| {
54 controller.ok_or_else(|| windows::core::Error::from(windows::core::HRESULT(-1)))
55 })
56 .and_then(|controller| attach(&shared, id, controller, &spec));
57 if attached.is_err() {
58 close(&shared, id);
59 }
60 Ok(())
61 }));
62 if unsafe { environment.CreateCoreWebView2Controller(parent, &handler) }.is_err() {
63 close(shared, id);
64 }
65 }
66
67 pub(crate) fn run(shared: &Rc<Shared>, id: u64, command: EmbedCommand) {
68 match command {
69 EmbedCommand::Bounds(bounds) => {
70 let controller = update(shared, id, |embed| embed.bounds = Some(bounds));
71 if let Some(controller) = controller {
72 apply_bounds(&controller, bounds);
73 }
74 }
75 EmbedCommand::Visible(visible) => {
76 let controller = update(shared, id, |embed| embed.visible = visible);
77 if let Some(controller) = controller {
78 unsafe {
79 let _ = controller.SetIsVisible(visible);
80 }
81 }
82 }
83 EmbedCommand::Navigate(url) => {
84 let webview = shared
85 .embeds
86 .borrow()
87 .get(&id)
88 .and_then(|embed| embed.view.as_ref().map(|view| view.webview.clone()));
89 if let Some(webview) = webview {
90 unsafe {
91 let _ = webview.Navigate(&HSTRING::from(url));
92 }
93 }
94 }
95 EmbedCommand::Close => close(shared, id),
96 }
97 }
98
99 pub(crate) fn close(shared: &Rc<Shared>, id: u64) {
100 let Some(embed) = shared.embeds.borrow_mut().remove(&id) else {
101 return;
102 };
103 if let Some(view) = &embed.view {
104 unsafe {
105 let _ = view.controller.Close();
106 }
107 }
108 let _ = embed.events.send(EmbedEvent::Closed);
109 }
110
111 pub(crate) fn close_all(shared: &Rc<Shared>) {
112 let ids: Vec<u64> = shared.embeds.borrow().keys().copied().collect();
113 for id in ids {
114 close(shared, id);
115 }
116 }
117
118 fn update(
119 shared: &Shared,
120 id: u64,
121 change: impl FnOnce(&mut Embed),
122 ) -> Option<ICoreWebView2Controller> {
123 let mut embeds = shared.embeds.borrow_mut();
124 let embed = embeds.get_mut(&id)?;
125 change(embed);
126 embed.view.as_ref().map(|view| view.controller.clone())
127 }
128
129 fn emit(id: u64, event: EmbedEvent) {
130 if let Some(shared) = running_host()
131 && let Some(embed) = shared.embeds.borrow().get(&id)
132 {
133 let _ = embed.events.send(event);
134 }
135 }
136
137 fn apply_bounds(controller: &ICoreWebView2Controller, bounds: EmbedBounds) {
138 unsafe {
139 let _ = controller.SetBounds(RECT {
140 left: bounds.x,
141 top: bounds.y,
142 right: bounds.x + bounds.width,
143 bottom: bounds.y + bounds.height,
144 });
145 }
146 }
147
148 fn attach(
149 shared: &Rc<Shared>,
150 id: u64,
151 controller: ICoreWebView2Controller,
152 spec: &EmbedSpec,
153 ) -> windows::core::Result<()> {
154 let Some((bounds, visible)) = shared
155 .embeds
156 .borrow()
157 .get(&id)
158 .map(|embed| (embed.bounds, embed.visible))
159 else {
160 unsafe { controller.Close() }?;
161 return Ok(());
162 };
163 let webview = unsafe { controller.CoreWebView2() }?;
164 unsafe {
165 controller
166 .cast::<ICoreWebView2Controller2>()?
167 .SetDefaultBackgroundColor(COREWEBVIEW2_COLOR {
168 A: 255,
169 R: (spec.background >> 16) as u8,
170 G: (spec.background >> 8) as u8,
171 B: spec.background as u8,
172 })?;
173 webview.Settings()?.SetIsStatusBarEnabled(false)?;
174 }
175 if let Some(bounds) = bounds {
176 apply_bounds(&controller, bounds);
177 }
178 watch_source(&webview, id)?;
179 forward_new_windows(&webview, id)?;
180 unsafe {
181 controller.SetIsVisible(visible)?;
182 webview.Navigate(&HSTRING::from(spec.url.as_str()))?;
183 }
184 if let Some(embed) = shared.embeds.borrow_mut().get_mut(&id) {
185 embed.view = Some(EmbedView {
186 controller,
187 webview,
188 });
189 }
190 Ok(())
191 }
192
193 fn watch_source(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {
194 let handler = SourceChangedEventHandler::create(Box::new(move |sender, _| {
195 if let Some(sender) = sender {
196 let mut source = PWSTR::null();
197 if unsafe { sender.Source(&mut source) }.is_ok() {
198 emit(id, EmbedEvent::Navigated(take_pwstr(source)));
199 }
200 }
201 Ok(())
202 }));
203 let mut token = 0;
204 unsafe { webview.add_SourceChanged(&handler, &mut token) }
205 }
206
207 fn forward_new_windows(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {
208 let handler = NewWindowRequestedEventHandler::create(Box::new(move |_, arguments| {
209 let Some(arguments) = arguments else {
210 return Ok(());
211 };
212 let mut target = PWSTR::null();
213 unsafe {
214 arguments.Uri(&mut target)?;
215 arguments.SetHandled(true)?;
216 }
217 emit(id, EmbedEvent::NewWindow(take_pwstr(target)));
218 Ok(())
219 }));
220 let mut token = 0;
221 unsafe { webview.add_NewWindowRequested(&handler, &mut token) }
222 }
@@ -0,0 +1,222 @@
1use std::rc::Rc;
2
3use tokio::sync::mpsc::UnboundedSender;
4use webview2_com::Microsoft::Web::WebView2::Win32::*;
5use webview2_com::{
6 CreateCoreWebView2ControllerCompletedHandler, NewWindowRequestedEventHandler,
7 SourceChangedEventHandler, take_pwstr,
8};
9use windows::Win32::Foundation::{HWND, RECT};
10use windows::core::{HSTRING, Interface, PWSTR};
11
12use crate::embed::{EmbedBounds, EmbedCommand, EmbedEvent, EmbedSpec};
13use crate::host::{Shared, shared as running_host};
14
15struct EmbedView {
16 controller: ICoreWebView2Controller,
17 webview: ICoreWebView2,
18}
19
20pub(crate) struct Embed {
21 view: Option<EmbedView>,
22 bounds: Option<EmbedBounds>,
23 visible: bool,
24 events: UnboundedSender<EmbedEvent>,
25}
26
27pub(crate) fn open(
28 shared: &Rc<Shared>,
29 id: u64,
30 spec: EmbedSpec,
31 events: UnboundedSender<EmbedEvent>,
32) {
33 let Some(environment) = shared.environment.borrow().clone() else {
34 let _ = events.send(EmbedEvent::Closed);
35 return;
36 };
37 shared.embeds.borrow_mut().insert(
38 id,
39 Embed {
40 view: None,
41 bounds: None,
42 visible: false,
43 events,
44 },
45 );
46 let parent = HWND(spec.parent as *mut _);
47 let handler =
48 CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |code, controller| {
49 let Some(shared) = running_host() else {
50 return Ok(());
51 };
52 let attached = code
53 .and_then(|()| {
54 controller.ok_or_else(|| windows::core::Error::from(windows::core::HRESULT(-1)))
55 })
56 .and_then(|controller| attach(&shared, id, controller, &spec));
57 if attached.is_err() {
58 close(&shared, id);
59 }
60 Ok(())
61 }));
62 if unsafe { environment.CreateCoreWebView2Controller(parent, &handler) }.is_err() {
63 close(shared, id);
64 }
65}
66
67pub(crate) fn run(shared: &Rc<Shared>, id: u64, command: EmbedCommand) {
68 match command {
69 EmbedCommand::Bounds(bounds) => {
70 let controller = update(shared, id, |embed| embed.bounds = Some(bounds));
71 if let Some(controller) = controller {
72 apply_bounds(&controller, bounds);
73 }
74 }
75 EmbedCommand::Visible(visible) => {
76 let controller = update(shared, id, |embed| embed.visible = visible);
77 if let Some(controller) = controller {
78 unsafe {
79 let _ = controller.SetIsVisible(visible);
80 }
81 }
82 }
83 EmbedCommand::Navigate(url) => {
84 let webview = shared
85 .embeds
86 .borrow()
87 .get(&id)
88 .and_then(|embed| embed.view.as_ref().map(|view| view.webview.clone()));
89 if let Some(webview) = webview {
90 unsafe {
91 let _ = webview.Navigate(&HSTRING::from(url));
92 }
93 }
94 }
95 EmbedCommand::Close => close(shared, id),
96 }
97}
98
99pub(crate) fn close(shared: &Rc<Shared>, id: u64) {
100 let Some(embed) = shared.embeds.borrow_mut().remove(&id) else {
101 return;
102 };
103 if let Some(view) = &embed.view {
104 unsafe {
105 let _ = view.controller.Close();
106 }
107 }
108 let _ = embed.events.send(EmbedEvent::Closed);
109}
110
111pub(crate) fn close_all(shared: &Rc<Shared>) {
112 let ids: Vec<u64> = shared.embeds.borrow().keys().copied().collect();
113 for id in ids {
114 close(shared, id);
115 }
116}
117
118fn update(
119 shared: &Shared,
120 id: u64,
121 change: impl FnOnce(&mut Embed),
122) -> Option<ICoreWebView2Controller> {
123 let mut embeds = shared.embeds.borrow_mut();
124 let embed = embeds.get_mut(&id)?;
125 change(embed);
126 embed.view.as_ref().map(|view| view.controller.clone())
127}
128
129fn emit(id: u64, event: EmbedEvent) {
130 if let Some(shared) = running_host()
131 && let Some(embed) = shared.embeds.borrow().get(&id)
132 {
133 let _ = embed.events.send(event);
134 }
135}
136
137fn apply_bounds(controller: &ICoreWebView2Controller, bounds: EmbedBounds) {
138 unsafe {
139 let _ = controller.SetBounds(RECT {
140 left: bounds.x,
141 top: bounds.y,
142 right: bounds.x + bounds.width,
143 bottom: bounds.y + bounds.height,
144 });
145 }
146}
147
148fn attach(
149 shared: &Rc<Shared>,
150 id: u64,
151 controller: ICoreWebView2Controller,
152 spec: &EmbedSpec,
153) -> windows::core::Result<()> {
154 let Some((bounds, visible)) = shared
155 .embeds
156 .borrow()
157 .get(&id)
158 .map(|embed| (embed.bounds, embed.visible))
159 else {
160 unsafe { controller.Close() }?;
161 return Ok(());
162 };
163 let webview = unsafe { controller.CoreWebView2() }?;
164 unsafe {
165 controller
166 .cast::<ICoreWebView2Controller2>()?
167 .SetDefaultBackgroundColor(COREWEBVIEW2_COLOR {
168 A: 255,
169 R: (spec.background >> 16) as u8,
170 G: (spec.background >> 8) as u8,
171 B: spec.background as u8,
172 })?;
173 webview.Settings()?.SetIsStatusBarEnabled(false)?;
174 }
175 if let Some(bounds) = bounds {
176 apply_bounds(&controller, bounds);
177 }
178 watch_source(&webview, id)?;
179 forward_new_windows(&webview, id)?;
180 unsafe {
181 controller.SetIsVisible(visible)?;
182 webview.Navigate(&HSTRING::from(spec.url.as_str()))?;
183 }
184 if let Some(embed) = shared.embeds.borrow_mut().get_mut(&id) {
185 embed.view = Some(EmbedView {
186 controller,
187 webview,
188 });
189 }
190 Ok(())
191}
192
193fn watch_source(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {
194 let handler = SourceChangedEventHandler::create(Box::new(move |sender, _| {
195 if let Some(sender) = sender {
196 let mut source = PWSTR::null();
197 if unsafe { sender.Source(&mut source) }.is_ok() {
198 emit(id, EmbedEvent::Navigated(take_pwstr(source)));
199 }
200 }
201 Ok(())
202 }));
203 let mut token = 0;
204 unsafe { webview.add_SourceChanged(&handler, &mut token) }
205}
206
207fn forward_new_windows(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {
208 let handler = NewWindowRequestedEventHandler::create(Box::new(move |_, arguments| {
209 let Some(arguments) = arguments else {
210 return Ok(());
211 };
212 let mut target = PWSTR::null();
213 unsafe {
214 arguments.Uri(&mut target)?;
215 arguments.SetHandled(true)?;
216 }
217 emit(id, EmbedEvent::NewWindow(take_pwstr(target)));
218 Ok(())
219 }));
220 let mut token = 0;
221 unsafe { webview.add_NewWindowRequested(&handler, &mut token) }
222}
crates/webview/src/lib.rs +3 −0
@@ -1,12 +1,15 @@
1 1 #![cfg(windows)]
2 2
3 3 mod dialog;
4 mod embed;
4 5 mod fanout;
5 6 mod host;
6 7 mod host_dialog;
8 mod host_embed;
7 9 mod transport;
8 10
9 11 pub use dialog::{DialogEvent, DialogHandle, DialogSpec};
12 pub use embed::{EmbedBounds, EmbedEvent, EmbedHandle, EmbedSpec};
10 13 pub use host::{HostConfig, start};
11 14 pub use transport::{HostState, WebViewTransport};
12 15
@@ -1,12 +1,15 @@
1#![cfg(windows)]
1#![cfg(windows)]
2
2
3mod dialog;
3mod dialog;
4mod embed;
4mod fanout;
5mod fanout;
5mod host;
6mod host;
6mod host_dialog;
7mod host_dialog;
8mod host_embed;
7mod transport;
9mod transport;
8
10
9pub use dialog::{DialogEvent, DialogHandle, DialogSpec};
11pub use dialog::{DialogEvent, DialogHandle, DialogSpec};
12pub use embed::{EmbedBounds, EmbedEvent, EmbedHandle, EmbedSpec};
10pub use host::{HostConfig, start};
13pub use host::{HostConfig, start};
11pub use transport::{HostState, WebViewTransport};
14pub use transport::{HostState, WebViewTransport};
12
15
crates/webview/src/transport.rs +24 −0
@@ -13,6 +13,7 @@ use tokio::sync::{
13 13 };
14 14
15 15 use crate::dialog::{DialogCommand, DialogEvent, DialogHandle, DialogSpec};
16 use crate::embed::{EmbedCommand, EmbedEvent, EmbedHandle, EmbedSpec};
16 17
17 18 const ENDPOINT_NAME: &str = "WebView2";
18 19 const READY_WAIT: Duration = Duration::from_secs(30);
@@ -39,6 +40,15 @@ pub(crate) enum UiRequest {
39 40 id: u64,
40 41 command: DialogCommand,
41 42 },
43 OpenEmbed {
44 id: u64,
45 spec: EmbedSpec,
46 events: UnboundedSender<EmbedEvent>,
47 },
48 Embed {
49 id: u64,
50 command: EmbedCommand,
51 },
42 52 }
43 53
44 54 #[derive(Debug, Clone, Default)]
@@ -54,6 +64,7 @@ pub struct WebViewTransport {
54 64 state: watch::Receiver<HostState>,
55 65 ready_wait: Duration,
56 66 next_dialog: AtomicU64,
67 next_embed: AtomicU64,
57 68 }
58 69
59 70 impl WebViewTransport {
@@ -68,6 +79,7 @@ impl WebViewTransport {
68 79 state,
69 80 ready_wait: READY_WAIT,
70 81 next_dialog: AtomicU64::new(1),
82 next_embed: AtomicU64::new(1),
71 83 }
72 84 }
73 85
@@ -83,6 +95,18 @@ impl WebViewTransport {
83 95 (handle, receiver)
84 96 }
85 97
98 pub fn open_embed(&self, spec: EmbedSpec) -> (EmbedHandle, UnboundedReceiver<EmbedEvent>) {
99 let id = self.next_embed.fetch_add(1, Ordering::Relaxed);
100 let (events, receiver) = unbounded_channel();
101 let handle = EmbedHandle {
102 id,
103 requests: self.requests.clone(),
104 waker: self.waker.clone(),
105 };
106 let _ = self.send(UiRequest::OpenEmbed { id, spec, events });
107 (handle, receiver)
108 }
109
86 110 fn send(&self, request: UiRequest) -> Result<()> {
87 111 self.requests
88 112 .send(request)
@@ -13,6 +13,7 @@ use tokio::sync::{
13};
13};
14
14
15use crate::dialog::{DialogCommand, DialogEvent, DialogHandle, DialogSpec};
15use crate::dialog::{DialogCommand, DialogEvent, DialogHandle, DialogSpec};
16use crate::embed::{EmbedCommand, EmbedEvent, EmbedHandle, EmbedSpec};
16
17
17const ENDPOINT_NAME: &str = "WebView2";
18const ENDPOINT_NAME: &str = "WebView2";
18const READY_WAIT: Duration = Duration::from_secs(30);
19const READY_WAIT: Duration = Duration::from_secs(30);
@@ -39,6 +40,15 @@ pub(crate) enum UiRequest {
39 id: u64,
40 id: u64,
40 command: DialogCommand,
41 command: DialogCommand,
41 },
42 },
43 OpenEmbed {
44 id: u64,
45 spec: EmbedSpec,
46 events: UnboundedSender<EmbedEvent>,
47 },
48 Embed {
49 id: u64,
50 command: EmbedCommand,
51 },
42}
52}
43
53
44#[derive(Debug, Clone, Default)]
54#[derive(Debug, Clone, Default)]
@@ -54,6 +64,7 @@ pub struct WebViewTransport {
54 state: watch::Receiver<HostState>,
64 state: watch::Receiver<HostState>,
55 ready_wait: Duration,
65 ready_wait: Duration,
56 next_dialog: AtomicU64,
66 next_dialog: AtomicU64,
67 next_embed: AtomicU64,
57}
68}
58
69
59impl WebViewTransport {
70impl WebViewTransport {
@@ -68,6 +79,7 @@ impl WebViewTransport {
68 state,
79 state,
69 ready_wait: READY_WAIT,
80 ready_wait: READY_WAIT,
70 next_dialog: AtomicU64::new(1),
81 next_dialog: AtomicU64::new(1),
82 next_embed: AtomicU64::new(1),
71 }
83 }
72 }
84 }
73
85
@@ -83,6 +95,18 @@ impl WebViewTransport {
83 (handle, receiver)
95 (handle, receiver)
84 }
96 }
85
97
98 pub fn open_embed(&self, spec: EmbedSpec) -> (EmbedHandle, UnboundedReceiver<EmbedEvent>) {
99 let id = self.next_embed.fetch_add(1, Ordering::Relaxed);
100 let (events, receiver) = unbounded_channel();
101 let handle = EmbedHandle {
102 id,
103 requests: self.requests.clone(),
104 waker: self.waker.clone(),
105 };
106 let _ = self.send(UiRequest::OpenEmbed { id, spec, events });
107 (handle, receiver)
108 }
109
86 fn send(&self, request: UiRequest) -> Result<()> {
110 fn send(&self, request: UiRequest) -> Result<()> {
87 self.requests
111 self.requests
88 .send(request)
112 .send(request)