BlueGit

ict rusty-teams

Files

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

cloud_picker.rs

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