BlueGit

ict rusty-teams

Files

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

cloud_picker.rs

cloud_picker.rs 20.3 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 { demo_rows() } else { Vec::new() });
169 return;
170 }
171 let Some(engine) = self.app.read(cx).engine.clone() else {
172 self.rows = Rows::Failed;
173 return;
174 };
175 let site = match place {
176 Place::Site(index) => self.sites.get(index).map(|site| site.id.clone()),
177 _ => None,
178 };
179 let receiver = runtime::spawn(async move {
180 match place {
181 Place::Home => Ok((None, engine.picker_recent().await?.into_iter().filter_map(recent_row).collect())),
182 Place::Shared => Ok((None, engine.picker_shared().await?)),
183 Place::MyFiles | Place::Site(_) => {
184 let root = engine.picker_root(site.as_deref()).await?;
185 let entries = engine.picker_folder(&root).await?;
186 Ok((Some(root), entries))
187 }
188 }
189 });
190 cx.spawn(async move |this, cx| {
191 let result: Option<teams_core::Result<(Option<DriveFolder>, Vec<DriveEntry>)>> = receiver.await.ok();
192 this.update(cx, |this, cx| {
193 if this.generation != generation {
194 return;
195 }
196 match result {
197 Some(Ok((root, entries))) => {
198 if let Some(folder) = root {
199 this.crumbs.push(Crumb { name: this.root_name(), folder });
200 }
201 this.rows = Rows::Ready(entries);
202 }
203 _ => this.rows = Rows::Failed,
204 }
205 cx.notify();
206 })
207 .ok();
208 })
209 .detach();
210 }
211
212 fn root_name(&self) -> String {
213 match self.place {
214 Place::Site(_) => "Documents".into(),
215 _ => "My files".into(),
216 }
217 }
218
219 fn open_folder(&mut self, name: String, folder: DriveFolder, cx: &mut Context<Self>) {
220 self.crumbs.push(Crumb { name, folder: folder.clone() });
221 self.list_folder(folder, cx);
222 }
223
224 fn back_to(&mut self, depth: usize, cx: &mut Context<Self>) {
225 self.crumbs.truncate(depth + 1);
226 if let Some(crumb) = self.crumbs.last() {
227 let folder = crumb.folder.clone();
228 self.list_folder(folder, cx);
229 }
230 }
231
232 fn list_folder(&mut self, folder: DriveFolder, cx: &mut Context<Self>) {
233 self.generation += 1;
234 let generation = self.generation;
235 self.rows = Rows::Loading;
236 cx.notify();
237 let Some(engine) = self.app.read(cx).engine.clone() else {
238 self.rows = Rows::Failed;
239 return;
240 };
241 let receiver = runtime::spawn(async move { engine.picker_folder(&folder).await });
242 cx.spawn(async move |this, cx| {
243 let result = receiver.await;
244 this.update(cx, |this, cx| {
245 if this.generation == generation {
246 this.rows = match result {
247 Ok(Ok(entries)) => Rows::Ready(entries),
248 _ => Rows::Failed,
249 };
250 cx.notify();
251 }
252 })
253 .ok();
254 })
255 .detach();
256 }
257
258 fn click_row(&mut self, entry: DriveEntry, cx: &mut Context<Self>) {
259 if entry.is_folder() {
260 self.open_folder(entry.name.clone(), entry.folder(), cx);
261 return;
262 }
263 match self.selected.iter().position(|picked| picked.id == entry.id) {
264 Some(index) => {
265 self.selected.remove(index);
266 }
267 None => self.selected.push(entry),
268 }
269 cx.notify();
270 }
271
272 fn attach(&mut self, cx: &mut Context<Self>) {
273 let files = self.selected.iter().map(CloudFile::from).collect::<Vec<_>>();
274 if !files.is_empty() {
275 cx.emit(CloudPickerEvent::Attach(files));
276 }
277 }
278
279 fn title(&self) -> String {
280 match self.place {
281 Place::Home => "Home".into(),
282 Place::Shared => "Shared with you".into(),
283 Place::MyFiles | Place::Site(_) => self.crumbs.last().map_or_else(|| self.root_name(), |crumb| crumb.name.clone()),
284 }
285 }
286
287 fn nav_row(&self, id: impl Into<ElementId>, glyph: &'static str, label: String, place: Place, cx: &mut Context<Self>) -> Stateful<Div> {
288 let active = self.place == place;
289 h_flex()
290 .id(id)
291 .h(px(NAV_ROW_HEIGHT))
292 .flex_none()
293 .px(px(10.))
294 .gap(px(10.))
295 .items_center()
296 .rounded(px(6.))
297 .cursor_pointer()
298 .text_size(px(13.))
299 .text_color(if active { theme::text_strong() } else { theme::text() })
300 .when(active, |row| row.bg(theme::selection()).font_weight(FontWeight::SEMIBOLD))
301 .hover(|row| row.bg(theme::row_hover()))
302 .child(symbol(glyph, 18., if active { theme::accent_text() } else { theme::text_soft() }))
303 .child(div().flex_1().min_w_0().truncate().child(label))
304 .on_click(cx.listener(move |this, _, _, cx| this.open_place(place, cx)))
305 }
306
307 fn navigation(&self, cx: &mut Context<Self>) -> Div {
308 let section = |label: &'static str| {
309 div()
310 .pt(px(20.))
311 .pb(px(6.))
312 .px(px(10.))
313 .text_size(px(13.))
314 .font_weight(FontWeight::SEMIBOLD)
315 .text_color(theme::text())
316 .child(label)
317 };
318 let mut sites = Vec::with_capacity(self.sites.len());
319 for (index, site) in self.sites.iter().enumerate() {
320 sites.push(self.nav_row(("cloud-picker-site", index), "domain", site.name.clone(), Place::Site(index), cx));
321 }
322 v_flex()
323 .w(px(NAV_WIDTH))
324 .flex_none()
325 .h_full()
326 .px(px(8.))
327 .py(px(PADDING))
328 .child(
329 div()
330 .px(px(10.))
331 .pb(px(16.))
332 .text_size(px(20.))
333 .font_weight(FontWeight::SEMIBOLD)
334 .text_color(theme::text_strong())
335 .child("OneDrive"),
336 )
337 .child(self.nav_row("cloud-picker-home", "home", "Home".into(), Place::Home, cx))
338 .child(self.nav_row("cloud-picker-mine", "folder", "My files".into(), Place::MyFiles, cx))
339 .child(self.nav_row("cloud-picker-shared", "group", "Shared".into(), Place::Shared, cx))
340 .when(!self.sites.is_empty(), |nav| {
341 nav.child(section("Quick access"))
342 .child(v_flex().id("cloud-picker-sites").flex_1().min_h_0().overflow_y_scrollbar().children(sites))
343 })
344 }
345
346 fn breadcrumb(&self, cx: &mut Context<Self>) -> Div {
347 let last = self.crumbs.len().saturating_sub(1);
348 let mut trail = h_flex().gap(px(4.)).items_center().min_w_0();
349 for (depth, crumb) in self.crumbs.iter().enumerate() {
350 if depth > 0 {
351 trail = trail.child(symbol("chevron_right", 16., theme::text_soft()));
352 }
353 let current = depth == last;
354 trail = trail.child(
355 div()
356 .id(("cloud-picker-crumb", depth))
357 .truncate()
358 .text_size(px(if current { 20. } else { 14. }))
359 .font_weight(if current { FontWeight::SEMIBOLD } else { FontWeight::NORMAL })
360 .text_color(if current { theme::text_strong() } else { theme::text_soft() })
361 .when(!current, |crumb| {
362 crumb.cursor_pointer().hover(|crumb| crumb.text_color(theme::text())).on_click(cx.listener(move |this, _, _, cx| this.back_to(depth, cx)))
363 })
364 .child(crumb.name.clone()),
365 );
366 }
367 trail
368 }
369
370 fn header(&self, cx: &mut Context<Self>) -> Div {
371 let site = match self.place {
372 Place::Site(index) => self.sites.get(index).map(|site| site.name.clone()),
373 _ => None,
374 };
375 let title = if self.crumbs.len() > 1 {
376 self.breadcrumb(cx)
377 } else {
378 h_flex().child(
379 div().text_size(px(20.)).font_weight(FontWeight::SEMIBOLD).text_color(theme::text_strong()).child(self.title()),
380 )
381 };
382 v_flex()
383 .gap(px(2.))
384 .children(site.map(|name| div().text_size(px(13.)).text_color(theme::text_soft()).child(name)))
385 .child(title)
386 }
387
388 fn column_header(&self) -> Div {
389 let [name, when, who] = self.place.columns();
390 h_flex()
391 .h(px(40.))
392 .flex_none()
393 .px(px(12.))
394 .gap(px(12.))
395 .items_center()
396 .border_b_1()
397 .border_color(theme::border())
398 .text_size(px(12.5))
399 .font_weight(FontWeight::SEMIBOLD)
400 .text_color(theme::text_soft())
401 .child(div().w(px(CHECK_WIDTH)).flex_none())
402 .child(div().flex_1().min_w_0().child(name))
403 .child(div().w(px(WHEN_WIDTH)).flex_none().child(when))
404 .child(div().w(px(WHO_WIDTH)).flex_none().child(who))
405 }
406
407 fn when_text(&self, entry: &DriveEntry, now: DateTime<Utc>) -> String {
408 match (self.place, entry.modified_at) {
409 (Place::Home, Some(opened)) => opened_ago(opened, now).unwrap_or_else(|| modified_text(entry)),
410 _ => modified_text(entry),
411 }
412 }
413
414 fn row(&self, index: usize, entry: &DriveEntry, now: DateTime<Utc>, cx: &mut Context<Self>) -> Stateful<Div> {
415 let picked = self.selected.iter().any(|selected| selected.id == entry.id);
416 let folder = entry.is_folder();
417 let clicked = entry.clone();
418 h_flex()
419 .id(("cloud-picker-row", index))
420 .h(px(ROW_HEIGHT))
421 .flex_none()
422 .px(px(12.))
423 .gap(px(12.))
424 .items_center()
425 .border_b_1()
426 .border_color(theme::border())
427 .cursor_pointer()
428 .text_size(px(13.))
429 .text_color(theme::text_soft())
430 .when(picked, |row| row.bg(theme::selection()))
431 .hover(|row| row.bg(theme::row_hover()))
432 .child(
433 div().w(px(CHECK_WIDTH)).flex_none().when(!folder, |cell| {
434 cell.child(Checkbox::new(("cloud-picker-check", index)).checked(picked))
435 }),
436 )
437 .child(
438 h_flex()
439 .flex_1()
440 .min_w_0()
441 .gap(px(10.))
442 .items_center()
443 .child(entry_badge(entry))
444 .child(div().truncate().text_color(theme::text()).child(entry.name.clone())),
445 )
446 .child(div().w(px(WHEN_WIDTH)).flex_none().truncate().child(self.when_text(entry, now)))
447 .child(div().w(px(WHO_WIDTH)).flex_none().truncate().child(entry.modified_by.clone().unwrap_or_default()))
448 .on_click(cx.listener(move |this, _, _, cx| this.click_row(clicked.clone(), cx)))
449 }
450
451 fn table(&self, cx: &mut Context<Self>) -> AnyElement {
452 let note = |text: &'static str| {
453 div().p(px(16.)).text_size(px(13.)).text_color(theme::text_soft()).child(text).into_any_element()
454 };
455 let now = Utc::now();
456 let body: Vec<AnyElement> = match &self.rows {
457 Rows::Loading => vec![note("Loading ...")],
458 Rows::Failed => vec![note("Couldn't load files.")],
459 Rows::Ready(entries) if entries.is_empty() => vec![note("This folder is empty.")],
460 Rows::Ready(entries) => {
461 entries.iter().enumerate().map(|(index, entry)| self.row(index, entry, now, cx).into_any_element()).collect()
462 }
463 };
464 v_flex()
465 .flex_1()
466 .min_h_0()
467 .rounded(px(10.))
468 .bg(theme::surface_raised())
469 .overflow_hidden()
470 .child(self.column_header())
471 .child(v_flex().id("cloud-picker-rows").flex_1().min_h_0().overflow_y_scrollbar().children(body))
472 .into_any_element()
473 }
474}
475
476impl Render for CloudPicker {
477 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
478 let viewport = window.viewport_size();
479 let width = px(PANEL_WIDTH).min(viewport.width - px(2. * PANEL_MARGIN));
480 let height = px(PANEL_HEIGHT).min(viewport.height - px(2. * PANEL_MARGIN));
481 let can_attach = !self.selected.is_empty();
482 let panel = h_flex()
483 .id(CLOUD_PICKER_TAG)
484 .debug_selector(|| CLOUD_PICKER_TAG.into())
485 .w(width)
486 .h(height)
487 .rounded(px(12.))
488 .dialog_surface()
489 .text_color(theme::text())
490 .occlude()
491 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
492 .child(self.navigation(cx))
493 .child(
494 v_flex()
495 .flex_1()
496 .min_w_0()
497 .h_full()
498 .p(px(PADDING))
499 .gap(px(16.))
500 .child(self.header(cx))
501 .child(self.table(cx))
502 .child(
503 h_flex()
504 .justify_end()
505 .gap(px(8.))
506 .child(
507 Button::new("cloud-picker-attach")
508 .primary()
509 .label("Attach")
510 .disabled(!can_attach)
511 .on_click(cx.listener(|this, _, _, cx| this.attach(cx))),
512 )
513 .child(
514 Button::new("cloud-picker-cancel")
515 .label("Cancel")
516 .on_click(cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close))),
517 ),
518 ),
519 );
520 deferred(
521 anchored().position(point(px(0.), px(0.))).child(
522 div()
523 .id("cloud-picker-backdrop")
524 .track_focus(&self.focus_handle)
525 .w(viewport.width)
526 .h(viewport.height)
527 .flex()
528 .items_center()
529 .justify_center()
530 .bg(black().opacity(BACKDROP_OPACITY))
531 .occlude()
532 .on_key_down(cx.listener(|_, event: &KeyDownEvent, _, cx| {
533 if event.keystroke.key == "escape" {
534 cx.emit(CloudPickerEvent::Close);
535 }
536 }))
537 .on_mouse_down(MouseButton::Left, cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)))
538 .child(panel),
539 ),
540 )
541 .with_priority(3)
542 }
543}
544
545#[cfg(test)]
546mod tests {
547 use chrono::{TimeZone as _, Utc};
548
549 use super::{Place, opened_ago};
550
551 #[test]
552 fn home_shows_hours_ago_like_the_onedrive_picker() {
553 let now = Utc.with_ymd_and_hms(2026, 11, 10, 22, 0, 0).unwrap();
554 assert_eq!(opened_ago(now - chrono::Duration::hours(9), now).as_deref(), Some("9h ago"));
555 assert_eq!(opened_ago(now - chrono::Duration::minutes(5), now).as_deref(), Some("5m ago"));
556 assert_eq!(opened_ago(now - chrono::Duration::days(3), now), None);
557 }
558
559 #[test]
560 fn each_place_has_the_picker_columns() {
561 assert_eq!(Place::Home.columns(), ["Name", "Opened", "Owner"]);
562 assert_eq!(Place::Shared.columns(), ["Name", "Date shared", "Shared by"]);
563 assert_eq!(Place::Site(0).columns(), ["Name", "Modified", "Modified By"]);
564 }
565}