BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / conversation / shared.rs

shared.rs

shared.rs 23.2 KiB Download Raw
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::notice::short_error;
18use crate::runtime;
19use crate::views::attachment_tray::{display_name, read_attachment};
20use crate::views::channel_tabs::{
21 ChannelPane, TabAction, TabBarActions, fallback_tab_link, header_title_width, render_tab_bar,
22 tab_action,
23};
24use crate::views::shared_tab::{
25 LibraryView, Listing, MessagesView, SharedCommand, SharedRun, SharedScope, render_library,
26 render_messages,
27};
28
29const LIBRARY_KEY: &str = "library";
30const NEW_FOLDER_PLACEHOLDER: &str = "Folder name";
31const ITEM_SCAN_LIMIT: usize = 5000;
32
33pub(super) struct SharedState {
34 scope: SharedScope,
35 filter: MessageFilter,
36 path: Option<LibraryPath>,
37 listing: Listing,
38 generation: u64,
39 new_folder_open: bool,
40 uploads_running: usize,
41 pub(super) items: Vec<SharedItem>,
42 listed_at: Option<Instant>,
43}
44
45impl Default for SharedState {
46 fn default() -> Self {
47 SharedState {
48 scope: SharedScope::Library,
49 filter: MessageFilter::All,
50 path: None,
51 listing: Listing::Loading,
52 generation: 0,
53 new_folder_open: false,
54 uploads_running: 0,
55 items: Vec::new(),
56 listed_at: None,
57 }
58 }
59}
60
61impl ConversationView {
62 fn channel_id(&self) -> Option<String> {
63 match &self.current.as_ref()?.selection {
64 Selection::Channel(channel_id) => Some(channel_id.clone()),
65 Selection::Chat(_) => None,
66 }
67 }
68
69 pub(super) fn shared_active(&self) -> bool {
70 self.pane == ChannelPane::Shared && (self.in_feed() || self.in_chat())
71 }
72
73 pub(super) fn in_chat(&self) -> bool {
74 !self.draft_active
75 && self
76 .current
77 .as_ref()
78 .is_some_and(|current| matches!(current.selection, Selection::Chat(_)))
79 }
80
81 pub(super) fn reset_channel_tabs(&mut self, cx: &mut Context<Self>) {
82 self.pane = ChannelPane::Posts;
83 self.tab_links.clear();
84 self.shared = SharedState {
85 generation: self.shared.generation + 1,
86 ..SharedState::default()
87 };
88 if self.channel_details_open {
89 self.refresh_shared_items(cx);
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 title = self
113 .current
114 .as_ref()
115 .map_or("", |current| current.title.as_str());
116 let row = self.header_width(window) - 2. * super::HEADER_PADDING;
117 let available = if self.tabs_below_title(window) {
118 row
119 } else {
120 row - super::HEADER_LEAD_SIZE - 2. * super::HEADER_GAP - header_title_width(title)
121 };
122 let view = cx.weak_entity();
123 let select = Rc::new(move |pane, cx: &mut App| {
124 view.update(cx, |this, cx| this.select_pane(pane, cx)).ok();
125 });
126 let open = {
127 let view = cx.weak_entity();
128 Rc::new(move |index: usize, _: &mut Window, cx: &mut App| {
129 view.update(cx, |this, cx| this.open_channel_tab(index, cx))
130 .ok();
131 })
132 };
133 Some(render_tab_bar(
134 &self.channel_tabs,
135 self.pane,
136 available,
137 &TabBarActions { select, open },
138 ))
139 }
140
141 fn open_channel_tab(&mut self, index: usize, cx: &mut Context<Self>) {
142 let (Some(tab), Some(channel_id)) =
143 (self.channel_tabs.get(index).cloned(), self.channel_id())
144 else {
145 return;
146 };
147 let resolved = self.tab_links.get(&tab.tab_id).map(String::as_str);
148 match tab_action(&tab, resolved) {
149 TabAction::Browser(url) => cx.open_url(&url),
150 TabAction::ResolveLink => self.resolve_tab_link(tab, channel_id, cx),
151 }
152 }
153
154 fn resolve_tab_link(
155 &mut self,
156 tab: ChannelTabRecord,
157 channel_id: String,
158 cx: &mut Context<Self>,
159 ) {
160 let fallback = fallback_tab_link(&tab, &channel_id);
161 let state = self.app.read(cx);
162 let engine = state.engine.clone().filter(|_| !state.mode.demo);
163 let Some(engine) = engine else {
164 cx.open_url(&fallback);
165 return;
166 };
167 let tab_id = tab.tab_id;
168 let lookup = {
169 let tab_id = tab_id.clone();
170 runtime::spawn(async move { engine.channel_tab_web_url(&channel_id, &tab_id).await })
171 };
172 cx.spawn(async move |this, cx| {
173 let link = lookup.await.ok().and_then(Result::ok).flatten();
174 this.update(cx, |this, cx| {
175 let target = match link {
176 Some(link) => {
177 this.tab_links.insert(tab_id, link.clone());
178 link
179 }
180 None => fallback,
181 };
182 cx.open_url(&target);
183 })
184 .ok();
185 })
186 .detach();
187 }
188
189 pub(super) fn select_pane(&mut self, pane: ChannelPane, cx: &mut Context<Self>) {
190 if self.pane == pane {
191 return;
192 }
193 self.pane = pane;
194 if pane == ChannelPane::Shared {
195 self.refresh_shared_items(cx);
196 if self.in_chat() {
197 self.shared.scope = SharedScope::Messages;
198 } else if self.shared.path.is_none() {
199 self.load_library(cx);
200 }
201 }
202 if pane == ChannelPane::Recap {
203 self.open_recap_pane(cx);
204 }
205 cx.notify();
206 }
207
208 pub(super) fn refresh_shared_items(&mut self, cx: &mut Context<Self>) {
209 let Some(conversation_id) = self.conversation_id() else {
210 return;
211 };
212 let store = self.app.read(cx).store.clone();
213 let records = store
214 .messages(&conversation_id, None, ITEM_SCAN_LIMIT)
215 .unwrap_or_default();
216 self.shared.items = shared_items(&records);
217 }
218
219 fn download_library_entry(
220 &mut self,
221 conversation_id: &str,
222 entry: &DriveEntry,
223 cx: &mut Context<Self>,
224 ) {
225 let source =
226 DownloadSource::Library(library_file(entry, self.shared.listed_at, Instant::now()));
227 self.activate_file(conversation_id, LIBRARY_KEY, file_card(entry), source, cx);
228 }
229
230 fn library_entry(&self, index: usize) -> Option<DriveEntry> {
231 match &self.shared.listing {
232 Listing::Ready(entries) => entries.get(index).cloned(),
233 _ => None,
234 }
235 }
236
237 fn library_download_states(&self) -> Vec<Option<crate::downloads::DownloadState>> {
238 let conversation_id = self.conversation_id().unwrap_or_default();
239 let Listing::Ready(entries) = &self.shared.listing else {
240 return Vec::new();
241 };
242 entries
243 .iter()
244 .map(|entry| {
245 let key = DownloadKey::new(&conversation_id, LIBRARY_KEY, &entry.web_url);
246 self.downloads.state(&key).cloned()
247 })
248 .collect()
249 }
250
251 pub(super) fn item_download_states(&self) -> Vec<Option<crate::downloads::DownloadState>> {
252 let conversation_id = self.conversation_id().unwrap_or_default();
253 self.shared
254 .items
255 .iter()
256 .map(|item| match &item.content {
257 SharedContent::File(card) => {
258 let key = DownloadKey::new(&conversation_id, &item.message_id, &card.open_url);
259 self.downloads.state(&key).cloned()
260 }
261 SharedContent::Link(_) => None,
262 })
263 .collect()
264 }
265
266 pub(super) fn render_shared(&self, cx: &mut Context<Self>) -> AnyElement {
267 let view = cx.weak_entity();
268 let run: SharedRun = Rc::new(move |command, window, cx| {
269 view.update(cx, |this, cx| this.run_shared(command, window, cx))
270 .ok();
271 });
272 match self.shared.scope {
273 SharedScope::Library => {
274 let status = (self.shared.uploads_running > 0)
275 .then(|| format!("Uploading {} ...", self.shared.uploads_running));
276 render_library(
277 LibraryView {
278 path: self.shared.path.as_ref(),
279 listing: &self.shared.listing,
280 new_folder: self
281 .new_folder_input
282 .as_ref()
283 .filter(|_| self.shared.new_folder_open),
284 status: status.as_deref(),
285 download_states: self.library_download_states(),
286 },
287 &run,
288 )
289 }
290 SharedScope::Messages => render_messages(
291 MessagesView {
292 items: &self.shared.items,
293 filter: self.shared.filter,
294 download_states: self.item_download_states(),
295 has_library: !self.in_chat(),
296 },
297 &run,
298 ),
299 }
300 }
301
302 pub(super) fn run_shared(&mut self, command: SharedCommand, window: &mut Window, cx: &mut Context<Self>) {
303 let conversation_id = self.conversation_id().unwrap_or_default();
304 match command {
305 SharedCommand::Scope(scope) => {
306 self.shared.scope = scope;
307 if scope == SharedScope::Messages {
308 self.refresh_shared_items(cx);
309 }
310 cx.notify();
311 }
312 SharedCommand::Filter(filter) => {
313 self.shared.filter = filter;
314 cx.notify();
315 }
316 SharedCommand::Crumb(index) => {
317 if let Some(path) = self.shared.path.as_mut() {
318 path.go_to(index);
319 }
320 self.shared.new_folder_open = false;
321 self.load_library(cx);
322 }
323 SharedCommand::Open(index) => {
324 let Some(entry) = self.library_entry(index) else {
325 return;
326 };
327 if entry.is_folder() {
328 if let Some(path) = self.shared.path.as_mut() {
329 path.enter(&entry);
330 }
331 self.shared.new_folder_open = false;
332 self.load_library(cx);
333 } else {
334 self.download_library_entry(&conversation_id, &entry, cx);
335 }
336 }
337 SharedCommand::OpenInBrowser(index) => {
338 if let Some(entry) = self.library_entry(index) {
339 cx.open_url(&entry.web_url);
340 }
341 }
342 SharedCommand::Download(index) => {
343 if let Some(entry) = self.library_entry(index) {
344 self.download_library_entry(&conversation_id, &entry, cx);
345 }
346 }
347 SharedCommand::CopyLink(index) => {
348 if let Some(entry) = self.library_entry(index) {
349 cx.write_to_clipboard(ClipboardItem::new_string(entry.web_url));
350 self.app.update(cx, |state, cx| {
351 state.raise_notice("Link copied".to_owned(), None, cx)
352 });
353 }
354 }
355 SharedCommand::Retry => self.load_library(cx),
356 SharedCommand::ToggleNewFolder => self.toggle_new_folder(window, cx),
357 SharedCommand::Upload => self.pick_upload(cx),
358 SharedCommand::OpenSharePoint => {
359 if let Some(path) = &self.shared.path {
360 cx.open_url(path.current_web_url());
361 }
362 }
363 SharedCommand::OpenItem(index) => {
364 let Some(item) = self.shared.items.get(index).cloned() else {
365 return;
366 };
367 match item.content {
368 SharedContent::File(card) => self.activate_file(
369 &conversation_id,
370 &item.message_id,
371 card,
372 DownloadSource::Share,
373 cx,
374 ),
375 SharedContent::Link(url) => cx.open_url(&url),
376 }
377 }
378 SharedCommand::JumpToPost(index) => {
379 let Some(message_id) = self
380 .shared
381 .items
382 .get(index)
383 .map(|item| item.message_id.clone())
384 else {
385 return;
386 };
387 self.jump_to_message(&conversation_id, &message_id, cx);
388 }
389 }
390 }
391
392 fn load_library(&mut self, cx: &mut Context<Self>) {
393 let Some(channel_id) = self.channel_id() else {
394 return;
395 };
396 self.shared.generation += 1;
397 let generation = self.shared.generation;
398 self.shared.listing = Listing::Loading;
399 cx.notify();
400 let state = self.app.read(cx);
401 let (demo, engine) = (state.mode.demo, state.engine.clone());
402 let folder = self.shared.path.as_ref().map(|path| path.current().clone());
403 if demo {
404 self.load_demo_library(&channel_id, folder.is_none());
405 return;
406 }
407 let Some(engine) = engine else {
408 self.shared.listing = Listing::Failed("not connected".to_owned());
409 return;
410 };
411 let receiver = runtime::spawn(async move {
412 let (root, target) = match folder {
413 Some(folder) => (None, folder),
414 None => {
415 let root = engine.channel_library_root(&channel_id).await?;
416 let target = root.folder();
417 (Some(root), target)
418 }
419 };
420 let entries = engine.library_children(&target).await?;
421 Ok::<_, teams_core::Error>((root, entries))
422 });
423 cx.spawn(async move |this, cx| {
424 let outcome = match receiver.await {
425 Ok(Ok(loaded)) => Ok(loaded),
426 Ok(Err(error)) => Err(short_error(&error)),
427 Err(error) => Err(short_error(&error)),
428 };
429 this.update(cx, |this, cx| {
430 this.finish_library_load(generation, outcome, cx)
431 })
432 .ok();
433 })
434 .detach();
435 }
436
437 fn finish_library_load(
438 &mut self,
439 generation: u64,
440 outcome: Result<(Option<DriveEntry>, Vec<DriveEntry>), String>,
441 cx: &mut Context<Self>,
442 ) {
443 if generation != self.shared.generation {
444 return;
445 }
446 match outcome {
447 Ok((root, entries)) => {
448 if let Some(root) = root {
449 self.shared.path = Some(LibraryPath::new(Crumb {
450 name: root.name.clone(),
451 folder: root.folder(),
452 web_url: root.web_url,
453 }));
454 }
455 self.shared.listing = Listing::Ready(sorted_entries(entries));
456 self.shared.listed_at = Some(Instant::now());
457 }
458 Err(reason) => self.shared.listing = Listing::Failed(reason),
459 }
460 cx.notify();
461 }
462
463 fn load_demo_library(&mut self, channel_id: &str, at_root: bool) {
464 if at_root {
465 let name = self
466 .current
467 .as_ref()
468 .map(|current| current.title.clone())
469 .unwrap_or_default();
470 let root = self.demo_library.root(channel_id, &name);
471 self.shared.path = Some(LibraryPath::new(Crumb {
472 name: root.name.clone(),
473 folder: root.folder(),
474 web_url: root.web_url,
475 }));
476 }
477 let Some(path) = &self.shared.path else {
478 return;
479 };
480 let entries = self.demo_library.children(&path.current().item_id);
481 self.shared.listing = Listing::Ready(sorted_entries(entries));
482 }
483
484 fn toggle_new_folder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
485 if self.shared.new_folder_open {
486 self.shared.new_folder_open = false;
487 cx.notify();
488 return;
489 }
490 let input = match &self.new_folder_input {
491 Some(input) => input.clone(),
492 None => {
493 let input =
494 cx.new(|cx| InputState::new(window, cx).placeholder(NEW_FOLDER_PLACEHOLDER));
495 let subscription = cx.subscribe_in(&input, window, Self::on_new_folder_event);
496 self._subscriptions.push(subscription);
497 self.new_folder_input = Some(input.clone());
498 input
499 }
500 };
501 input.update(cx, |input, cx| {
502 input.set_value("", window, cx);
503 input.focus(window, cx);
504 });
505 self.shared.new_folder_open = true;
506 cx.notify();
507 }
508
509 fn on_new_folder_event(
510 &mut self,
511 _: &Entity<InputState>,
512 event: &InputEvent,
513 _: &mut Window,
514 cx: &mut Context<Self>,
515 ) {
516 if matches!(event, InputEvent::PressEnter { .. }) {
517 self.create_folder(cx);
518 }
519 }
520
521 pub(super) fn close_new_folder(&mut self, cx: &mut Context<Self>) -> bool {
522 if !self.shared.new_folder_open {
523 return false;
524 }
525 self.shared.new_folder_open = false;
526 cx.notify();
527 true
528 }
529
530 fn create_folder(&mut self, cx: &mut Context<Self>) {
531 let Some(input) = self.new_folder_input.clone() else {
532 return;
533 };
534 let name = input.read(cx).value().trim().to_owned();
535 let Some(parent) = self.shared.path.as_ref().map(|path| path.current().clone()) else {
536 return;
537 };
538 if name.is_empty() {
539 return;
540 }
541 self.shared.new_folder_open = false;
542 let state = self.app.read(cx);
543 let (demo, engine) = (state.mode.demo, state.engine.clone());
544 if demo {
545 self.demo_library.create_folder(&parent.item_id, &name);
546 self.load_library(cx);
547 return;
548 }
549 let Some(engine) = engine else {
550 return;
551 };
552 let target = parent.clone();
553 let receiver =
554 runtime::spawn(async move { engine.create_library_folder(&target, &name).await });
555 cx.spawn(async move |this, cx| {
556 let outcome = match receiver.await {
557 Ok(Ok(_)) => Ok(()),
558 Ok(Err(error)) => Err(short_error(&error)),
559 Err(error) => Err(short_error(&error)),
560 };
561 this.update(cx, |this, cx| {
562 this.finish_change(&parent, outcome, "Folder not created", cx)
563 })
564 .ok();
565 })
566 .detach();
567 }
568
569 fn finish_change(
570 &mut self,
571 folder: &DriveFolder,
572 outcome: Result<(), String>,
573 failure: &str,
574 cx: &mut Context<Self>,
575 ) {
576 if let Err(reason) = outcome {
577 self.notice = Some(format!("{failure}: {reason}"));
578 }
579 let still_open = self
580 .shared
581 .path
582 .as_ref()
583 .is_some_and(|path| path.current() == folder);
584 if still_open {
585 self.load_library(cx);
586 } else {
587 cx.notify();
588 }
589 }
590
591 fn pick_upload(&mut self, cx: &mut Context<Self>) {
592 let receiver = cx.prompt_for_paths(PathPromptOptions {
593 files: true,
594 directories: false,
595 multiple: true,
596 prompt: None,
597 });
598 cx.spawn(async move |this, cx| {
599 if let Ok(Ok(Some(paths))) = receiver.await {
600 this.update(cx, |this, cx| this.upload_paths(paths, cx))
601 .ok();
602 }
603 })
604 .detach();
605 }
606
607 pub(super) fn upload_paths(&mut self, paths: Vec<PathBuf>, cx: &mut Context<Self>) {
608 let Some(folder) = self.shared.path.as_ref().map(|path| path.current().clone()) else {
609 return;
610 };
611 let state = self.app.read(cx);
612 let (demo, engine) = (state.mode.demo, state.engine.clone());
613 for path in paths {
614 self.shared.uploads_running += 1;
615 let (folder, engine) = (folder.clone(), engine.clone());
616 cx.spawn(async move |this, cx| {
617 let name = display_name(&path);
618 let loaded = cx
619 .background_executor()
620 .spawn(async move { read_attachment(&path) })
621 .await;
622 let outcome = match loaded {
623 Err(reason) => Err(reason),
624 Ok(file) if demo => {
625 let size = file.bytes.len() as u64;
626 let (folder_id, file_name) = (folder.item_id.clone(), name.clone());
627 this.update(cx, |this, _| {
628 this.demo_library.add_file(&folder_id, &file_name, size);
629 })
630 .ok();
631 Ok(())
632 }
633 Ok(file) => match engine {
634 None => Err("not connected".to_owned()),
635 Some(engine) => {
636 let (target, file_name) = (folder.clone(), name.clone());
637 let receiver = runtime::spawn(async move {
638 engine
639 .upload_to_library(&target, &file_name, &file.bytes, |_| {})
640 .await
641 });
642 match receiver.await {
643 Ok(Ok(_)) => Ok(()),
644 Ok(Err(error)) => Err(short_error(&error)),
645 Err(error) => Err(short_error(&error)),
646 }
647 }
648 },
649 };
650 this.update(cx, |this, cx| {
651 this.shared.uploads_running = this.shared.uploads_running.saturating_sub(1);
652 let failure = format!("{name} not uploaded");
653 if this.shared.uploads_running == 0 || outcome.is_err() {
654 this.finish_change(&folder, outcome, &failure, cx);
655 } else {
656 cx.notify();
657 }
658 })
659 .ok();
660 })
661 .detach();
662 }
663 cx.notify();
664 }
665}