BlueGit

ict rusty-teams

Files

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

attach_menu.rs

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