BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / composer / cloud_picker.rs

cloud_picker.rs

cloud_picker.rs 22.9 KiB Download Raw
1use chrono::{DateTime, Utc};
2use gpui_kit::component::button::{Button, ButtonVariants as _};
3use gpui_kit::component::checkbox::Checkbox;
4use gpui_kit::component::scroll::ScrollableElement as _;
5use gpui_kit::component::{Disableable as _, h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8use teams_core::{CloudFile, DriveEntry, DriveFolder, QuickSite};
9
10use crate::app_state::AppState;
11use crate::i18n::tr;
12use crate::runtime;
13use crate::theme::{self, ElevatedSurface as _};
14use crate::views::shared_tab::{entry_badge, modified_text};
15use crate::views::widgets::symbol;
16
17pub const CLOUD_PICKER_TAG: &str = "composer/cloud-picker";
18pub const ATTACH_CLOUD_LABEL: &str = "Attach cloud files";
19const PANEL_WIDTH: f32 = 1052.;
20const PANEL_HEIGHT: f32 = 742.;
21const PANEL_MARGIN: f32 = 32.;
22const NAV_WIDTH: f32 = 210.;
23const NAV_ROW_HEIGHT: f32 = 32.;
24const ROW_HEIGHT: f32 = 48.;
25const WHEN_WIDTH: f32 = 150.;
26const WHO_WIDTH: f32 = 170.;
27const CHECK_WIDTH: f32 = 32.;
28const PADDING: f32 = 24.;
29const BACKDROP_OPACITY: f32 = 0.55;
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32enum Place {
33 Home,
34 MyFiles,
35 Shared,
36 Site(usize),
37}
38
39impl Place {
40 fn columns(self) -> [&'static str; 3] {
41 match self {
42 Place::Home => ["Name", "Opened", "Owner"],
43 Place::Shared => ["Name", "Date shared", "Shared by"],
44 Place::MyFiles | Place::Site(_) => ["Name", "Modified", "Modified By"],
45 }
46 }
47}
48
49struct Crumb {
50 name: String,
51 folder: DriveFolder,
52}
53
54enum Rows {
55 Loading,
56 Failed,
57 Ready(Vec<DriveEntry>),
58}
59
60pub enum CloudPickerEvent {
61 Attach(Vec<CloudFile>),
62 Close,
63}
64
65pub struct CloudPicker {
66 app: Entity<AppState>,
67 place: Place,
68 sites: Vec<QuickSite>,
69 crumbs: Vec<Crumb>,
70 rows: Rows,
71 selected: Vec<DriveEntry>,
72 generation: u64,
73 focus_handle: FocusHandle,
74}
75
76impl EventEmitter<CloudPickerEvent> for CloudPicker {}
77
78impl Focusable for CloudPicker {
79 fn focus_handle(&self, _: &App) -> FocusHandle {
80 self.focus_handle.clone()
81 }
82}
83
84fn recent_row((file, owner): (CloudFile, Option<String>)) -> Option<DriveEntry> {
85 Some(DriveEntry {
86 drive_id: file.drive_id?,
87 id: file.item_id?,
88 name: file.name,
89 web_url: file.web_url,
90 size: file.size,
91 modified_at: file.last_opened,
92 modified_by: owner,
93 child_count: None,
94 download_url: None,
95 })
96}
97
98fn demo_rows() -> Vec<DriveEntry> {
99 let now = Utc::now();
100 ["Q4 planning.pptx", "Budget 2027.xlsx", "Release notes.docx"]
101 .iter()
102 .enumerate()
103 .map(|(index, name)| DriveEntry {
104 drive_id: "demo-drive".into(),
105 id: format!("demo-{index}"),
106 name: (*name).into(),
107 web_url: format!("https://example.com/demo/{index}"),
108 size: 20_000,
109 modified_at: Some(now - chrono::Duration::hours(3 * index as i64 + 1)),
110 modified_by: Some("Megan Bowen".into()),
111 child_count: None,
112 download_url: None,
113 })
114 .collect()
115}
116
117pub fn opened_ago(time: DateTime<Utc>, now: DateTime<Utc>) -> Option<String> {
118 let minutes = (now - time).num_minutes().max(0);
119 match minutes {
120 0 => Some("Just now".into()),
121 1..60 => Some(format!("{minutes}m ago")),
122 60..1440 => Some(format!("{}h ago", minutes / 60)),
123 _ => None,
124 }
125}
126
127impl CloudPicker {
128 pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {
129 let mut picker = CloudPicker {
130 app,
131 place: Place::Home,
132 sites: Vec::new(),
133 crumbs: Vec::new(),
134 rows: Rows::Loading,
135 selected: Vec::new(),
136 generation: 0,
137 focus_handle: cx.focus_handle(),
138 };
139 picker.load_sites(cx);
140 picker.open_place(Place::Home, cx);
141 picker
142 }
143
144 fn load_sites(&mut self, cx: &mut Context<Self>) {
145 let Some(engine) = self.app.read(cx).engine.clone() else {
146 return;
147 };
148 let receiver = runtime::spawn(async move { engine.picker_sites().await });
149 cx.spawn(async move |this, cx| {
150 if let Ok(Ok(sites)) = receiver.await {
151 this.update(cx, |this, cx| {
152 this.sites = sites;
153 cx.notify();
154 })
155 .ok();
156 }
157 })
158 .detach();
159 }
160
161 fn open_place(&mut self, place: Place, cx: &mut Context<Self>) {
162 self.place = place;
163 self.crumbs.clear();
164 self.generation += 1;
165 let generation = self.generation;
166 self.rows = Rows::Loading;
167 cx.notify();
168 if self.app.read(cx).mode.demo {
169 self.rows = Rows::Ready(if place == Place::Home {
170 demo_rows()
171 } else {
172 Vec::new()
173 });
174 return;
175 }
176 let Some(engine) = self.app.read(cx).engine.clone() else {
177 self.rows = Rows::Failed;
178 return;
179 };
180 let site = match place {
181 Place::Site(index) => self.sites.get(index).map(|site| site.id.clone()),
182 _ => None,
183 };
184 let receiver = runtime::spawn(async move {
185 match place {
186 Place::Home => Ok((
187 None,
188 engine
189 .picker_recent()
190 .await?
191 .into_iter()
192 .filter_map(recent_row)
193 .collect(),
194 )),
195 Place::Shared => Ok((None, engine.picker_shared().await?)),
196 Place::MyFiles | Place::Site(_) => {
197 let root = engine.picker_root(site.as_deref()).await?;
198 let entries = engine.picker_folder(&root).await?;
199 Ok((Some(root), entries))
200 }
201 }
202 });
203 cx.spawn(async move |this, cx| {
204 let result: Option<teams_core::Result<(Option<DriveFolder>, Vec<DriveEntry>)>> =
205 receiver.await.ok();
206 this.update(cx, |this, cx| {
207 if this.generation != generation {
208 return;
209 }
210 match result {
211 Some(Ok((root, entries))) => {
212 if let Some(folder) = root {
213 this.crumbs.push(Crumb {
214 name: this.root_name(),
215 folder,
216 });
217 }
218 this.rows = Rows::Ready(entries);
219 }
220 _ => this.rows = Rows::Failed,
221 }
222 cx.notify();
223 })
224 .ok();
225 })
226 .detach();
227 }
228
229 fn root_name(&self) -> String {
230 match self.place {
231 Place::Site(_) => "Documents".into(),
232 _ => "My files".into(),
233 }
234 }
235
236 fn open_folder(&mut self, name: String, folder: DriveFolder, cx: &mut Context<Self>) {
237 self.crumbs.push(Crumb {
238 name,
239 folder: folder.clone(),
240 });
241 self.list_folder(folder, cx);
242 }
243
244 fn back_to(&mut self, depth: usize, cx: &mut Context<Self>) {
245 self.crumbs.truncate(depth + 1);
246 if let Some(crumb) = self.crumbs.last() {
247 let folder = crumb.folder.clone();
248 self.list_folder(folder, cx);
249 }
250 }
251
252 fn list_folder(&mut self, folder: DriveFolder, cx: &mut Context<Self>) {
253 self.generation += 1;
254 let generation = self.generation;
255 self.rows = Rows::Loading;
256 cx.notify();
257 let Some(engine) = self.app.read(cx).engine.clone() else {
258 self.rows = Rows::Failed;
259 return;
260 };
261 let receiver = runtime::spawn(async move { engine.picker_folder(&folder).await });
262 cx.spawn(async move |this, cx| {
263 let result = receiver.await;
264 this.update(cx, |this, cx| {
265 if this.generation == generation {
266 this.rows = match result {
267 Ok(Ok(entries)) => Rows::Ready(entries),
268 _ => Rows::Failed,
269 };
270 cx.notify();
271 }
272 })
273 .ok();
274 })
275 .detach();
276 }
277
278 fn click_row(&mut self, entry: DriveEntry, cx: &mut Context<Self>) {
279 if entry.is_folder() {
280 self.open_folder(entry.name.clone(), entry.folder(), cx);
281 return;
282 }
283 match self
284 .selected
285 .iter()
286 .position(|picked| picked.id == entry.id)
287 {
288 Some(index) => {
289 self.selected.remove(index);
290 }
291 None => self.selected.push(entry),
292 }
293 cx.notify();
294 }
295
296 fn attach(&mut self, cx: &mut Context<Self>) {
297 let files = self
298 .selected
299 .iter()
300 .map(CloudFile::from)
301 .collect::<Vec<_>>();
302 if !files.is_empty() {
303 cx.emit(CloudPickerEvent::Attach(files));
304 }
305 }
306
307 fn title(&self) -> String {
308 match self.place {
309 Place::Home => "Home".into(),
310 Place::Shared => "Shared with you".into(),
311 Place::MyFiles | Place::Site(_) => self
312 .crumbs
313 .last()
314 .map_or_else(|| self.root_name(), |crumb| crumb.name.clone()),
315 }
316 }
317
318 fn nav_row(
319 &self,
320 id: impl Into<ElementId>,
321 glyph: &'static str,
322 label: String,
323 place: Place,
324 cx: &mut Context<Self>,
325 ) -> Stateful<Div> {
326 let active = self.place == place;
327 h_flex()
328 .id(id)
329 .h(px(NAV_ROW_HEIGHT))
330 .flex_none()
331 .px(px(10.))
332 .gap(px(10.))
333 .items_center()
334 .rounded(px(6.))
335 .cursor_pointer()
336 .text_size(px(13.))
337 .text_color(if active {
338 theme::text_strong()
339 } else {
340 theme::text()
341 })
342 .when(active, |row| {
343 row.bg(theme::selection()).font_weight(FontWeight::SEMIBOLD)
344 })
345 .hover(|row| row.bg(theme::row_hover()))
346 .child(symbol(
347 glyph,
348 18.,
349 if active {
350 theme::accent_text()
351 } else {
352 theme::text_soft()
353 },
354 ))
355 .child(div().flex_1().min_w_0().truncate().child(label))
356 .on_click(cx.listener(move |this, _, _, cx| this.open_place(place, cx)))
357 }
358
359 fn navigation(&self, cx: &mut Context<Self>) -> Div {
360 let section = |label: &'static str| {
361 div()
362 .pt(px(20.))
363 .pb(px(6.))
364 .px(px(10.))
365 .text_size(px(13.))
366 .font_weight(FontWeight::SEMIBOLD)
367 .text_color(theme::text())
368 .child(label)
369 };
370 let mut sites = Vec::with_capacity(self.sites.len());
371 for (index, site) in self.sites.iter().enumerate() {
372 sites.push(self.nav_row(
373 ("cloud-picker-site", index),
374 "domain",
375 site.name.clone(),
376 Place::Site(index),
377 cx,
378 ));
379 }
380 v_flex()
381 .w(px(NAV_WIDTH))
382 .flex_none()
383 .h_full()
384 .px(px(8.))
385 .py(px(PADDING))
386 .child(
387 div()
388 .px(px(10.))
389 .pb(px(16.))
390 .text_size(px(20.))
391 .font_weight(FontWeight::SEMIBOLD)
392 .text_color(theme::text_strong())
393 .child("OneDrive"),
394 )
395 .child(self.nav_row("cloud-picker-home", "home", "Home".into(), Place::Home, cx))
396 .child(self.nav_row(
397 "cloud-picker-mine",
398 "folder",
399 "My files".into(),
400 Place::MyFiles,
401 cx,
402 ))
403 .child(self.nav_row(
404 "cloud-picker-shared",
405 "group",
406 "Shared".into(),
407 Place::Shared,
408 cx,
409 ))
410 .when(!self.sites.is_empty(), |nav| {
411 nav.child(section("Quick access")).child(
412 v_flex()
413 .id("cloud-picker-sites")
414 .flex_1()
415 .min_h_0()
416 .overflow_y_scrollbar()
417 .children(sites),
418 )
419 })
420 }
421
422 fn breadcrumb(&self, cx: &mut Context<Self>) -> Div {
423 let last = self.crumbs.len().saturating_sub(1);
424 let mut trail = h_flex().gap(px(4.)).items_center().min_w_0();
425 for (depth, crumb) in self.crumbs.iter().enumerate() {
426 if depth > 0 {
427 trail = trail.child(symbol("chevron_right", 16., theme::text_soft()));
428 }
429 let current = depth == last;
430 trail = trail.child(
431 div()
432 .id(("cloud-picker-crumb", depth))
433 .truncate()
434 .text_size(px(if current { 20. } else { 14. }))
435 .font_weight(if current {
436 FontWeight::SEMIBOLD
437 } else {
438 FontWeight::NORMAL
439 })
440 .text_color(if current {
441 theme::text_strong()
442 } else {
443 theme::text_soft()
444 })
445 .when(!current, |crumb| {
446 crumb
447 .cursor_pointer()
448 .hover(|crumb| crumb.text_color(theme::text()))
449 .on_click(cx.listener(move |this, _, _, cx| this.back_to(depth, cx)))
450 })
451 .child(crumb.name.clone()),
452 );
453 }
454 trail
455 }
456
457 fn header(&self, cx: &mut Context<Self>) -> Div {
458 let site = match self.place {
459 Place::Site(index) => self.sites.get(index).map(|site| site.name.clone()),
460 _ => None,
461 };
462 let title = if self.crumbs.len() > 1 {
463 self.breadcrumb(cx)
464 } else {
465 h_flex().child(
466 div()
467 .text_size(px(20.))
468 .font_weight(FontWeight::SEMIBOLD)
469 .text_color(theme::text_strong())
470 .child(self.title()),
471 )
472 };
473 v_flex()
474 .gap(px(2.))
475 .children(site.map(|name| {
476 div()
477 .text_size(px(13.))
478 .text_color(theme::text_soft())
479 .child(name)
480 }))
481 .child(title)
482 }
483
484 fn column_header(&self) -> Div {
485 let [name, when, who] = self.place.columns();
486 h_flex()
487 .h(px(40.))
488 .flex_none()
489 .px(px(12.))
490 .gap(px(12.))
491 .items_center()
492 .border_b_1()
493 .border_color(theme::border())
494 .text_size(px(12.5))
495 .font_weight(FontWeight::SEMIBOLD)
496 .text_color(theme::text_soft())
497 .child(div().w(px(CHECK_WIDTH)).flex_none())
498 .child(div().flex_1().min_w_0().child(name))
499 .child(div().w(px(WHEN_WIDTH)).flex_none().child(when))
500 .child(div().w(px(WHO_WIDTH)).flex_none().child(who))
501 }
502
503 fn when_text(&self, entry: &DriveEntry, now: DateTime<Utc>) -> String {
504 match (self.place, entry.modified_at) {
505 (Place::Home, Some(opened)) => {
506 opened_ago(opened, now).unwrap_or_else(|| modified_text(entry))
507 }
508 _ => modified_text(entry),
509 }
510 }
511
512 fn row(
513 &self,
514 index: usize,
515 entry: &DriveEntry,
516 now: DateTime<Utc>,
517 cx: &mut Context<Self>,
518 ) -> Stateful<Div> {
519 let picked = self.selected.iter().any(|selected| selected.id == entry.id);
520 let folder = entry.is_folder();
521 let clicked = entry.clone();
522 h_flex()
523 .id(("cloud-picker-row", index))
524 .h(px(ROW_HEIGHT))
525 .flex_none()
526 .px(px(12.))
527 .gap(px(12.))
528 .items_center()
529 .border_b_1()
530 .border_color(theme::border())
531 .cursor_pointer()
532 .text_size(px(13.))
533 .text_color(theme::text_soft())
534 .when(picked, |row| row.bg(theme::selection()))
535 .hover(|row| row.bg(theme::row_hover()))
536 .child(div().w(px(CHECK_WIDTH)).flex_none().when(!folder, |cell| {
537 cell.child(Checkbox::new(("cloud-picker-check", index)).checked(picked))
538 }))
539 .child(
540 h_flex()
541 .flex_1()
542 .min_w_0()
543 .gap(px(10.))
544 .items_center()
545 .child(entry_badge(entry))
546 .child(
547 div()
548 .truncate()
549 .text_color(theme::text())
550 .child(entry.name.clone()),
551 ),
552 )
553 .child(
554 div()
555 .w(px(WHEN_WIDTH))
556 .flex_none()
557 .truncate()
558 .child(self.when_text(entry, now)),
559 )
560 .child(
561 div()
562 .w(px(WHO_WIDTH))
563 .flex_none()
564 .truncate()
565 .child(entry.modified_by.clone().unwrap_or_default()),
566 )
567 .on_click(cx.listener(move |this, _, _, cx| this.click_row(clicked.clone(), cx)))
568 }
569
570 fn table(&self, cx: &mut Context<Self>) -> AnyElement {
571 let note = |text: &'static str| {
572 div()
573 .p(px(16.))
574 .text_size(px(13.))
575 .text_color(theme::text_soft())
576 .child(text)
577 .into_any_element()
578 };
579 let now = Utc::now();
580 let body: Vec<AnyElement> = match &self.rows {
581 Rows::Loading => vec![note("Loading ...")],
582 Rows::Failed => vec![note("Couldn't load files.")],
583 Rows::Ready(entries) if entries.is_empty() => vec![note("This folder is empty.")],
584 Rows::Ready(entries) => entries
585 .iter()
586 .enumerate()
587 .map(|(index, entry)| self.row(index, entry, now, cx).into_any_element())
588 .collect(),
589 };
590 v_flex()
591 .flex_1()
592 .min_h_0()
593 .rounded(px(10.))
594 .bg(theme::surface_raised())
595 .overflow_hidden()
596 .child(self.column_header())
597 .child(
598 v_flex()
599 .id("cloud-picker-rows")
600 .flex_1()
601 .min_h_0()
602 .overflow_y_scrollbar()
603 .children(body),
604 )
605 .into_any_element()
606 }
607}
608
609impl Render for CloudPicker {
610 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
611 let viewport = window.viewport_size();
612 let width = px(PANEL_WIDTH).min(viewport.width - px(2. * PANEL_MARGIN));
613 let height = px(PANEL_HEIGHT).min(viewport.height - px(2. * PANEL_MARGIN));
614 let can_attach = !self.selected.is_empty();
615 let panel = h_flex()
616 .id(CLOUD_PICKER_TAG)
617 .debug_selector(|| CLOUD_PICKER_TAG.into())
618 .w(width)
619 .h(height)
620 .rounded(px(12.))
621 .dialog_surface()
622 .text_color(theme::text())
623 .occlude()
624 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
625 .child(self.navigation(cx))
626 .child(
627 v_flex()
628 .flex_1()
629 .min_w_0()
630 .h_full()
631 .p(px(PADDING))
632 .gap(px(16.))
633 .child(self.header(cx))
634 .child(self.table(cx))
635 .child(
636 h_flex()
637 .justify_end()
638 .gap(px(8.))
639 .child(
640 Button::new("cloud-picker-attach")
641 .primary()
642 .label(tr("common.attach"))
643 .disabled(!can_attach)
644 .on_click(cx.listener(|this, _, _, cx| this.attach(cx))),
645 )
646 .child(
647 Button::new("cloud-picker-cancel")
648 .label(tr("common.cancel"))
649 .on_click(
650 cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)),
651 ),
652 ),
653 ),
654 );
655 deferred(
656 anchored().position(point(px(0.), px(0.))).child(
657 div()
658 .id("cloud-picker-backdrop")
659 .track_focus(&self.focus_handle)
660 .w(viewport.width)
661 .h(viewport.height)
662 .flex()
663 .items_center()
664 .justify_center()
665 .bg(black().opacity(BACKDROP_OPACITY))
666 .occlude()
667 .on_key_down(cx.listener(|_, event: &KeyDownEvent, _, cx| {
668 if event.keystroke.key == "escape" {
669 cx.emit(CloudPickerEvent::Close);
670 }
671 }))
672 .on_mouse_down(
673 MouseButton::Left,
674 cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)),
675 )
676 .child(panel),
677 ),
678 )
679 .with_priority(3)
680 }
681}
682
683#[cfg(test)]
684mod tests {
685 use chrono::{TimeZone as _, Utc};
686
687 use super::{Place, opened_ago};
688
689 #[test]
690 fn home_shows_hours_ago_like_the_onedrive_picker() {
691 let now = Utc.with_ymd_and_hms(2026, 11, 10, 22, 0, 0).unwrap();
692 assert_eq!(
693 opened_ago(now - chrono::Duration::hours(9), now).as_deref(),
694 Some("9h ago")
695 );
696 assert_eq!(
697 opened_ago(now - chrono::Duration::minutes(5), now).as_deref(),
698 Some("5m ago")
699 );
700 assert_eq!(opened_ago(now - chrono::Duration::days(3), now), None);
701 }
702
703 #[test]
704 fn each_place_has_the_picker_columns() {
705 assert_eq!(Place::Home.columns(), ["Name", "Opened", "Owner"]);
706 assert_eq!(
707 Place::Shared.columns(),
708 ["Name", "Date shared", "Shared by"]
709 );
710 assert_eq!(
711 Place::Site(0).columns(),
712 ["Name", "Modified", "Modified By"]
713 );
714 }
715}