BlueGit

ict rusty-teams

Files

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

attach_menu.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
attach_menu.rs 18.6 KiB Download Raw
1use std::time::Duration;
2
3use chrono::{DateTime, Utc};
4use gpui_kit::component::fluent::{
5 MENU_ICON_LABEL_GAP, MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X, MENU_LIST_PADDING,
6};
7use gpui_kit::component::input::{Input, InputEvent, InputState};
8use gpui_kit::component::scroll::ScrollableElement as _;
9use gpui_kit::component::tooltip::PopupTriggerTooltip as _;
10use gpui_kit::component::{h_flex, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
13use teams_core::substrate_search::SearchSession;
14use teams_core::{CloudFile, FileKind, FileReference};
15
16use super::cloud_picker::{ATTACH_CLOUD_LABEL, CloudPicker, CloudPickerEvent};
17use super::{COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
18use crate::runtime;
19use crate::theme::{self, ElevatedSurface as _};
20use crate::views::attachments::file_badge;
21use crate::views::widgets::symbol;
22
23pub const ATTACH_BUTTON_TAG: &str = "composer/actions/attach";
24pub const ATTACH_MENU_TAG: &str = "composer/attach-menu";
25const BUTTON_LABEL: &str = "Attach file";
26const SEARCH_PLACEHOLDER: &str = "Search cloud files";
27const RECENT_TITLE: &str = "Recent cloud files";
28const RESULTS_TITLE: &str = "Cloud files";
29const UPLOAD_LABEL: &str = "Upload from this device";
30const LOADING: &str = "Loading ...";
31const NO_RECENT: &str = "Your recent files will show up here.";
32const NO_RESULTS: &str = "No files found.";
33const FAILED: &str = "Couldn't load files.";
34const ATTACH_FAILED: &str = "Couldn't attach";
35const MENU_WIDTH: f32 = 316.;
36const LIST_MAX_HEIGHT: f32 = 300.;
37const ROW_HEIGHT: f32 = 48.;
38const BADGE_SIZE: f32 = 24.;
39const SEARCH_HEIGHT: f32 = 32.;
40const SIDE_INSET: f32 = 12.;
41const SEARCH_DEBOUNCE: Duration = Duration::from_millis(300);
42const MINUTE: i64 = 60;
43const HOUR: i64 = 60 * MINUTE;
44const DAY: i64 = 24 * HOUR;
45
46#[derive(Default)]
47pub(super) struct AttachMenu {
48 pub(super) open: bool,
49 recent: Listing,
50 found: Option<Listing>,
51 search_input: Option<Entity<InputState>>,
52 search_session: Option<SearchSession>,
53 search_generation: u64,
54 search_task: Option<Task<()>>,
55 _search_events: Option<Subscription>,
56}
57
58impl AttachMenu {
59 pub(super) fn input_focused(&self, window: &Window, cx: &App) -> bool {
60 self.search_input
61 .as_ref()
62 .is_some_and(|input| input.read(cx).focus_handle(cx).is_focused(window))
63 }
64}
65
66#[derive(Default)]
67enum Listing {
68 #[default]
69 Loading,
70 Ready(Vec<CloudFile>),
71 Failed,
72}
73
74pub fn opened_label(opened: DateTime<Utc>, now: DateTime<Utc>) -> String {
75 let seconds = (now - opened).num_seconds().max(0);
76 let count = |value: i64, unit: &str| {
77 let plural = if value == 1 { "" } else { "s" };
78 format!("Opened {value} {unit}{plural} ago")
79 };
80 match seconds {
81 0..MINUTE => "Opened just now".to_owned(),
82 MINUTE..HOUR => count(seconds / MINUTE, "minute"),
83 HOUR..DAY => count(seconds / HOUR, "hour"),
84 _ => count(seconds / DAY, "day"),
85 }
86}
87
88fn demo_files() -> Vec<CloudFile> {
89 let now = Utc::now();
90 [
91 ("Release plan Q4.pptx", 2_480_000, 4 * HOUR),
92 ("Architecture review.pdf", 860_000, 2 * DAY),
93 ("Budget 2027.xlsx", 74_000, 9 * DAY),
94 ]
95 .into_iter()
96 .map(|(name, size, age)| CloudFile {
97 name: name.to_owned(),
98 size,
99 web_url: format!("https://example.com/demo/{name}"),
100 drive_id: None,
101 item_id: None,
102 last_opened: Some(now - chrono::Duration::seconds(age)),
103 })
104 .collect()
105}
106
107impl Composer {
108 pub(super) fn render_attach_button(&self, cx: &mut Context<Self>) -> Stateful<Div> {
109 let open = self.attach_menu.open;
110 div()
111 .id("composer-attach")
112 .debug_selector(|| ATTACH_BUTTON_TAG.into())
113 .size(px(COMPOSER_BUTTON_SIZE))
114 .flex_none()
115 .flex()
116 .items_center()
117 .justify_center()
118 .rounded(px(8.))
119 .cursor_pointer()
120 .when(open, |button| button.bg(theme::popup_hover()))
121 .hover(|button| button.bg(theme::popup_hover()))
122 .popup_trigger_tooltip_text(open, BUTTON_LABEL)
123 .child(symbol(
124 "attach_file",
125 COMPOSER_ICON_SIZE,
126 if open {
127 theme::accent_text()
128 } else {
129 theme::text_muted()
130 },
131 ))
132 .on_mouse_down(MouseButton::Left, |_, window, cx| {
133 window.prevent_default();
134 cx.stop_propagation();
135 })
136 .on_click(cx.listener(|this, _, window, cx| this.toggle_attach_menu(window, cx)))
137 }
138
139 fn toggle_attach_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
140 if self.attach_menu.open {
141 self.close_attach_menu(window, cx);
142 return;
143 }
144 self.attach_menu.open = true;
145 self.plus_menu = false;
146 self.load_recent_cloud_files(cx);
147 let input = self.attach_search_input(window, cx);
148 input.update(cx, |input, cx| input.focus(window, cx));
149 cx.notify();
150 }
151
152 pub(super) fn close_attach_menu(
153 &mut self,
154 window: &mut Window,
155 cx: &mut Context<Self>,
156 ) -> bool {
157 if !self.attach_menu.open {
158 return false;
159 }
160 self.attach_menu.open = false;
161 self.attach_menu.found = None;
162 self.attach_menu.search_task = None;
163 self.attach_menu.search_generation += 1;
164 if let Some(input) = &self.attach_menu.search_input {
165 input.update(cx, |input, cx| input.set_value("", window, cx));
166 }
167 self.focus(window, cx);
168 cx.notify();
169 true
170 }
171
172 fn attach_search_input(
173 &mut self,
174 window: &mut Window,
175 cx: &mut Context<Self>,
176 ) -> Entity<InputState> {
177 if let Some(input) = &self.attach_menu.search_input {
178 return input.clone();
179 }
180 let input = cx.new(|cx| InputState::new(window, cx).placeholder(SEARCH_PLACEHOLDER));
181 let subscription =
182 cx.subscribe_in(&input, window, |this, input, event: &InputEvent, _, cx| {
183 if matches!(event, InputEvent::Change) {
184 let text = input.read(cx).value().trim().to_owned();
185 this.search_cloud_files(text, cx);
186 }
187 });
188 self.attach_menu.search_input = Some(input.clone());
189 self.attach_menu._search_events = Some(subscription);
190 input
191 }
192
193 fn load_recent_cloud_files(&mut self, cx: &mut Context<Self>) {
194 let state = self.app.read(cx);
195 if state.mode.demo {
196 self.attach_menu.recent = Listing::Ready(demo_files());
197 return;
198 }
199 let Some(engine) = state.engine.clone() else {
200 self.attach_menu.recent = Listing::Failed;
201 return;
202 };
203 if !matches!(self.attach_menu.recent, Listing::Ready(_)) {
204 self.attach_menu.recent = Listing::Loading;
205 }
206 let receiver = runtime::spawn(async move { engine.recent_cloud_files().await });
207 cx.spawn(async move |this, cx| {
208 let listing = match receiver.await {
209 Ok(Ok(files)) => Listing::Ready(files),
210 _ => Listing::Failed,
211 };
212 this.update(cx, |this, cx| {
213 if !matches!(listing, Listing::Failed)
214 || !matches!(this.attach_menu.recent, Listing::Ready(_))
215 {
216 this.attach_menu.recent = listing;
217 }
218 cx.notify();
219 })
220 .ok();
221 })
222 .detach();
223 }
224
225 fn search_cloud_files(&mut self, text: String, cx: &mut Context<Self>) {
226 self.attach_menu.search_generation += 1;
227 let generation = self.attach_menu.search_generation;
228 if text.is_empty() {
229 self.attach_menu.found = None;
230 self.attach_menu.search_task = None;
231 cx.notify();
232 return;
233 }
234 let state = self.app.read(cx);
235 if state.mode.demo {
236 let needle = text.to_lowercase();
237 let matches = demo_files()
238 .into_iter()
239 .filter(|file| file.name.to_lowercase().contains(&needle))
240 .collect();
241 self.attach_menu.found = Some(Listing::Ready(matches));
242 cx.notify();
243 return;
244 }
245 let Some(engine) = state.engine.clone() else {
246 return;
247 };
248 let search_session = self
249 .attach_menu
250 .search_session
251 .get_or_insert_with(SearchSession::new)
252 .clone();
253 self.attach_menu.found = Some(Listing::Loading);
254 self.attach_menu.search_task = Some(cx.spawn(async move |this, cx| {
255 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
256 let receiver =
257 runtime::spawn(
258 async move { engine.search_cloud_files(&search_session, &text).await },
259 );
260 let listing = match receiver.await {
261 Ok(Ok(files)) => Listing::Ready(files),
262 _ => Listing::Failed,
263 };
264 this.update(cx, |this, cx| {
265 if this.attach_menu.search_generation == generation {
266 this.attach_menu.found = Some(listing);
267 cx.notify();
268 }
269 })
270 .ok();
271 }));
272 cx.notify();
273 }
274
275 fn attach_cloud_file(&mut self, file: CloudFile, window: &mut Window, cx: &mut Context<Self>) {
276 self.close_attach_menu(window, cx);
277 let state = self.app.read(cx);
278 if state.mode.demo {
279 let reference = FileReference {
280 attachment_id: uuid::Uuid::new_v4().to_string(),
281 content_url: file.web_url.clone(),
282 name: file.name.clone(),
283 };
284 self.tray.add_cloud_file(file.name, file.size, reference);
285 self.schedule_draft_save(cx);
286 cx.notify();
287 return;
288 }
289 let (Some(engine), Some(conversation_id)) =
290 (state.engine.clone(), self.conversation_id.clone())
291 else {
292 return;
293 };
294 let task_file = file.clone();
295 let receiver =
296 runtime::spawn(
297 async move { engine.attach_cloud_file(&conversation_id, &task_file).await },
298 );
299 cx.spawn(async move |this, cx| {
300 let attached = receiver.await;
301 this.update(cx, |this, cx| {
302 match attached {
303 Ok(Ok(reference)) => {
304 this.tray.add_cloud_file(file.name, file.size, reference);
305 this.schedule_draft_save(cx);
306 }
307 _ => this
308 .tray
309 .set_notice(format!("{ATTACH_FAILED} {}.", file.name)),
310 }
311 cx.notify();
312 })
313 .ok();
314 })
315 .detach();
316 }
317
318 fn open_cloud_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
319 self.close_attach_menu(window, cx);
320 let app = self.app.clone();
321 let picker = cx.new(|cx| CloudPicker::new(app, cx));
322 let subscription = cx.subscribe_in(
323 &picker,
324 window,
325 |this, _, event: &CloudPickerEvent, window, cx| {
326 let files = match event {
327 CloudPickerEvent::Attach(files) => files.clone(),
328 CloudPickerEvent::Close => Vec::new(),
329 };
330 this.cloud_picker = None;
331 for file in files {
332 this.attach_cloud_file(file, window, cx);
333 }
334 this.focus(window, cx);
335 cx.notify();
336 },
337 );
338 picker.read(cx).focus_handle(cx).focus(window, cx);
339 self.cloud_picker = Some((picker, subscription));
340 cx.notify();
341 }
342
343 pub(super) fn render_attach_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
344 if !self.attach_menu.open {
345 return None;
346 }
347 let search = self.attach_menu.search_input.clone().map(|input| {
348 h_flex()
349 .mx(px(SIDE_INSET))
350 .mt(px(4.))
351 .h(px(SEARCH_HEIGHT))
352 .px(px(10.))
353 .gap(px(8.))
354 .items_center()
355 .rounded(px(6.))
356 .bg(theme::surface_raised())
357 .child(symbol("search", 16., theme::text_muted()))
358 .child(
359 div()
360 .flex_1()
361 .min_w_0()
362 .child(Input::new(&input).appearance(false).bordered(false)),
363 )
364 });
365 let (title, listing) = match &self.attach_menu.found {
366 Some(found) => (RESULTS_TITLE, found),
367 None => (RECENT_TITLE, &self.attach_menu.recent),
368 };
369 let now = Utc::now();
370 let body = match listing {
371 Listing::Loading => vec![self.menu_note(LOADING)],
372 Listing::Failed => vec![self.menu_note(FAILED)],
373 Listing::Ready(files) if files.is_empty() => {
374 vec![self.menu_note(if self.attach_menu.found.is_some() {
375 NO_RESULTS
376 } else {
377 NO_RECENT
378 })]
379 }
380 Listing::Ready(files) => files
381 .iter()
382 .enumerate()
383 .map(|(index, file)| self.cloud_file_row(index, file, now, cx).into_any_element())
384 .collect(),
385 };
386 let browse = h_flex()
387 .id("composer-attach-cloud")
388 .w_full()
389 .h(MENU_ITEM_HEIGHT)
390 .px(MENU_ITEM_PADDING_X)
391 .gap(MENU_ICON_LABEL_GAP)
392 .items_center()
393 .rounded(px(6.))
394 .cursor_pointer()
395 .hover(|row| row.bg(theme::popup_hover()))
396 .child(symbol("cloud", 16., theme::text_soft()))
397 .child(
398 div()
399 .text_size(px(13.))
400 .text_color(theme::text())
401 .child(ATTACH_CLOUD_LABEL),
402 )
403 .on_click(cx.listener(|this, _, window, cx| this.open_cloud_picker(window, cx)));
404 let upload = h_flex()
405 .id("composer-attach-upload")
406 .w_full()
407 .h(MENU_ITEM_HEIGHT)
408 .px(MENU_ITEM_PADDING_X)
409 .gap(MENU_ICON_LABEL_GAP)
410 .items_center()
411 .rounded(px(6.))
412 .cursor_pointer()
413 .hover(|row| row.bg(theme::popup_hover()))
414 .child(symbol("upload", 16., theme::text_soft()))
415 .child(
416 div()
417 .text_size(px(13.))
418 .text_color(theme::text())
419 .child(UPLOAD_LABEL),
420 )
421 .on_click(cx.listener(|this, _, window, cx| {
422 this.close_attach_menu(window, cx);
423 this.open_picker(window, cx);
424 }));
425 Some(
426 v_flex()
427 .id(ATTACH_MENU_TAG)
428 .debug_selector(|| ATTACH_MENU_TAG.into())
429 .absolute()
430 .bottom(relative(1.))
431 .right_0()
432 .mb(px(6.))
433 .w(px(MENU_WIDTH))
434 .max_w(relative(1.))
435 .py(MENU_LIST_PADDING)
436 .gap(MENU_ITEM_GAP)
437 .rounded(px(10.))
438 .flyout_surface()
439 .occlude()
440 .on_mouse_down_out(cx.listener(|this, _, window, cx| {
441 this.close_attach_menu(window, cx);
442 }))
443 .children(search)
444 .child(
445 div()
446 .px(px(SIDE_INSET))
447 .pt(px(6.))
448 .text_size(px(13.))
449 .font_weight(FontWeight::SEMIBOLD)
450 .text_color(theme::text())
451 .child(title),
452 )
453 .child(
454 v_flex()
455 .id("composer-attach-list")
456 .max_h(px(LIST_MAX_HEIGHT))
457 .px(MENU_LIST_PADDING)
458 .overflow_y_scrollbar()
459 .children(body),
460 )
461 .child(div().w_full().h(px(1.)).bg(theme::border()))
462 .child(div().px(MENU_LIST_PADDING).child(browse).child(upload))
463 .into_any_element(),
464 )
465 }
466
467 fn menu_note(&self, text: &'static str) -> AnyElement {
468 div()
469 .px(MENU_ITEM_PADDING_X)
470 .py(px(10.))
471 .text_size(px(12.))
472 .text_color(theme::text_soft())
473 .child(text)
474 .into_any_element()
475 }
476
477 fn cloud_file_row(
478 &self,
479 index: usize,
480 file: &CloudFile,
481 now: DateTime<Utc>,
482 cx: &mut Context<Self>,
483 ) -> Stateful<Div> {
484 let picked = file.clone();
485 h_flex()
486 .id(("composer-attach-file", index))
487 .w_full()
488 .h(px(ROW_HEIGHT))
489 .flex_none()
490 .px(MENU_ITEM_PADDING_X)
491 .gap(px(10.))
492 .items_center()
493 .rounded(px(6.))
494 .cursor_pointer()
495 .hover(|row| row.bg(theme::popup_hover()))
496 .child(file_badge(FileKind::from_name(&file.name), BADGE_SIZE))
497 .child(
498 v_flex()
499 .flex_1()
500 .min_w_0()
501 .child(
502 div()
503 .text_size(px(13.))
504 .text_color(theme::text())
505 .truncate()
506 .child(file.name.clone()),
507 )
508 .children(file.last_opened.map(|opened| {
509 div()
510 .text_size(px(12.))
511 .text_color(theme::text_soft())
512 .child(opened_label(opened, now))
513 })),
514 )
515 .on_click(cx.listener(move |this, _, window, cx| {
516 this.attach_cloud_file(picked.clone(), window, cx)
517 }))
518 }
519}
520
521#[cfg(test)]
522mod tests {
523 use chrono::TimeZone as _;
524
525 use super::opened_label;
526
527 #[test]
528 fn opened_reads_like_teams() {
529 let now = chrono::Utc.with_ymd_and_hms(2026, 11, 9, 20, 0, 0).unwrap();
530 let ago = |seconds: i64| opened_label(now - chrono::Duration::seconds(seconds), now);
531 assert_eq!(ago(20), "Opened just now");
532 assert_eq!(ago(60), "Opened 1 minute ago");
533 assert_eq!(ago(4 * 3600 + 100), "Opened 4 hours ago");
534 assert_eq!(ago(6 * 86_400), "Opened 6 days ago");
535 }
536}