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