BlueGit

ict rusty-teams

Files

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

attachments.rs

attachments.rs 19.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, render_table, table_images};
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 .flat_map(|block| match block {
397 Block::Image { url } => vec![url.as_str()],
398 table => table_images(table),
399 })
400 .filter_map(|url| placement(url, images, local_count))
401 .collect()
402}
403
404fn draws_images(block: &Block) -> bool {
405 matches!(block, Block::Image { .. }) || !table_images(block).is_empty()
406}
407
408pub fn message_body(
409 blocks: &[Block],
410 images: &[ImageRef],
411 local_images: &[LocalImage],
412 id: &str,
413 own: bool,
414 directory: &Directory,
415 open_image: Option<&ImageActions>,
416 cx: &App,
417) -> Vec<AnyElement> {
418 if !blocks.iter().any(draws_images) {
419 return vec![render_blocks(blocks, id, own, cx)];
420 }
421 let mut elements = Vec::new();
422 let mut run_start = 0;
423 let render_run = |start: usize, end: usize, elements: &mut Vec<AnyElement>| {
424 if end > start {
425 let part_id = format!("{id}-part-{start}");
426 elements.push(render_blocks(&blocks[start..end], &part_id, own, cx));
427 }
428 };
429 let placed_view = |url: &str, key: &str| -> Option<AnyElement> {
430 match placement(url, images, local_images.len())? {
431 Placement::Remote(position) => Some(image_view(
432 &images[position],
433 format!("{key}-image-{position}"),
434 directory,
435 open_image,
436 )),
437 Placement::Local(position) => Some(local_image_view(
438 &local_images[position],
439 format!("{key}-local-image-{position}"),
440 )),
441 }
442 };
443 for (index, block) in blocks.iter().enumerate() {
444 if !draws_images(block) {
445 continue;
446 }
447 render_run(run_start, index, &mut elements);
448 run_start = index + 1;
449 match block {
450 Block::Image { url } => elements.extend(placed_view(url, id)),
451 Block::Table { header, rows } => {
452 let table_id = format!("{id}-table-{index}");
453 elements.push(render_table(*header, rows, &table_id, own, cx, &|url| {
454 placed_view(url, &table_id)
455 }));
456 }
457 _ => {}
458 }
459 }
460 render_run(run_start, blocks.len(), &mut elements);
461 elements
462}
463
464pub fn attachments_view(
465 blocks: &[Block],
466 images: &[ImageRef],
467 local_images: &[LocalImage],
468 files: &[FileCard],
469 id: &str,
470 directory: &Directory,
471 file_actions: Option<&FileActions>,
472 open_image: Option<&ImageActions>,
473) -> Option<Div> {
474 let placed = placements(blocks, images, local_images.len());
475 let unplaced_images: Vec<(usize, &ImageRef)> = images
476 .iter()
477 .enumerate()
478 .filter(|(index, _)| !placed.contains(&Placement::Remote(*index)))
479 .collect();
480 let unplaced_local: Vec<(usize, &LocalImage)> = local_images
481 .iter()
482 .enumerate()
483 .filter(|(index, _)| !placed.contains(&Placement::Local(*index)))
484 .collect();
485 if unplaced_images.is_empty() && unplaced_local.is_empty() && files.is_empty() {
486 return None;
487 }
488 Some(
489 v_flex()
490 .gap(px(6.))
491 .items_start()
492 .children(unplaced_images.into_iter().map(|(index, image)| {
493 image_view(image, format!("{id}-image-{index}"), directory, open_image)
494 }))
495 .children(
496 unplaced_local.into_iter().map(|(index, image)| {
497 local_image_view(image, format!("{id}-local-image-{index}"))
498 }),
499 )
500 .children(files.iter().enumerate().map(|(index, card)| {
501 file_view(
502 card,
503 format!("{id}-file-{index}"),
504 index,
505 file_actions,
506 directory,
507 )
508 })),
509 )
510}
511
512#[cfg(test)]
513mod tests {
514 use super::{
515 IMAGE_FALLBACK, Placement, file_subtitle, fit_image, fit_image_within, local_image_index,
516 placement, placements,
517 };
518 use crate::render::{Block, TableCell};
519 use teams_core::{FileCard, FileKind, ImageRef};
520
521 fn image_ref(url: &str) -> ImageRef {
522 ImageRef {
523 id: url.into(),
524 url: url.into(),
525 width: None,
526 height: None,
527 alt: None,
528 }
529 }
530
531 fn image_block(url: &str) -> Block {
532 Block::Image { url: url.into() }
533 }
534
535 #[test]
536 fn hosted_content_urls_map_to_zero_based_local_indices() {
537 assert_eq!(local_image_index("../hostedContents/2/$value"), Some(1));
538 assert_eq!(local_image_index("../hostedContents/0/$value"), None);
539 assert_eq!(local_image_index("https://x/y"), None);
540 }
541
542 #[test]
543 fn placed_images_are_found_by_url_before_local_indices() {
544 let images = [image_ref("a"), image_ref("b")];
545 let blocks = [
546 image_block("b"),
547 image_block("../hostedContents/2/$value"),
548 image_block("../hostedContents/9/$value"),
549 image_block("missing"),
550 ];
551 assert_eq!(
552 placements(&blocks, &images, 2),
553 vec![Placement::Remote(1), Placement::Local(1)]
554 );
555 assert_eq!(placement("a", &images, 0), Some(Placement::Remote(0)));
556 }
557
558 #[test]
559 fn an_image_in_a_table_cell_counts_as_placed() {
560 let images = [image_ref("a"), image_ref("b")];
561 let table = Block::Table {
562 header: false,
563 rows: vec![vec![TableCell {
564 inline: Default::default(),
565 images: vec!["b".into()],
566 }]],
567 };
568 assert_eq!(placements(&[table], &images, 0), vec![Placement::Remote(1)]);
569 }
570
571 #[test]
572 fn wide_images_shrink_to_the_max_width_keeping_aspect() {
573 assert_eq!(fit_image(Some((720, 360))), (360., 180.));
574 }
575
576 #[test]
577 fn gifs_and_stickers_are_capped_at_250_high() {
578 assert_eq!(fit_image_within(Some((300, 500)), 250.), (150., 250.));
579 }
580
581 #[test]
582 fn tall_images_shrink_to_the_max_height() {
583 assert_eq!(fit_image(Some((300, 600))), (150., 300.));
584 }
585
586 #[test]
587 fn small_images_keep_their_size() {
588 assert_eq!(fit_image(Some((200, 100))), (200., 100.));
589 }
590
591 #[test]
592 fn unknown_or_empty_sizes_use_the_fallback() {
593 assert_eq!(fit_image(None), IMAGE_FALLBACK);
594 assert_eq!(fit_image(Some((0, 10))), IMAGE_FALLBACK);
595 }
596
597 #[test]
598 fn thin_images_keep_a_clickable_side() {
599 assert_eq!(fit_image(Some((3000, 10))), (360., 48.));
600 }
601
602 #[test]
603 fn subtitle_adds_the_size_when_known() {
604 let card = FileCard {
605 name: "a.pdf".into(),
606 kind: FileKind::Pdf,
607 content_type: None,
608 size: Some(2048),
609 open_url: String::new(),
610 };
611 assert_eq!(file_subtitle(&card), "PDF document \u{b7} 2 KB");
612 let unknown = FileCard { size: None, ..card };
613 assert_eq!(file_subtitle(&unknown), "PDF document");
614 }
615}