BlueGit

ict rusty-teams

Files

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

attach_menu.rs

attach_menu.rs 17.7 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 { theme::accent_text() } else { theme::text_muted() },
127 ))
128 .on_mouse_down(MouseButton::Left, |_, window, cx| {
129 window.prevent_default();
130 cx.stop_propagation();
131 })
132 .on_click(cx.listener(|this, _, window, cx| this.toggle_attach_menu(window, cx)))
133 }
134
135 fn toggle_attach_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
136 if self.attach_menu.open {
137 self.close_attach_menu(window, cx);
138 return;
139 }
140 self.attach_menu.open = true;
141 self.plus_menu = false;
142 self.load_recent_cloud_files(cx);
143 let input = self.attach_search_input(window, cx);
144 input.update(cx, |input, cx| input.focus(window, cx));
145 cx.notify();
146 }
147
148 pub(super) fn close_attach_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
149 if !self.attach_menu.open {
150 return false;
151 }
152 self.attach_menu.open = false;
153 self.attach_menu.found = None;
154 self.attach_menu.search_task = None;
155 self.attach_menu.search_generation += 1;
156 if let Some(input) = &self.attach_menu.search_input {
157 input.update(cx, |input, cx| input.set_value("", window, cx));
158 }
159 self.focus(window, cx);
160 cx.notify();
161 true
162 }
163
164 fn attach_search_input(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<InputState> {
165 if let Some(input) = &self.attach_menu.search_input {
166 return input.clone();
167 }
168 let input = cx.new(|cx| InputState::new(window, cx).placeholder(SEARCH_PLACEHOLDER));
169 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, _, cx| {
170 if matches!(event, InputEvent::Change) {
171 let text = input.read(cx).value().trim().to_owned();
172 this.search_cloud_files(text, cx);
173 }
174 });
175 self.attach_menu.search_input = Some(input.clone());
176 self.attach_menu._search_events = Some(subscription);
177 input
178 }
179
180 fn load_recent_cloud_files(&mut self, cx: &mut Context<Self>) {
181 let state = self.app.read(cx);
182 if state.mode.demo {
183 self.attach_menu.recent = Listing::Ready(demo_files());
184 return;
185 }
186 let Some(engine) = state.engine.clone() else {
187 self.attach_menu.recent = Listing::Failed;
188 return;
189 };
190 if !matches!(self.attach_menu.recent, Listing::Ready(_)) {
191 self.attach_menu.recent = Listing::Loading;
192 }
193 let receiver = runtime::spawn(async move { engine.recent_cloud_files().await });
194 cx.spawn(async move |this, cx| {
195 let listing = match receiver.await {
196 Ok(Ok(files)) => Listing::Ready(files),
197 _ => Listing::Failed,
198 };
199 this.update(cx, |this, cx| {
200 if !matches!(listing, Listing::Failed) || !matches!(this.attach_menu.recent, Listing::Ready(_)) {
201 this.attach_menu.recent = listing;
202 }
203 cx.notify();
204 })
205 .ok();
206 })
207 .detach();
208 }
209
210 fn search_cloud_files(&mut self, text: String, cx: &mut Context<Self>) {
211 self.attach_menu.search_generation += 1;
212 let generation = self.attach_menu.search_generation;
213 if text.is_empty() {
214 self.attach_menu.found = None;
215 self.attach_menu.search_task = None;
216 cx.notify();
217 return;
218 }
219 let state = self.app.read(cx);
220 if state.mode.demo {
221 let needle = text.to_lowercase();
222 let matches = demo_files()
223 .into_iter()
224 .filter(|file| file.name.to_lowercase().contains(&needle))
225 .collect();
226 self.attach_menu.found = Some(Listing::Ready(matches));
227 cx.notify();
228 return;
229 }
230 let Some(engine) = state.engine.clone() else {
231 return;
232 };
233 let search_session = self.attach_menu.search_session.get_or_insert_with(SearchSession::new).clone();
234 self.attach_menu.found = Some(Listing::Loading);
235 self.attach_menu.search_task = Some(cx.spawn(async move |this, cx| {
236 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
237 let receiver = runtime::spawn(async move { engine.search_cloud_files(&search_session, &text).await });
238 let listing = match receiver.await {
239 Ok(Ok(files)) => Listing::Ready(files),
240 _ => Listing::Failed,
241 };
242 this.update(cx, |this, cx| {
243 if this.attach_menu.search_generation == generation {
244 this.attach_menu.found = Some(listing);
245 cx.notify();
246 }
247 })
248 .ok();
249 }));
250 cx.notify();
251 }
252
253 fn attach_cloud_file(&mut self, file: CloudFile, window: &mut Window, cx: &mut Context<Self>) {
254 self.close_attach_menu(window, cx);
255 let state = self.app.read(cx);
256 if state.mode.demo {
257 let reference = FileReference {
258 attachment_id: uuid::Uuid::new_v4().to_string(),
259 content_url: file.web_url.clone(),
260 name: file.name.clone(),
261 };
262 self.tray.add_cloud_file(file.name, file.size, reference);
263 self.schedule_draft_save(cx);
264 cx.notify();
265 return;
266 }
267 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id.clone()) else {
268 return;
269 };
270 let task_file = file.clone();
271 let receiver =
272 runtime::spawn(async move { engine.attach_cloud_file(&conversation_id, &task_file).await });
273 cx.spawn(async move |this, cx| {
274 let attached = receiver.await;
275 this.update(cx, |this, cx| {
276 match attached {
277 Ok(Ok(reference)) => {
278 this.tray.add_cloud_file(file.name, file.size, reference);
279 this.schedule_draft_save(cx);
280 }
281 _ => this.tray.set_notice(format!("{ATTACH_FAILED} {}.", file.name)),
282 }
283 cx.notify();
284 })
285 .ok();
286 })
287 .detach();
288 }
289
290 fn open_cloud_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
291 self.close_attach_menu(window, cx);
292 let app = self.app.clone();
293 let picker = cx.new(|cx| CloudPicker::new(app, cx));
294 let subscription = cx.subscribe_in(&picker, window, |this, _, event: &CloudPickerEvent, window, cx| {
295 let files = match event {
296 CloudPickerEvent::Attach(files) => files.clone(),
297 CloudPickerEvent::Close => Vec::new(),
298 };
299 this.cloud_picker = None;
300 for file in files {
301 this.attach_cloud_file(file, window, cx);
302 }
303 this.focus(window, cx);
304 cx.notify();
305 });
306 picker.read(cx).focus_handle(cx).focus(window, cx);
307 self.cloud_picker = Some((picker, subscription));
308 cx.notify();
309 }
310
311 pub(super) fn render_attach_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
312 if !self.attach_menu.open {
313 return None;
314 }
315 let search = self.attach_menu.search_input.clone().map(|input| {
316 h_flex()
317 .mx(px(SIDE_INSET))
318 .mt(px(4.))
319 .h(px(SEARCH_HEIGHT))
320 .px(px(10.))
321 .gap(px(8.))
322 .items_center()
323 .rounded(px(6.))
324 .bg(theme::surface_raised())
325 .child(symbol("search", 16., theme::text_muted()))
326 .child(div().flex_1().min_w_0().child(Input::new(&input).appearance(false).bordered(false)))
327 });
328 let (title, listing) = match &self.attach_menu.found {
329 Some(found) => (RESULTS_TITLE, found),
330 None => (RECENT_TITLE, &self.attach_menu.recent),
331 };
332 let now = Utc::now();
333 let body = match listing {
334 Listing::Loading => vec![self.menu_note(LOADING)],
335 Listing::Failed => vec![self.menu_note(FAILED)],
336 Listing::Ready(files) if files.is_empty() => {
337 vec![self.menu_note(if self.attach_menu.found.is_some() { NO_RESULTS } else { NO_RECENT })]
338 }
339 Listing::Ready(files) => files
340 .iter()
341 .enumerate()
342 .map(|(index, file)| self.cloud_file_row(index, file, now, cx).into_any_element())
343 .collect(),
344 };
345 let browse = h_flex()
346 .id("composer-attach-cloud")
347 .w_full()
348 .h(MENU_ITEM_HEIGHT)
349 .px(MENU_ITEM_PADDING_X)
350 .gap(MENU_ICON_LABEL_GAP)
351 .items_center()
352 .rounded(px(6.))
353 .cursor_pointer()
354 .hover(|row| row.bg(theme::popup_hover()))
355 .child(symbol("cloud", 16., theme::text_soft()))
356 .child(div().text_size(px(13.)).text_color(theme::text()).child(ATTACH_CLOUD_LABEL))
357 .on_click(cx.listener(|this, _, window, cx| this.open_cloud_picker(window, cx)));
358 let upload = h_flex()
359 .id("composer-attach-upload")
360 .w_full()
361 .h(MENU_ITEM_HEIGHT)
362 .px(MENU_ITEM_PADDING_X)
363 .gap(MENU_ICON_LABEL_GAP)
364 .items_center()
365 .rounded(px(6.))
366 .cursor_pointer()
367 .hover(|row| row.bg(theme::popup_hover()))
368 .child(symbol("upload", 16., theme::text_soft()))
369 .child(div().text_size(px(13.)).text_color(theme::text()).child(UPLOAD_LABEL))
370 .on_click(cx.listener(|this, _, window, cx| {
371 this.close_attach_menu(window, cx);
372 this.open_picker(window, cx);
373 }));
374 Some(
375 v_flex()
376 .id(ATTACH_MENU_TAG)
377 .debug_selector(|| ATTACH_MENU_TAG.into())
378 .absolute()
379 .bottom(relative(1.))
380 .right_0()
381 .mb(px(6.))
382 .w(px(MENU_WIDTH))
383 .max_w(relative(1.))
384 .py(MENU_LIST_PADDING)
385 .gap(MENU_ITEM_GAP)
386 .rounded(px(10.))
387 .flyout_surface()
388 .occlude()
389 .on_mouse_down_out(cx.listener(|this, _, window, cx| {
390 this.close_attach_menu(window, cx);
391 }))
392 .children(search)
393 .child(
394 div()
395 .px(px(SIDE_INSET))
396 .pt(px(6.))
397 .text_size(px(13.))
398 .font_weight(FontWeight::SEMIBOLD)
399 .text_color(theme::text())
400 .child(title),
401 )
402 .child(
403 v_flex()
404 .id("composer-attach-list")
405 .max_h(px(LIST_MAX_HEIGHT))
406 .px(MENU_LIST_PADDING)
407 .overflow_y_scrollbar()
408 .children(body),
409 )
410 .child(div().w_full().h(px(1.)).bg(theme::border()))
411 .child(div().px(MENU_LIST_PADDING).child(browse).child(upload))
412 .into_any_element(),
413 )
414 }
415
416 fn menu_note(&self, text: &'static str) -> AnyElement {
417 div()
418 .px(MENU_ITEM_PADDING_X)
419 .py(px(10.))
420 .text_size(px(12.))
421 .text_color(theme::text_soft())
422 .child(text)
423 .into_any_element()
424 }
425
426 fn cloud_file_row(&self, index: usize, file: &CloudFile, now: DateTime<Utc>, cx: &mut Context<Self>) -> Stateful<Div> {
427 let picked = file.clone();
428 h_flex()
429 .id(("composer-attach-file", index))
430 .w_full()
431 .h(px(ROW_HEIGHT))
432 .flex_none()
433 .px(MENU_ITEM_PADDING_X)
434 .gap(px(10.))
435 .items_center()
436 .rounded(px(6.))
437 .cursor_pointer()
438 .hover(|row| row.bg(theme::popup_hover()))
439 .child(file_badge(FileKind::from_name(&file.name), BADGE_SIZE))
440 .child(
441 v_flex()
442 .flex_1()
443 .min_w_0()
444 .child(
445 div()
446 .text_size(px(13.))
447 .text_color(theme::text())
448 .truncate()
449 .child(file.name.clone()),
450 )
451 .children(file.last_opened.map(|opened| {
452 div()
453 .text_size(px(12.))
454 .text_color(theme::text_soft())
455 .child(opened_label(opened, now))
456 })),
457 )
458 .on_click(cx.listener(move |this, _, window, cx| this.attach_cloud_file(picked.clone(), window, cx)))
459 }
460}
461
462#[cfg(test)]
463mod tests {
464 use chrono::TimeZone as _;
465
466 use super::opened_label;
467
468 #[test]
469 fn opened_reads_like_teams() {
470 let now = chrono::Utc.with_ymd_and_hms(2026, 11, 9, 20, 0, 0).unwrap();
471 let ago = |seconds: i64| opened_label(now - chrono::Duration::seconds(seconds), now);
472 assert_eq!(ago(20), "Opened just now");
473 assert_eq!(ago(60), "Opened 1 minute ago");
474 assert_eq!(ago(4 * 3600 + 100), "Opened 4 hours ago");
475 assert_eq!(ago(6 * 86_400), "Opened 6 days ago");
476 }
477}