BlueGit

ict rusty-teams

Files

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

attachments.rs

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