BlueGit

ict rusty-teams

Files

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

attachments.rs

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