BlueGit

ict rusty-teams

Files

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

shared.rs

shared.rs 24.3 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::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}