BlueGit

ict rusty-teams

Files

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

attachments.rs

attachments.rs 16.0 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::Loop => ("", "Loop component", 0x7C3AED),
146 FileKind::Other => ("", "File", 0x525252),
147 };
148 KindStyle {
149 label,
150 description,
151 color,
152 }
153}
154
155pub fn file_subtitle(card: &FileCard) -> String {
156 let description = kind_style(card.kind).description;
157 match card.size {
158 Some(size) => format!("{description} \u{b7} {}", format::file_size_label(size)),
159 None => description.to_owned(),
160 }
161}
162
163pub fn file_badge(kind: FileKind, size: f32) -> Div {
164 let style = kind_style(kind);
165 div()
166 .size(px(size))
167 .flex_none()
168 .flex()
169 .items_center()
170 .justify_center()
171 .rounded(px(7.))
172 .bg(theme::color(style.color))
173 .text_color(gpui_kit::white())
174 .text_size(px(10.5))
175 .font_weight(FontWeight::BOLD)
176 .when(style.label.is_empty(), |badge| {
177 badge.child(icon(IconName::File, 16., gpui_kit::white()))
178 })
179 .when(!style.label.is_empty(), |badge| badge.child(style.label))
180}
181
182fn local_image_view(image: &LocalImage, id: String) -> AnyElement {
183 let (width, height) = fit_image(image.size);
184 let image_id = ElementId::Name(format!("{id}-image").into());
185 div()
186 .id(ElementId::Name(id.into()))
187 .w(px(width))
188 .h(px(height))
189 .max_w(relative(1.))
190 .flex_none()
191 .rounded(px(IMAGE_RADIUS))
192 .overflow_hidden()
193 .child(
194 img(image.image.clone())
195 .id(image_id)
196 .size_full()
197 .rounded(px(IMAGE_RADIUS))
198 .object_fit(ObjectFit::Cover),
199 )
200 .into_any_element()
201}
202
203fn save_button(
204 state: Option<&DownloadState>,
205 id: String,
206 index: usize,
207 activate: FileActivate,
208) -> Stateful<Div> {
209 let look = downloads::button_look(state);
210 let tooltip = look.tooltip.clone();
211 let clickable = look.clickable;
212 let button = div()
213 .id(ElementId::Name(id.into()))
214 .size(px(SAVE_BUTTON_SIZE))
215 .flex_none()
216 .flex()
217 .items_center()
218 .justify_center()
219 .rounded(px(SAVE_BUTTON_RADIUS))
220 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
221 .when(look.clickable, |button| {
222 button
223 .cursor_pointer()
224 .hover(|button| button.bg(theme::row_hover()))
225 })
226 .on_click(move |_, _, cx| {
227 cx.stop_propagation();
228 if clickable {
229 activate(index, cx);
230 }
231 });
232 match look.percent {
233 Some(percent) => button.child(
234 div()
235 .text_size(px(11.))
236 .text_color(theme::text_muted())
237 .child(downloads::percent_label(percent)),
238 ),
239 None => button.child(symbol(look.symbol, 16., theme::text_muted())),
240 }
241}
242
243fn file_view(
244 card: &FileCard,
245 id: String,
246 index: usize,
247 actions: Option<&FileActions>,
248) -> AnyElement {
249 let badge = file_badge(card.kind, FILE_BADGE_SIZE);
250 let url = card.open_url.clone();
251 let state = actions
252 .and_then(|actions| actions.states.get(index))
253 .and_then(Option::as_ref);
254 let progress = downloads::progress_fraction(state);
255 let button = actions
256 .filter(|_| !card.open_url.is_empty() && card.kind != FileKind::Loop)
257 .map(|actions| save_button(state, format!("{id}-save"), index, actions.activate.clone()));
258 h_flex()
259 .id(ElementId::Name(id.into()))
260 .relative()
261 .overflow_hidden()
262 .w_full()
263 .max_w(px(FILE_CARD_WIDTH))
264 .gap(px(12.))
265 .px(px(8.))
266 .py(px(8.))
267 .items_center()
268 .rounded(px(10.))
269 .bg(theme::surface())
270 .cursor_pointer()
271 .hover(|card| card.bg(theme::row_hover()))
272 .child(badge)
273 .child(
274 v_flex()
275 .flex_1()
276 .min_w_0()
277 .child(
278 div()
279 .truncate()
280 .text_size(px(13.))
281 .text_color(theme::text())
282 .child(card.name.clone()),
283 )
284 .child(
285 div()
286 .truncate()
287 .text_size(px(11.))
288 .text_color(theme::text_muted())
289 .child(file_subtitle(card)),
290 ),
291 )
292 .child(icon(IconName::ExternalLink, 14., theme::text_muted()))
293 .children(button)
294 .when_some(progress, |card, fraction| {
295 card.child(
296 div()
297 .absolute()
298 .left_0()
299 .bottom_0()
300 .h(px(SAVE_PROGRESS_HEIGHT))
301 .w(relative(fraction))
302 .bg(theme::accent()),
303 )
304 })
305 .on_click(move |_, _, cx| cx.open_url(&url))
306 .into_any_element()
307}
308
309#[derive(Debug, Clone, Copy, PartialEq, Eq)]
310enum Placement {
311 Remote(usize),
312 Local(usize),
313}
314
315fn local_image_index(url: &str) -> Option<usize> {
316 url.strip_prefix(LOCAL_IMAGE_PREFIX)?
317 .strip_suffix(LOCAL_IMAGE_SUFFIX)?
318 .parse::<usize>()
319 .ok()?
320 .checked_sub(1)
321}
322
323fn placement(url: &str, images: &[ImageRef], local_count: usize) -> Option<Placement> {
324 if let Some(index) = images.iter().position(|image| image.url == url) {
325 return Some(Placement::Remote(index));
326 }
327 local_image_index(url)
328 .filter(|index| *index < local_count)
329 .map(Placement::Local)
330}
331
332fn placements(blocks: &[Block], images: &[ImageRef], local_count: usize) -> Vec<Placement> {
333 blocks
334 .iter()
335 .filter_map(|block| match block {
336 Block::Image { url } => placement(url, images, local_count),
337 _ => None,
338 })
339 .collect()
340}
341
342pub fn message_body(
343 blocks: &[Block],
344 images: &[ImageRef],
345 local_images: &[LocalImage],
346 id: &str,
347 own: bool,
348 directory: &Directory,
349 open_image: Option<&ImageActions>,
350 cx: &App,
351) -> Vec<AnyElement> {
352 if !blocks
353 .iter()
354 .any(|block| matches!(block, Block::Image { .. }))
355 {
356 return vec![render_blocks(blocks, id, own, cx)];
357 }
358 let mut elements = Vec::new();
359 let mut run_start = 0;
360 let render_run = |start: usize, end: usize, elements: &mut Vec<AnyElement>| {
361 if end > start {
362 let part_id = format!("{id}-part-{start}");
363 elements.push(render_blocks(&blocks[start..end], &part_id, own, cx));
364 }
365 };
366 for (index, block) in blocks.iter().enumerate() {
367 let Block::Image { url } = block else {
368 continue;
369 };
370 render_run(run_start, index, &mut elements);
371 run_start = index + 1;
372 match placement(url, images, local_images.len()) {
373 Some(Placement::Remote(position)) => elements.push(image_view(
374 &images[position],
375 format!("{id}-image-{position}"),
376 directory,
377 open_image,
378 )),
379 Some(Placement::Local(position)) => elements.push(local_image_view(
380 &local_images[position],
381 format!("{id}-local-image-{position}"),
382 )),
383 None => {}
384 }
385 }
386 render_run(run_start, blocks.len(), &mut elements);
387 elements
388}
389
390pub fn attachments_view(
391 blocks: &[Block],
392 images: &[ImageRef],
393 local_images: &[LocalImage],
394 files: &[FileCard],
395 id: &str,
396 directory: &Directory,
397 file_actions: Option<&FileActions>,
398 open_image: Option<&ImageActions>,
399) -> Option<Div> {
400 let placed = placements(blocks, images, local_images.len());
401 let unplaced_images: Vec<(usize, &ImageRef)> = images
402 .iter()
403 .enumerate()
404 .filter(|(index, _)| !placed.contains(&Placement::Remote(*index)))
405 .collect();
406 let unplaced_local: Vec<(usize, &LocalImage)> = local_images
407 .iter()
408 .enumerate()
409 .filter(|(index, _)| !placed.contains(&Placement::Local(*index)))
410 .collect();
411 if unplaced_images.is_empty() && unplaced_local.is_empty() && files.is_empty() {
412 return None;
413 }
414 Some(
415 v_flex()
416 .gap(px(6.))
417 .items_start()
418 .children(unplaced_images.into_iter().map(|(index, image)| {
419 image_view(image, format!("{id}-image-{index}"), directory, open_image)
420 }))
421 .children(
422 unplaced_local.into_iter().map(|(index, image)| {
423 local_image_view(image, format!("{id}-local-image-{index}"))
424 }),
425 )
426 .children(files.iter().enumerate().map(|(index, card)| {
427 file_view(card, format!("{id}-file-{index}"), index, file_actions)
428 })),
429 )
430}
431
432#[cfg(test)]
433mod tests {
434 use super::{
435 IMAGE_FALLBACK, Placement, file_subtitle, fit_image, fit_image_within, local_image_index,
436 placement, placements,
437 };
438 use crate::render::Block;
439 use teams_core::{FileCard, FileKind, ImageRef};
440
441 fn image_ref(url: &str) -> ImageRef {
442 ImageRef {
443 id: url.into(),
444 url: url.into(),
445 width: None,
446 height: None,
447 alt: None,
448 }
449 }
450
451 fn image_block(url: &str) -> Block {
452 Block::Image { url: url.into() }
453 }
454
455 #[test]
456 fn hosted_content_urls_map_to_zero_based_local_indices() {
457 assert_eq!(local_image_index("../hostedContents/2/$value"), Some(1));
458 assert_eq!(local_image_index("../hostedContents/0/$value"), None);
459 assert_eq!(local_image_index("https://x/y"), None);
460 }
461
462 #[test]
463 fn placed_images_are_found_by_url_before_local_indices() {
464 let images = [image_ref("a"), image_ref("b")];
465 let blocks = [
466 image_block("b"),
467 image_block("../hostedContents/2/$value"),
468 image_block("../hostedContents/9/$value"),
469 image_block("missing"),
470 ];
471 assert_eq!(
472 placements(&blocks, &images, 2),
473 vec![Placement::Remote(1), Placement::Local(1)]
474 );
475 assert_eq!(placement("a", &images, 0), Some(Placement::Remote(0)));
476 }
477
478 #[test]
479 fn wide_images_shrink_to_the_max_width_keeping_aspect() {
480 assert_eq!(fit_image(Some((720, 360))), (360., 180.));
481 }
482
483 #[test]
484 fn gifs_and_stickers_are_capped_at_250_high() {
485 assert_eq!(fit_image_within(Some((300, 500)), 250.), (150., 250.));
486 }
487
488 #[test]
489 fn tall_images_shrink_to_the_max_height() {
490 assert_eq!(fit_image(Some((300, 600))), (150., 300.));
491 }
492
493 #[test]
494 fn small_images_keep_their_size() {
495 assert_eq!(fit_image(Some((200, 100))), (200., 100.));
496 }
497
498 #[test]
499 fn unknown_or_empty_sizes_use_the_fallback() {
500 assert_eq!(fit_image(None), IMAGE_FALLBACK);
501 assert_eq!(fit_image(Some((0, 10))), IMAGE_FALLBACK);
502 }
503
504 #[test]
505 fn thin_images_keep_a_clickable_side() {
506 assert_eq!(fit_image(Some((3000, 10))), (360., 48.));
507 }
508
509 #[test]
510 fn subtitle_adds_the_size_when_known() {
511 let card = FileCard {
512 name: "a.pdf".into(),
513 kind: FileKind::Pdf,
514 content_type: None,
515 size: Some(2048),
516 open_url: String::new(),
517 };
518 assert_eq!(file_subtitle(&card), "PDF document \u{b7} 2 KB");
519 let unknown = FileCard { size: None, ..card };
520 assert_eq!(file_subtitle(&unknown), "PDF document");
521 }
522}