BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / attachments.rs

attachments.rs

33b53d7d History
attachments.rs 18.2 KiB Download Raw
1use std::rc::Rc;
2
3use gpui_kit::assets::IconName;
4use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7use teams_core::{FileCard, FileKind, ImageRef, external_image_url};
8
9use super::image_menu::{ImageShare, with_image_menu};
10use super::widgets::{icon, symbol};
11use crate::data::Directory;
12use crate::downloads::{self, DownloadState};
13use crate::format;
14use crate::inline_video;
15use crate::remote_image;
16use crate::render::{Block, render_blocks};
17use crate::rows::LocalImage;
18use crate::theme;
19
20pub const IMAGE_MAX_WIDTH: f32 = 360.;
21const IMAGE_MAX_HEIGHT: f32 = 300.;
22const IMAGE_MIN_SIDE: f32 = 48.;
23const IMAGE_FALLBACK: (f32, f32) = (240., 160.);
24const IMAGE_RADIUS: f32 = 10.;
25const FILE_CARD_WIDTH: f32 = 300.;
26const FILE_BADGE_SIZE: f32 = 34.;
27const SAVE_BUTTON_SIZE: f32 = 28.;
28const SAVE_BUTTON_RADIUS: f32 = 6.;
29const SAVE_PROGRESS_HEIGHT: f32 = 2.;
30const FILE_PREVIEW_HEIGHT: f32 = FILE_CARD_WIDTH * 9. / 16.;
31const PLAY_BUTTON_SIZE: f32 = 40.;
32const LOCAL_IMAGE_PREFIX: &str = "../hostedContents/";
33const LOCAL_IMAGE_SUFFIX: &str = "/$value";
34
35pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;
36#[derive(Clone)]
37pub struct ImageActions {
38 pub open: Rc<dyn Fn(&str, &mut App)>,
39 pub share: Option<ImageShare>,
40}
41
42#[derive(Clone)]
43pub struct FileActions {
44 pub states: Vec<Option<DownloadState>>,
45 pub activate: FileActivate,
46}
47
48pub fn fit_image(size: Option<(u32, u32)>) -> (f32, f32) {
49 fit_image_within(size, IMAGE_MAX_HEIGHT)
50}
51
52fn fit_image_within(size: Option<(u32, u32)>, max_height: f32) -> (f32, f32) {
53 let Some((width, height)) = size.filter(|(width, height)| *width > 0 && *height > 0) else {
54 return IMAGE_FALLBACK;
55 };
56 let (width, height) = (width as f32, height as f32);
57 let scale = (IMAGE_MAX_WIDTH / width).min(max_height / height).min(1.);
58 (
59 (width * scale).max(IMAGE_MIN_SIDE).round(),
60 (height * scale).max(IMAGE_MIN_SIDE).round(),
61 )
62}
63
64fn declared_size(image: &ImageRef) -> Option<(u32, u32)> {
65 image.width.zip(image.height)
66}
67
68pub fn image_size(image: &ImageRef, directory: &Directory) -> (f32, f32) {
69 let loaded = directory.image(&image.url).and_then(|entry| entry.size);
70 let max_height = if external_image_url(&image.url).is_some() {
71 remote_image::MAX_HEIGHT as f32
72 } else {
73 IMAGE_MAX_HEIGHT
74 };
75 fit_image_within(declared_size(image).or(loaded), max_height)
76}
77
78fn image_view(
79 image: &ImageRef,
80 id: String,
81 directory: &Directory,
82 open_image: Option<&ImageActions>,
83) -> AnyElement {
84 let (width, height) = image_size(image, directory);
85 let image_id = ElementId::Name(format!("{id}-image").into());
86 let frame = div()
87 .id(ElementId::Name(id.into()))
88 .relative()
89 .w(px(width))
90 .h(px(height))
91 .max_w(relative(1.))
92 .flex_none()
93 .rounded(px(IMAGE_RADIUS))
94 .overflow_hidden();
95 let Some(entry) = directory.image(&image.url) else {
96 return frame
97 .flex()
98 .flex_col()
99 .gap(px(6.))
100 .items_center()
101 .justify_center()
102 .bg(theme::background())
103 .child(icon(IconName::Image, 24., theme::text_muted()))
104 .child(
105 div()
106 .text_size(px(11.))
107 .text_color(theme::text_muted())
108 .child("Loading image"),
109 )
110 .into_any_element();
111 };
112 let path = entry.path.clone();
113 let share = open_image.and_then(|actions| actions.share.clone());
114 let (url, open_image) = (image.url.clone(), open_image.cloned());
115 let frame = frame
116 .cursor_pointer()
117 .child(
118 img(entry.path.clone())
119 .id(image_id)
120 .size_full()
121 .rounded(px(IMAGE_RADIUS))
122 .object_fit(ObjectFit::Cover),
123 )
124 .on_click({
125 let path = path.clone();
126 move |_, _, cx| match &open_image {
127 Some(actions) => (actions.open)(&url, cx),
128 None => cx.open_with_system(&path),
129 }
130 });
131 with_image_menu(frame, path, share).into_any_element()
132}
133
134struct KindStyle {
135 label: &'static str,
136 description: &'static str,
137 color: u32,
138}
139
140fn kind_style(kind: FileKind) -> KindStyle {
141 let (label, description, color) = match kind {
142 FileKind::Word => ("DOC", "Word document", 0x2563EB),
143 FileKind::Excel => ("XLS", "Excel spreadsheet", 0x15803D),
144 FileKind::PowerPoint => ("PPT", "PowerPoint", 0xC2410C),
145 FileKind::Pdf => ("PDF", "PDF document", 0xB91C1C),
146 FileKind::Image => ("IMG", "Image", 0x7C3AED),
147 FileKind::Video => ("VID", "Video", 0xBE185D),
148 FileKind::Archive => ("ZIP", "Archive", 0xB45309),
149 FileKind::Loop => ("", "Loop component", 0x7C3AED),
150 FileKind::Other => ("", "File", 0x525252),
151 };
152 KindStyle {
153 label,
154 description,
155 color,
156 }
157}
158
159pub fn file_subtitle(card: &FileCard) -> String {
160 let description = kind_style(card.kind).description;
161 match card.size {
162 Some(size) => format!("{description} \u{b7} {}", format::file_size_label(size)),
163 None => description.to_owned(),
164 }
165}
166
167pub fn file_badge(kind: FileKind, size: f32) -> Div {
168 let style = kind_style(kind);
169 div()
170 .size(px(size))
171 .flex_none()
172 .flex()
173 .items_center()
174 .justify_center()
175 .rounded(px(7.))
176 .bg(theme::color(style.color))
177 .text_color(gpui_kit::white())
178 .text_size(px(10.5))
179 .font_weight(FontWeight::BOLD)
180 .when(style.label.is_empty(), |badge| {
181 badge.child(icon(IconName::File, 16., gpui_kit::white()))
182 })
183 .when(!style.label.is_empty(), |badge| badge.child(style.label))
184}
185
186fn local_image_view(image: &LocalImage, id: String) -> AnyElement {
187 let (width, height) = fit_image(image.size);
188 let image_id = ElementId::Name(format!("{id}-image").into());
189 div()
190 .id(ElementId::Name(id.into()))
191 .w(px(width))
192 .h(px(height))
193 .max_w(relative(1.))
194 .flex_none()
195 .rounded(px(IMAGE_RADIUS))
196 .overflow_hidden()
197 .child(
198 img(image.image.clone())
199 .id(image_id)
200 .size_full()
201 .rounded(px(IMAGE_RADIUS))
202 .object_fit(ObjectFit::Cover),
203 )
204 .into_any_element()
205}
206
207fn save_button(
208 state: Option<&DownloadState>,
209 id: String,
210 index: usize,
211 activate: FileActivate,
212) -> Stateful<Div> {
213 let look = downloads::button_look(state);
214 let tooltip = look.tooltip.clone();
215 let clickable = look.clickable;
216 let button = div()
217 .id(ElementId::Name(id.into()))
218 .size(px(SAVE_BUTTON_SIZE))
219 .flex_none()
220 .flex()
221 .items_center()
222 .justify_center()
223 .rounded(px(SAVE_BUTTON_RADIUS))
224 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
225 .when(look.clickable, |button| {
226 button
227 .cursor_pointer()
228 .hover(|button| button.bg(theme::row_hover()))
229 })
230 .on_click(move |_, _, cx| {
231 cx.stop_propagation();
232 if clickable {
233 activate(index, cx);
234 }
235 });
236 match look.percent {
237 Some(percent) => button.child(
238 div()
239 .text_size(px(11.))
240 .text_color(theme::text_muted())
241 .child(downloads::percent_label(percent)),
242 ),
243 None => button.child(symbol(look.symbol, 16., theme::text_muted())),
244 }
245}
246
247fn file_preview(card: &FileCard, id: &str, directory: &Directory) -> Option<Stateful<Div>> {
248 let image = card
249 .preview()
250 .and_then(|preview| directory.image(&preview.url).map(|entry| entry.path.clone()));
251 if image.is_none() && card.kind != FileKind::Video {
252 return None;
253 }
254 let frame = div()
255 .id(SharedString::from(format!("{id}-preview")))
256 .relative()
257 .w_full()
258 .h(px(FILE_PREVIEW_HEIGHT))
259 .overflow_hidden()
260 .bg(theme::code_surface());
261 let frame = match image {
262 Some(path) => frame.child(img(path).size_full().object_fit(match card.kind {
263 FileKind::Video => ObjectFit::Cover,
264 _ => ObjectFit::Contain,
265 })),
266 None => frame,
267 };
268 let player_key = SharedString::from(format!("{id}-player"));
269 let content_url = card.open_url.clone();
270 Some(frame.when(card.kind == FileKind::Video, |frame| {
271 let play_key = player_key.clone();
272 frame
273 .child(inline_video::slot(player_key))
274 .on_click(move |_, window, cx| {
275 if inline_video::play(play_key.clone(), &content_url, window, cx) {
276 cx.stop_propagation();
277 }
278 })
279 .child(
280 h_flex()
281 .absolute()
282 .inset_0()
283 .items_center()
284 .justify_center()
285 .child(
286 h_flex()
287 .size(px(PLAY_BUTTON_SIZE))
288 .rounded_full()
289 .items_center()
290 .justify_center()
291 .bg(black().opacity(0.5))
292 .child(icon(IconName::Play, 18., theme::white())),
293 ),
294 )
295 }))
296}
297
298fn file_view(
299 card: &FileCard,
300 id: String,
301 index: usize,
302 actions: Option<&FileActions>,
303 directory: &Directory,
304) -> AnyElement {
305 let badge = file_badge(card.kind, FILE_BADGE_SIZE);
306 let url = card.open_url.clone();
307 let state = actions
308 .and_then(|actions| actions.states.get(index))
309 .and_then(Option::as_ref);
310 let progress = downloads::progress_fraction(state);
311 let button = actions
312 .filter(|_| !card.open_url.is_empty() && card.kind != FileKind::Loop)
313 .map(|actions| save_button(state, format!("{id}-save"), index, actions.activate.clone()));
314 let preview = file_preview(card, &id, directory);
315 let row = h_flex()
316 .w_full()
317 .gap(px(12.))
318 .px(px(8.))
319 .py(px(8.))
320 .items_center()
321 .child(badge)
322 .child(
323 v_flex()
324 .flex_1()
325 .min_w_0()
326 .child(
327 div()
328 .truncate()
329 .text_size(px(13.))
330 .text_color(theme::text())
331 .child(card.name.clone()),
332 )
333 .child(
334 div()
335 .truncate()
336 .text_size(px(11.))
337 .text_color(theme::text_muted())
338 .child(file_subtitle(card)),
339 ),
340 )
341 .child(icon(IconName::ExternalLink, 14., theme::text_muted()))
342 .children(button);
343 v_flex()
344 .id(ElementId::Name(id.into()))
345 .relative()
346 .overflow_hidden()
347 .w_full()
348 .max_w(px(FILE_CARD_WIDTH))
349 .rounded(px(10.))
350 .bg(theme::surface())
351 .cursor_pointer()
352 .hover(|card| card.bg(theme::row_hover()))
353 .children(preview)
354 .child(row)
355 .when_some(progress, |card, fraction| {
356 card.child(
357 div()
358 .absolute()
359 .left_0()
360 .bottom_0()
361 .h(px(SAVE_PROGRESS_HEIGHT))
362 .w(relative(fraction))
363 .bg(theme::accent()),
364 )
365 })
366 .on_click(move |_, _, cx| cx.open_url(&url))
367 .into_any_element()
368}
369
370#[derive(Debug, Clone, Copy, PartialEq, Eq)]
371enum Placement {
372 Remote(usize),
373 Local(usize),
374}
375
376fn local_image_index(url: &str) -> Option<usize> {
377 url.strip_prefix(LOCAL_IMAGE_PREFIX)?
378 .strip_suffix(LOCAL_IMAGE_SUFFIX)?
379 .parse::<usize>()
380 .ok()?
381 .checked_sub(1)
382}
383
384fn placement(url: &str, images: &[ImageRef], local_count: usize) -> Option<Placement> {
385 if let Some(index) = images.iter().position(|image| image.url == url) {
386 return Some(Placement::Remote(index));
387 }
388 local_image_index(url)
389 .filter(|index| *index < local_count)
390 .map(Placement::Local)
391}
392
393fn placements(blocks: &[Block], images: &[ImageRef], local_count: usize) -> Vec<Placement> {
394 blocks
395 .iter()
396 .filter_map(|block| match block {
397 Block::Image { url } => placement(url, images, local_count),
398 _ => None,
399 })
400 .collect()
401}
402
403pub fn message_body(
404 blocks: &[Block],
405 images: &[ImageRef],
406 local_images: &[LocalImage],
407 id: &str,
408 own: bool,
409 directory: &Directory,
410 open_image: Option<&ImageActions>,
411 cx: &App,
412) -> Vec<AnyElement> {
413 if !blocks
414 .iter()
415 .any(|block| matches!(block, Block::Image { .. }))
416 {
417 return vec![render_blocks(blocks, id, own, cx)];
418 }
419 let mut elements = Vec::new();
420 let mut run_start = 0;
421 let render_run = |start: usize, end: usize, elements: &mut Vec<AnyElement>| {
422 if end > start {
423 let part_id = format!("{id}-part-{start}");
424 elements.push(render_blocks(&blocks[start..end], &part_id, own, cx));
425 }
426 };
427 for (index, block) in blocks.iter().enumerate() {
428 let Block::Image { url } = block else {
429 continue;
430 };
431 render_run(run_start, index, &mut elements);
432 run_start = index + 1;
433 match placement(url, images, local_images.len()) {
434 Some(Placement::Remote(position)) => elements.push(image_view(
435 &images[position],
436 format!("{id}-image-{position}"),
437 directory,
438 open_image,
439 )),
440 Some(Placement::Local(position)) => elements.push(local_image_view(
441 &local_images[position],
442 format!("{id}-local-image-{position}"),
443 )),
444 None => {}
445 }
446 }
447 render_run(run_start, blocks.len(), &mut elements);
448 elements
449}
450
451pub fn attachments_view(
452 blocks: &[Block],
453 images: &[ImageRef],
454 local_images: &[LocalImage],
455 files: &[FileCard],
456 id: &str,
457 directory: &Directory,
458 file_actions: Option<&FileActions>,
459 open_image: Option<&ImageActions>,
460) -> Option<Div> {
461 let placed = placements(blocks, images, local_images.len());
462 let unplaced_images: Vec<(usize, &ImageRef)> = images
463 .iter()
464 .enumerate()
465 .filter(|(index, _)| !placed.contains(&Placement::Remote(*index)))
466 .collect();
467 let unplaced_local: Vec<(usize, &LocalImage)> = local_images
468 .iter()
469 .enumerate()
470 .filter(|(index, _)| !placed.contains(&Placement::Local(*index)))
471 .collect();
472 if unplaced_images.is_empty() && unplaced_local.is_empty() && files.is_empty() {
473 return None;
474 }
475 Some(
476 v_flex()
477 .gap(px(6.))
478 .items_start()
479 .children(unplaced_images.into_iter().map(|(index, image)| {
480 image_view(image, format!("{id}-image-{index}"), directory, open_image)
481 }))
482 .children(
483 unplaced_local.into_iter().map(|(index, image)| {
484 local_image_view(image, format!("{id}-local-image-{index}"))
485 }),
486 )
487 .children(files.iter().enumerate().map(|(index, card)| {
488 file_view(
489 card,
490 format!("{id}-file-{index}"),
491 index,
492 file_actions,
493 directory,
494 )
495 })),
496 )
497}
498
499#[cfg(test)]
500mod tests {
501 use super::{
502 IMAGE_FALLBACK, Placement, file_subtitle, fit_image, fit_image_within, local_image_index,
503 placement, placements,
504 };
505 use crate::render::Block;
506 use teams_core::{FileCard, FileKind, ImageRef};
507
508 fn image_ref(url: &str) -> ImageRef {
509 ImageRef {
510 id: url.into(),
511 url: url.into(),
512 width: None,
513 height: None,
514 alt: None,
515 }
516 }
517
518 fn image_block(url: &str) -> Block {
519 Block::Image { url: url.into() }
520 }
521
522 #[test]
523 fn hosted_content_urls_map_to_zero_based_local_indices() {
524 assert_eq!(local_image_index("../hostedContents/2/$value"), Some(1));
525 assert_eq!(local_image_index("../hostedContents/0/$value"), None);
526 assert_eq!(local_image_index("https://x/y"), None);
527 }
528
529 #[test]
530 fn placed_images_are_found_by_url_before_local_indices() {
531 let images = [image_ref("a"), image_ref("b")];
532 let blocks = [
533 image_block("b"),
534 image_block("../hostedContents/2/$value"),
535 image_block("../hostedContents/9/$value"),
536 image_block("missing"),
537 ];
538 assert_eq!(
539 placements(&blocks, &images, 2),
540 vec![Placement::Remote(1), Placement::Local(1)]
541 );
542 assert_eq!(placement("a", &images, 0), Some(Placement::Remote(0)));
543 }
544
545 #[test]
546 fn wide_images_shrink_to_the_max_width_keeping_aspect() {
547 assert_eq!(fit_image(Some((720, 360))), (360., 180.));
548 }
549
550 #[test]
551 fn gifs_and_stickers_are_capped_at_250_high() {
552 assert_eq!(fit_image_within(Some((300, 500)), 250.), (150., 250.));
553 }
554
555 #[test]
556 fn tall_images_shrink_to_the_max_height() {
557 assert_eq!(fit_image(Some((300, 600))), (150., 300.));
558 }
559
560 #[test]
561 fn small_images_keep_their_size() {
562 assert_eq!(fit_image(Some((200, 100))), (200., 100.));
563 }
564
565 #[test]
566 fn unknown_or_empty_sizes_use_the_fallback() {
567 assert_eq!(fit_image(None), IMAGE_FALLBACK);
568 assert_eq!(fit_image(Some((0, 10))), IMAGE_FALLBACK);
569 }
570
571 #[test]
572 fn thin_images_keep_a_clickable_side() {
573 assert_eq!(fit_image(Some((3000, 10))), (360., 48.));
574 }
575
576 #[test]
577 fn subtitle_adds_the_size_when_known() {
578 let card = FileCard {
579 name: "a.pdf".into(),
580 kind: FileKind::Pdf,
581 content_type: None,
582 size: Some(2048),
583 open_url: String::new(),
584 };
585 assert_eq!(file_subtitle(&card), "PDF document \u{b7} 2 KB");
586 let unknown = FileCard { size: None, ..card };
587 assert_eq!(file_subtitle(&unknown), "PDF document");
588 }
589}