BlueGit

ict rusty-teams

Files

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

attachments.rs

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