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