feat(chat): show message images where they sit in the text
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -146,6 +146,9 @@ pub enum Block {
146
146
rows: Vec<Vec<Inline>>,
147
147
},
148
148
Rule,
149
Image {
150
url: String,
151
},
149
152
}
150
153
151
154
impl Block {
@@ -187,7 +190,7 @@ impl Block {
187
190
.join("\n"),
188
191
),
189
192
Block::Quote(children) => Some(join(children)),
190
Block::Reply(_) | Block::Rule => None,
193
Block::Reply(_) | Block::Rule | Block::Image { .. } => None,
191
194
}
192
195
}
193
196
@@ -198,7 +201,7 @@ impl Block {
198
201
Block::List { items, .. } => items.first()?.iter().find_map(Block::first_line),
199
202
Block::Table { rows, .. } => Some(rows.first()?.first()?.plain_text()),
200
203
Block::Quote(children) => children.iter().find_map(Block::first_line),
201
Block::Reply(_) | Block::Rule => None,
204
Block::Reply(_) | Block::Rule | Block::Image { .. } => None,
202
205
}
203
206
}
204
207
@@ -249,6 +252,10 @@ pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {
249
252
}
250
253
251
254
pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {
255
layout_blocks_with(spans, true)
256
}
257
258
fn layout_blocks_with(spans: &[Span], split_images: bool) -> Vec<Block> {
252
259
let mut blocks = Vec::new();
253
260
let mut current = Inline::default();
254
261
for span in spans {
@@ -262,7 +269,7 @@ pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {
262
269
}
263
270
Span::Quote(children) | Span::BlockQuote(children) => {
264
271
flush(&mut current, &mut blocks, Block::Paragraph);
265
let inner = layout_blocks(children);
272
let inner = layout_blocks_with(children, false);
266
273
if !inner.is_empty() {
267
274
blocks.push(match span {
268
275
Span::Quote(_) => Block::Reply(inner),
@@ -278,7 +285,7 @@ pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {
278
285
flush(&mut current, &mut blocks, Block::Paragraph);
279
286
let items: Vec<Vec<Block>> = items
280
287
.iter()
281
.map(|item| layout_blocks(item))
288
.map(|item| layout_blocks_with(item, false))
282
289
.filter(|item| !item.is_empty())
283
290
.collect();
284
291
if !items.is_empty() {
@@ -316,6 +323,12 @@ pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {
316
323
flush(&mut current, &mut blocks, Block::Paragraph);
317
324
blocks.push(Block::Rule);
318
325
}
326
Span::Image { hosted_content_url } if split_images => {
327
flush(&mut current, &mut blocks, Block::Paragraph);
328
blocks.push(Block::Image {
329
url: hosted_content_url.clone(),
330
});
331
}
319
332
other => append_inline(
320
333
std::slice::from_ref(other),
321
334
StyleFlags::default(),
@@ -338,7 +351,7 @@ fn inline_of(spans: &[Span]) -> Inline {
338
351
fn flush(current: &mut Inline, blocks: &mut Vec<Block>, make: fn(Inline) -> Block) {
339
352
let mut inline = std::mem::take(current);
340
353
inline.trim_end();
341
let leading = inline.text.len() - inline.text.trim_start_matches('\n').len();
354
let leading = inline.text.len() - inline.text.trim_start().len();
342
355
if leading > 0 {
343
356
inline.text.drain(..leading);
344
357
inline.segments.retain_mut(|segment| {
@@ -827,39 +840,99 @@ mod tests {
827
840
assert_eq!(inline.plain_text(), "run x. y");
828
841
}
829
842
843
fn image(url: &str) -> Span {
844
Span::Image {
845
hosted_content_url: url.into(),
846
}
847
}
848
849
#[test]
850
fn top_level_image_is_its_own_block() {
851
assert_eq!(
852
layout_blocks(&[image("u")]),
853
vec![Block::Image { url: "u".into() }]
854
);
855
}
856
857
#[test]
858
fn image_splits_the_paragraph_at_its_position() {
859
let blocks = layout_blocks(&[text("a "), image("u"), text(" b")]);
860
assert_eq!(
861
blocks,
862
vec![
863
Block::Paragraph(Inline::plain("a")),
864
Block::Image { url: "u".into() },
865
Block::Paragraph(Inline::plain("b")),
866
]
867
);
868
}
869
830
870
#[test]
831
fn image_becomes_placeholder() {
832
let blocks = layout_blocks(&[Span::Image {
833
hosted_content_url: "u".into(),
871
fn image_inside_a_list_keeps_the_placeholder() {
872
let blocks = layout_blocks(&[Span::List {
873
ordered: false,
874
start: 1,
875
items: vec![vec![text("x "), image("u")]],
834
876
}]);
835
877
assert_eq!(
836
878
blocks,
837
vec![Block::Paragraph(Inline::plain(IMAGE_PLACEHOLDER))]
879
vec![Block::List {
880
ordered: false,
881
start: 1,
882
items: vec![vec![Block::Paragraph(Inline::plain("x [image]"))]],
883
}]
884
);
885
}
886
887
#[test]
888
fn image_inside_a_quote_keeps_the_placeholder() {
889
let blocks = layout_blocks(&[Span::BlockQuote(vec![image("u")])]);
890
assert_eq!(
891
blocks,
892
vec![Block::Quote(vec![Block::Paragraph(Inline::plain(
893
IMAGE_PLACEHOLDER
894
))])]
838
895
);
839
896
}
840
897
898
#[test]
899
fn image_blocks_have_no_text() {
900
let block = Block::Image { url: "u".into() };
901
assert_eq!(block.markdown(), None);
902
assert_eq!(block.first_line(), None);
903
}
904
841
905
#[test]
842
906
fn stripping_placeholders_keeps_the_text_around_them() {
843
let blocks = layout_blocks(&[
844
text("look "),
845
Span::Bold(vec![text("here")]),
846
Span::LineBreak,
847
Span::Image {
848
hosted_content_url: "u".into(),
849
},
850
]);
907
let blocks = layout_blocks(&[Span::List {
908
ordered: false,
909
start: 1,
910
items: vec![vec![
911
text("look "),
912
Span::Bold(vec![text("here")]),
913
Span::LineBreak,
914
image("u"),
915
]],
916
}]);
851
917
let stripped = strip_image_placeholders(blocks);
852
let Block::Paragraph(inline) = &stripped[0] else {
918
let Block::List { items, .. } = &stripped[0] else {
919
panic!("list expected")
920
};
921
let Block::Paragraph(inline) = &items[0][0] else {
853
922
panic!("paragraph expected")
854
923
};
855
924
assert_eq!(inline.text, "look here");
856
925
assert!(inline.segments.last().unwrap().style.bold);
857
let only_image = layout_blocks(&[Span::Image {
858
hosted_content_url: "u".into(),
859
}]);
926
let only_image = vec![Block::Paragraph(Inline::plain(IMAGE_PLACEHOLDER))];
860
927
assert!(strip_image_placeholders(only_image).is_empty());
861
928
}
862
929
930
#[test]
931
fn stripping_placeholders_keeps_image_blocks() {
932
let blocks = vec![Block::Image { url: "u".into() }];
933
assert_eq!(strip_image_placeholders(blocks.clone()), blocks);
934
}
935
863
936
#[test]
864
937
fn line_break_stays_inside_paragraph() {
865
938
let blocks = layout_blocks(&[text("a"), Span::LineBreak, text("b")]);
@@ -146,6 +146,9 @@ pub enum Block {146
rows: Vec<Vec<Inline>>,146
rows: Vec<Vec<Inline>>,147
},147
},148
Rule,148
Rule,149
Image {150
url: String,151
},149
}152
}150
153
151
impl Block {154
impl Block {@@ -187,7 +190,7 @@ impl Block {187
.join("\n"),190
.join("\n"),188
),191
),189
Block::Quote(children) => Some(join(children)),192
Block::Quote(children) => Some(join(children)),190
Block::Reply(_) | Block::Rule => None,193
Block::Reply(_) | Block::Rule | Block::Image { .. } => None,191
}194
}192
}195
}193
196
@@ -198,7 +201,7 @@ impl Block {198
Block::List { items, .. } => items.first()?.iter().find_map(Block::first_line),201
Block::List { items, .. } => items.first()?.iter().find_map(Block::first_line),199
Block::Table { rows, .. } => Some(rows.first()?.first()?.plain_text()),202
Block::Table { rows, .. } => Some(rows.first()?.first()?.plain_text()),200
Block::Quote(children) => children.iter().find_map(Block::first_line),203
Block::Quote(children) => children.iter().find_map(Block::first_line),201
Block::Reply(_) | Block::Rule => None,204
Block::Reply(_) | Block::Rule | Block::Image { .. } => None,202
}205
}203
}206
}204
207
@@ -249,6 +252,10 @@ pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {249
}252
}250
253
251
pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {254
pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {255
layout_blocks_with(spans, true)256
}257
258
fn layout_blocks_with(spans: &[Span], split_images: bool) -> Vec<Block> {252
let mut blocks = Vec::new();259
let mut blocks = Vec::new();253
let mut current = Inline::default();260
let mut current = Inline::default();254
for span in spans {261
for span in spans {@@ -262,7 +269,7 @@ pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {262
}269
}263
Span::Quote(children) | Span::BlockQuote(children) => {270
Span::Quote(children) | Span::BlockQuote(children) => {264
flush(&mut current, &mut blocks, Block::Paragraph);271
flush(&mut current, &mut blocks, Block::Paragraph);265
let inner = layout_blocks(children);272
let inner = layout_blocks_with(children, false);266
if !inner.is_empty() {273
if !inner.is_empty() {267
blocks.push(match span {274
blocks.push(match span {268
Span::Quote(_) => Block::Reply(inner),275
Span::Quote(_) => Block::Reply(inner),@@ -278,7 +285,7 @@ pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {278
flush(&mut current, &mut blocks, Block::Paragraph);285
flush(&mut current, &mut blocks, Block::Paragraph);279
let items: Vec<Vec<Block>> = items286
let items: Vec<Vec<Block>> = items280
.iter()287
.iter()281
.map(|item| layout_blocks(item))288
.map(|item| layout_blocks_with(item, false))282
.filter(|item| !item.is_empty())289
.filter(|item| !item.is_empty())283
.collect();290
.collect();284
if !items.is_empty() {291
if !items.is_empty() {@@ -316,6 +323,12 @@ pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {316
flush(&mut current, &mut blocks, Block::Paragraph);323
flush(&mut current, &mut blocks, Block::Paragraph);317
blocks.push(Block::Rule);324
blocks.push(Block::Rule);318
}325
}326
Span::Image { hosted_content_url } if split_images => {327
flush(&mut current, &mut blocks, Block::Paragraph);328
blocks.push(Block::Image {329
url: hosted_content_url.clone(),330
});331
}319
other => append_inline(332
other => append_inline(320
std::slice::from_ref(other),333
std::slice::from_ref(other),321
StyleFlags::default(),334
StyleFlags::default(),@@ -338,7 +351,7 @@ fn inline_of(spans: &[Span]) -> Inline {338
fn flush(current: &mut Inline, blocks: &mut Vec<Block>, make: fn(Inline) -> Block) {351
fn flush(current: &mut Inline, blocks: &mut Vec<Block>, make: fn(Inline) -> Block) {339
let mut inline = std::mem::take(current);352
let mut inline = std::mem::take(current);340
inline.trim_end();353
inline.trim_end();341
let leading = inline.text.len() - inline.text.trim_start_matches('\n').len();354
let leading = inline.text.len() - inline.text.trim_start().len();342
if leading > 0 {355
if leading > 0 {343
inline.text.drain(..leading);356
inline.text.drain(..leading);344
inline.segments.retain_mut(|segment| {357
inline.segments.retain_mut(|segment| {@@ -827,39 +840,99 @@ mod tests {827
assert_eq!(inline.plain_text(), "run x. y");840
assert_eq!(inline.plain_text(), "run x. y");828
}841
}829
842
843
fn image(url: &str) -> Span {844
Span::Image {845
hosted_content_url: url.into(),846
}847
}848
849
#[test]850
fn top_level_image_is_its_own_block() {851
assert_eq!(852
layout_blocks(&[image("u")]),853
vec![Block::Image { url: "u".into() }]854
);855
}856
857
#[test]858
fn image_splits_the_paragraph_at_its_position() {859
let blocks = layout_blocks(&[text("a "), image("u"), text(" b")]);860
assert_eq!(861
blocks,862
vec![863
Block::Paragraph(Inline::plain("a")),864
Block::Image { url: "u".into() },865
Block::Paragraph(Inline::plain("b")),866
]867
);868
}869
830
#[test]870
#[test]831
fn image_becomes_placeholder() {871
fn image_inside_a_list_keeps_the_placeholder() {832
let blocks = layout_blocks(&[Span::Image {872
let blocks = layout_blocks(&[Span::List {833
hosted_content_url: "u".into(),873
ordered: false,874
start: 1,875
items: vec![vec![text("x "), image("u")]],834
}]);876
}]);835
assert_eq!(877
assert_eq!(836
blocks,878
blocks,837
vec![Block::Paragraph(Inline::plain(IMAGE_PLACEHOLDER))]879
vec![Block::List {880
ordered: false,881
start: 1,882
items: vec![vec![Block::Paragraph(Inline::plain("x [image]"))]],883
}]884
);885
}886
887
#[test]888
fn image_inside_a_quote_keeps_the_placeholder() {889
let blocks = layout_blocks(&[Span::BlockQuote(vec![image("u")])]);890
assert_eq!(891
blocks,892
vec![Block::Quote(vec![Block::Paragraph(Inline::plain(893
IMAGE_PLACEHOLDER894
))])]838
);895
);839
}896
}840
897
898
#[test]899
fn image_blocks_have_no_text() {900
let block = Block::Image { url: "u".into() };901
assert_eq!(block.markdown(), None);902
assert_eq!(block.first_line(), None);903
}904
841
#[test]905
#[test]842
fn stripping_placeholders_keeps_the_text_around_them() {906
fn stripping_placeholders_keeps_the_text_around_them() {843
let blocks = layout_blocks(&[907
let blocks = layout_blocks(&[Span::List {844
text("look "),908
ordered: false,845
Span::Bold(vec![text("here")]),909
start: 1,846
Span::LineBreak,910
items: vec![vec![847
Span::Image {911
text("look "),848
hosted_content_url: "u".into(),912
Span::Bold(vec![text("here")]),849
},913
Span::LineBreak,850
]);914
image("u"),915
]],916
}]);851
let stripped = strip_image_placeholders(blocks);917
let stripped = strip_image_placeholders(blocks);852
let Block::Paragraph(inline) = &stripped[0] else {918
let Block::List { items, .. } = &stripped[0] else {919
panic!("list expected")920
};921
let Block::Paragraph(inline) = &items[0][0] else {853
panic!("paragraph expected")922
panic!("paragraph expected")854
};923
};855
assert_eq!(inline.text, "look here");924
assert_eq!(inline.text, "look here");856
assert!(inline.segments.last().unwrap().style.bold);925
assert!(inline.segments.last().unwrap().style.bold);857
let only_image = layout_blocks(&[Span::Image {926
let only_image = vec![Block::Paragraph(Inline::plain(IMAGE_PLACEHOLDER))];858
hosted_content_url: "u".into(),859
}]);860
assert!(strip_image_placeholders(only_image).is_empty());927
assert!(strip_image_placeholders(only_image).is_empty());861
}928
}862
929
930
#[test]931
fn stripping_placeholders_keeps_image_blocks() {932
let blocks = vec![Block::Image { url: "u".into() }];933
assert_eq!(strip_image_placeholders(blocks.clone()), blocks);934
}935
863
#[test]936
#[test]864
fn line_break_stays_inside_paragraph() {937
fn line_break_stays_inside_paragraph() {865
let blocks = layout_blocks(&[text("a"), Span::LineBreak, text("b")]);938
let blocks = layout_blocks(&[text("a"), Span::LineBreak, text("b")]);@@ -69,6 +69,7 @@ fn render_block(block: &Block, id: String, own: bool, depth: usize, cx: &App) ->
69
69
start,
70
70
items,
71
71
} => render_list(*ordered, *start, items, &id, own, depth, cx),
72
Block::Image { .. } => div().into_any_element(),
72
73
Block::Table { header, rows } => render_table(*header, rows, &id, own, cx),
73
74
Block::Rule => div()
74
75
.w_full()
@@ -69,6 +69,7 @@ fn render_block(block: &Block, id: String, own: bool, depth: usize, cx: &App) ->69
start,69
start,70
items,70
items,71
} => render_list(*ordered, *start, items, &id, own, depth, cx),71
} => render_list(*ordered, *start, items, &id, own, depth, cx),72
Block::Image { .. } => div().into_any_element(),72
Block::Table { header, rows } => render_table(*header, rows, &id, own, cx),73
Block::Table { header, rows } => render_table(*header, rows, &id, own, cx),73
Block::Rule => div()74
Block::Rule => div()74
.w_full()75
.w_full()@@ -10,6 +10,7 @@ use super::widgets::{icon, symbol};
10
10
use crate::data::Directory;
11
11
use crate::downloads::{self, DownloadState};
12
12
use crate::format;
13
use crate::render::{Block, render_blocks};
13
14
use crate::rows::LocalImage;
14
15
use crate::theme;
15
16
@@ -23,6 +24,8 @@ const FILE_BADGE_SIZE: f32 = 34.;
23
24
const SAVE_BUTTON_SIZE: f32 = 28.;
24
25
const SAVE_BUTTON_RADIUS: f32 = 6.;
25
26
const SAVE_PROGRESS_HEIGHT: f32 = 2.;
27
const LOCAL_IMAGE_PREFIX: &str = "../hostedContents/";
28
const LOCAL_IMAGE_SUFFIX: &str = "/$value";
26
29
27
30
pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;
28
31
@@ -280,7 +283,87 @@ fn file_view(
280
283
.into_any_element()
281
284
}
282
285
286
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
287
enum Placement {
288
Remote(usize),
289
Local(usize),
290
}
291
292
fn local_image_index(url: &str) -> Option<usize> {
293
url.strip_prefix(LOCAL_IMAGE_PREFIX)?
294
.strip_suffix(LOCAL_IMAGE_SUFFIX)?
295
.parse::<usize>()
296
.ok()?
297
.checked_sub(1)
298
}
299
300
fn placement(url: &str, images: &[ImageRef], local_count: usize) -> Option<Placement> {
301
if let Some(index) = images.iter().position(|image| image.url == url) {
302
return Some(Placement::Remote(index));
303
}
304
local_image_index(url)
305
.filter(|index| *index < local_count)
306
.map(Placement::Local)
307
}
308
309
fn placements(blocks: &[Block], images: &[ImageRef], local_count: usize) -> Vec<Placement> {
310
blocks
311
.iter()
312
.filter_map(|block| match block {
313
Block::Image { url } => placement(url, images, local_count),
314
_ => None,
315
})
316
.collect()
317
}
318
319
pub fn message_body(
320
blocks: &[Block],
321
images: &[ImageRef],
322
local_images: &[LocalImage],
323
id: &str,
324
own: bool,
325
directory: &Directory,
326
cx: &App,
327
) -> Vec<AnyElement> {
328
if !blocks
329
.iter()
330
.any(|block| matches!(block, Block::Image { .. }))
331
{
332
return vec![render_blocks(blocks, id, own, cx)];
333
}
334
let mut elements = Vec::new();
335
let mut run_start = 0;
336
let render_run = |start: usize, end: usize, elements: &mut Vec<AnyElement>| {
337
if end > start {
338
let part_id = format!("{id}-part-{start}");
339
elements.push(render_blocks(&blocks[start..end], &part_id, own, cx));
340
}
341
};
342
for (index, block) in blocks.iter().enumerate() {
343
let Block::Image { url } = block else {
344
continue;
345
};
346
render_run(run_start, index, &mut elements);
347
run_start = index + 1;
348
match placement(url, images, local_images.len()) {
349
Some(Placement::Remote(position)) => elements.push(image_view(
350
&images[position],
351
format!("{id}-image-{position}"),
352
directory,
353
)),
354
Some(Placement::Local(position)) => elements.push(local_image_view(
355
&local_images[position],
356
format!("{id}-local-image-{position}"),
357
)),
358
None => {}
359
}
360
}
361
render_run(run_start, blocks.len(), &mut elements);
362
elements
363
}
364
283
365
pub fn attachments_view(
366
blocks: &[Block],
284
367
images: &[ImageRef],
285
368
local_images: &[LocalImage],
286
369
files: &[FileCard],
@@ -288,7 +371,18 @@ pub fn attachments_view(
288
371
directory: &Directory,
289
372
file_actions: Option<&FileActions>,
290
373
) -> Option<Div> {
291
if images.is_empty() && local_images.is_empty() && files.is_empty() {
374
let placed = placements(blocks, images, local_images.len());
375
let unplaced_images: Vec<(usize, &ImageRef)> = images
376
.iter()
377
.enumerate()
378
.filter(|(index, _)| !placed.contains(&Placement::Remote(*index)))
379
.collect();
380
let unplaced_local: Vec<(usize, &LocalImage)> = local_images
381
.iter()
382
.enumerate()
383
.filter(|(index, _)| !placed.contains(&Placement::Local(*index)))
384
.collect();
385
if unplaced_images.is_empty() && unplaced_local.is_empty() && files.is_empty() {
292
386
return None;
293
387
}
294
388
Some(
@@ -296,12 +390,12 @@ pub fn attachments_view(
296
390
.gap(px(6.))
297
391
.items_start()
298
392
.children(
299
images.iter().enumerate().map(|(index, image)| {
393
unplaced_images.into_iter().map(|(index, image)| {
300
394
image_view(image, format!("{id}-image-{index}"), directory)
301
395
}),
302
396
)
303
397
.children(
304
local_images.iter().enumerate().map(|(index, image)| {
398
unplaced_local.into_iter().map(|(index, image)| {
305
399
local_image_view(image, format!("{id}-local-image-{index}"))
306
400
}),
307
401
)
@@ -313,8 +407,48 @@ pub fn attachments_view(
313
407
314
408
#[cfg(test)]
315
409
mod tests {
316
use super::{IMAGE_FALLBACK, file_subtitle, fit_image};
317
use teams_core::{FileCard, FileKind};
410
use super::{
411
IMAGE_FALLBACK, Placement, file_subtitle, fit_image, local_image_index, placement,
412
placements,
413
};
414
use crate::render::Block;
415
use teams_core::{FileCard, FileKind, ImageRef};
416
417
fn image_ref(url: &str) -> ImageRef {
418
ImageRef {
419
id: url.into(),
420
url: url.into(),
421
width: None,
422
height: None,
423
}
424
}
425
426
fn image_block(url: &str) -> Block {
427
Block::Image { url: url.into() }
428
}
429
430
#[test]
431
fn hosted_content_urls_map_to_zero_based_local_indices() {
432
assert_eq!(local_image_index("../hostedContents/2/$value"), Some(1));
433
assert_eq!(local_image_index("../hostedContents/0/$value"), None);
434
assert_eq!(local_image_index("https://x/y"), None);
435
}
436
437
#[test]
438
fn placed_images_are_found_by_url_before_local_indices() {
439
let images = [image_ref("a"), image_ref("b")];
440
let blocks = [
441
image_block("b"),
442
image_block("../hostedContents/2/$value"),
443
image_block("../hostedContents/9/$value"),
444
image_block("missing"),
445
];
446
assert_eq!(
447
placements(&blocks, &images, 2),
448
vec![Placement::Remote(1), Placement::Local(1)]
449
);
450
assert_eq!(placement("a", &images, 0), Some(Placement::Remote(0)));
451
}
318
452
319
453
#[test]
320
454
fn wide_images_shrink_to_the_max_width_keeping_aspect() {
@@ -10,6 +10,7 @@ use super::widgets::{icon, symbol};10
use crate::data::Directory;10
use crate::data::Directory;11
use crate::downloads::{self, DownloadState};11
use crate::downloads::{self, DownloadState};12
use crate::format;12
use crate::format;13
use crate::render::{Block, render_blocks};13
use crate::rows::LocalImage;14
use crate::rows::LocalImage;14
use crate::theme;15
use crate::theme;15
16
@@ -23,6 +24,8 @@ const FILE_BADGE_SIZE: f32 = 34.;23
const SAVE_BUTTON_SIZE: f32 = 28.;24
const SAVE_BUTTON_SIZE: f32 = 28.;24
const SAVE_BUTTON_RADIUS: f32 = 6.;25
const SAVE_BUTTON_RADIUS: f32 = 6.;25
const SAVE_PROGRESS_HEIGHT: f32 = 2.;26
const SAVE_PROGRESS_HEIGHT: f32 = 2.;27
const LOCAL_IMAGE_PREFIX: &str = "../hostedContents/";28
const LOCAL_IMAGE_SUFFIX: &str = "/$value";26
29
27
pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;30
pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;28
31
@@ -280,7 +283,87 @@ fn file_view(280
.into_any_element()283
.into_any_element()281
}284
}282
285
286
#[derive(Debug, Clone, Copy, PartialEq, Eq)]287
enum Placement {288
Remote(usize),289
Local(usize),290
}291
292
fn local_image_index(url: &str) -> Option<usize> {293
url.strip_prefix(LOCAL_IMAGE_PREFIX)?294
.strip_suffix(LOCAL_IMAGE_SUFFIX)?295
.parse::<usize>()296
.ok()?297
.checked_sub(1)298
}299
300
fn placement(url: &str, images: &[ImageRef], local_count: usize) -> Option<Placement> {301
if let Some(index) = images.iter().position(|image| image.url == url) {302
return Some(Placement::Remote(index));303
}304
local_image_index(url)305
.filter(|index| *index < local_count)306
.map(Placement::Local)307
}308
309
fn placements(blocks: &[Block], images: &[ImageRef], local_count: usize) -> Vec<Placement> {310
blocks311
.iter()312
.filter_map(|block| match block {313
Block::Image { url } => placement(url, images, local_count),314
_ => None,315
})316
.collect()317
}318
319
pub fn message_body(320
blocks: &[Block],321
images: &[ImageRef],322
local_images: &[LocalImage],323
id: &str,324
own: bool,325
directory: &Directory,326
cx: &App,327
) -> Vec<AnyElement> {328
if !blocks329
.iter()330
.any(|block| matches!(block, Block::Image { .. }))331
{332
return vec![render_blocks(blocks, id, own, cx)];333
}334
let mut elements = Vec::new();335
let mut run_start = 0;336
let render_run = |start: usize, end: usize, elements: &mut Vec<AnyElement>| {337
if end > start {338
let part_id = format!("{id}-part-{start}");339
elements.push(render_blocks(&blocks[start..end], &part_id, own, cx));340
}341
};342
for (index, block) in blocks.iter().enumerate() {343
let Block::Image { url } = block else {344
continue;345
};346
render_run(run_start, index, &mut elements);347
run_start = index + 1;348
match placement(url, images, local_images.len()) {349
Some(Placement::Remote(position)) => elements.push(image_view(350
&images[position],351
format!("{id}-image-{position}"),352
directory,353
)),354
Some(Placement::Local(position)) => elements.push(local_image_view(355
&local_images[position],356
format!("{id}-local-image-{position}"),357
)),358
None => {}359
}360
}361
render_run(run_start, blocks.len(), &mut elements);362
elements363
}364
283
pub fn attachments_view(365
pub fn attachments_view(366
blocks: &[Block],284
images: &[ImageRef],367
images: &[ImageRef],285
local_images: &[LocalImage],368
local_images: &[LocalImage],286
files: &[FileCard],369
files: &[FileCard],@@ -288,7 +371,18 @@ pub fn attachments_view(288
directory: &Directory,371
directory: &Directory,289
file_actions: Option<&FileActions>,372
file_actions: Option<&FileActions>,290
) -> Option<Div> {373
) -> Option<Div> {291
if images.is_empty() && local_images.is_empty() && files.is_empty() {374
let placed = placements(blocks, images, local_images.len());375
let unplaced_images: Vec<(usize, &ImageRef)> = images376
.iter()377
.enumerate()378
.filter(|(index, _)| !placed.contains(&Placement::Remote(*index)))379
.collect();380
let unplaced_local: Vec<(usize, &LocalImage)> = local_images381
.iter()382
.enumerate()383
.filter(|(index, _)| !placed.contains(&Placement::Local(*index)))384
.collect();385
if unplaced_images.is_empty() && unplaced_local.is_empty() && files.is_empty() {292
return None;386
return None;293
}387
}294
Some(388
Some(@@ -296,12 +390,12 @@ pub fn attachments_view(296
.gap(px(6.))390
.gap(px(6.))297
.items_start()391
.items_start()298
.children(392
.children(299
images.iter().enumerate().map(|(index, image)| {393
unplaced_images.into_iter().map(|(index, image)| {300
image_view(image, format!("{id}-image-{index}"), directory)394
image_view(image, format!("{id}-image-{index}"), directory)301
}),395
}),302
)396
)303
.children(397
.children(304
local_images.iter().enumerate().map(|(index, image)| {398
unplaced_local.into_iter().map(|(index, image)| {305
local_image_view(image, format!("{id}-local-image-{index}"))399
local_image_view(image, format!("{id}-local-image-{index}"))306
}),400
}),307
)401
)@@ -313,8 +407,48 @@ pub fn attachments_view(313
407
314
#[cfg(test)]408
#[cfg(test)]315
mod tests {409
mod tests {316
use super::{IMAGE_FALLBACK, file_subtitle, fit_image};410
use super::{317
use teams_core::{FileCard, FileKind};411
IMAGE_FALLBACK, Placement, file_subtitle, fit_image, local_image_index, placement,412
placements,413
};414
use crate::render::Block;415
use teams_core::{FileCard, FileKind, ImageRef};416
417
fn image_ref(url: &str) -> ImageRef {418
ImageRef {419
id: url.into(),420
url: url.into(),421
width: None,422
height: None,423
}424
}425
426
fn image_block(url: &str) -> Block {427
Block::Image { url: url.into() }428
}429
430
#[test]431
fn hosted_content_urls_map_to_zero_based_local_indices() {432
assert_eq!(local_image_index("../hostedContents/2/$value"), Some(1));433
assert_eq!(local_image_index("../hostedContents/0/$value"), None);434
assert_eq!(local_image_index("https://x/y"), None);435
}436
437
#[test]438
fn placed_images_are_found_by_url_before_local_indices() {439
let images = [image_ref("a"), image_ref("b")];440
let blocks = [441
image_block("b"),442
image_block("../hostedContents/2/$value"),443
image_block("../hostedContents/9/$value"),444
image_block("missing"),445
];446
assert_eq!(447
placements(&blocks, &images, 2),448
vec![Placement::Remote(1), Placement::Local(1)]449
);450
assert_eq!(placement("a", &images, 0), Some(Placement::Remote(0)));451
}318
452
319
#[test]453
#[test]320
fn wide_images_shrink_to_the_max_width_keeping_aspect() {454
fn wide_images_shrink_to_the_max_width_keeping_aspect() {@@ -5,14 +5,14 @@ use gpui_kit::prelude::FluentBuilder as _;
5
5
use gpui_kit::*;
6
6
use std::time::Duration;
7
7
8
use super::attachments::{FileActions, attachments_view};
8
use super::attachments::{FileActions, attachments_view, message_body};
9
9
use super::avatar::{member_stack, person_avatar};
10
10
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
11
11
use super::reaction_picker::PickHandler;
12
12
use super::reaction_pills::{ReactionControls, reaction_pills};
13
13
use super::widgets::{icon, symbol};
14
14
use crate::data::Directory;
15
use crate::render::{Block, render_blocks};
15
use crate::render::Block;
16
16
use crate::rows::{Delivery, MessageRow, Receipt, Skeleton, bubble_corners};
17
17
use crate::sidebar_model::DELETED_PREVIEW;
18
18
use crate::theme;
@@ -129,14 +129,18 @@ fn bubble(
129
129
};
130
130
let meta_inline = has_text(row) && padded_blocks.is_some();
131
131
if has_text(row) {
132
content = content.child(render_blocks(
132
content = content.children(message_body(
133
133
padded_blocks.as_deref().unwrap_or(&row.blocks),
134
&row.images,
135
&row.local_images,
134
136
&format!("message-{index}"),
135
137
own,
138
directory,
136
139
cx,
137
140
));
138
141
}
139
142
content = content.children(attachments_view(
143
&row.blocks,
140
144
&row.images,
141
145
&row.local_images,
142
146
&row.files,
@@ -449,19 +453,24 @@ fn post_card(
449
453
} else {
450
454
if has_text(row) {
451
455
body = body.child(
452
div()
456
v_flex()
457
.gap(px(6.))
453
458
.text_size(px(BODY_SIZE))
454
459
.line_height(relative(1.45))
455
460
.text_color(theme::text_strong())
456
.child(render_blocks(
461
.children(message_body(
457
462
&row.blocks,
463
&row.images,
464
&row.local_images,
458
465
&format!("message-{index}"),
459
466
false,
467
directory,
460
468
cx,
461
469
)),
462
470
);
463
471
}
464
472
body = body.children(attachments_view(
473
&row.blocks,
465
474
&row.images,
466
475
&row.local_images,
467
476
&row.files,
@@ -5,14 +5,14 @@ use gpui_kit::prelude::FluentBuilder as _;5
use gpui_kit::*;5
use gpui_kit::*;6
use std::time::Duration;6
use std::time::Duration;7
7
8
use super::attachments::{FileActions, attachments_view};8
use super::attachments::{FileActions, attachments_view, message_body};9
use super::avatar::{member_stack, person_avatar};9
use super::avatar::{member_stack, person_avatar};10
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};10
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};11
use super::reaction_picker::PickHandler;11
use super::reaction_picker::PickHandler;12
use super::reaction_pills::{ReactionControls, reaction_pills};12
use super::reaction_pills::{ReactionControls, reaction_pills};13
use super::widgets::{icon, symbol};13
use super::widgets::{icon, symbol};14
use crate::data::Directory;14
use crate::data::Directory;15
use crate::render::{Block, render_blocks};15
use crate::render::Block;16
use crate::rows::{Delivery, MessageRow, Receipt, Skeleton, bubble_corners};16
use crate::rows::{Delivery, MessageRow, Receipt, Skeleton, bubble_corners};17
use crate::sidebar_model::DELETED_PREVIEW;17
use crate::sidebar_model::DELETED_PREVIEW;18
use crate::theme;18
use crate::theme;@@ -129,14 +129,18 @@ fn bubble(129
};129
};130
let meta_inline = has_text(row) && padded_blocks.is_some();130
let meta_inline = has_text(row) && padded_blocks.is_some();131
if has_text(row) {131
if has_text(row) {132
content = content.child(render_blocks(132
content = content.children(message_body(133
padded_blocks.as_deref().unwrap_or(&row.blocks),133
padded_blocks.as_deref().unwrap_or(&row.blocks),134
&row.images,135
&row.local_images,134
&format!("message-{index}"),136
&format!("message-{index}"),135
own,137
own,138
directory,136
cx,139
cx,137
));140
));138
}141
}139
content = content.children(attachments_view(142
content = content.children(attachments_view(143
&row.blocks,140
&row.images,144
&row.images,141
&row.local_images,145
&row.local_images,142
&row.files,146
&row.files,@@ -449,19 +453,24 @@ fn post_card(449
} else {453
} else {450
if has_text(row) {454
if has_text(row) {451
body = body.child(455
body = body.child(452
div()456
v_flex()457
.gap(px(6.))453
.text_size(px(BODY_SIZE))458
.text_size(px(BODY_SIZE))454
.line_height(relative(1.45))459
.line_height(relative(1.45))455
.text_color(theme::text_strong())460
.text_color(theme::text_strong())456
.child(render_blocks(461
.children(message_body(457
&row.blocks,462
&row.blocks,463
&row.images,464
&row.local_images,458
&format!("message-{index}"),465
&format!("message-{index}"),459
false,466
false,467
directory,460
cx,468
cx,461
)),469
)),462
);470
);463
}471
}464
body = body.children(attachments_view(472
body = body.children(attachments_view(473
&row.blocks,465
&row.images,474
&row.images,466
&row.local_images,475
&row.local_images,467
&row.files,476
&row.files,