BlueGit

ict rusty-teams

Files

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

attachments.rs

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