BlueGit

ict rusty-teams

Files

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

shared.rs

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