feat(messages): render org emoji in message bodies
- <customemoji> tags were dropped, the emoji vanished from the text - Now parsed into a CustomEmoji span and painted inline at 20 px from the hosted content image - Copy, previews and plain text use :name: - Deviation: animated org emoji show as a still image Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -4,6 +4,7 @@ use teams_core::{FontSize, PROFILE_LINK_PREFIX, Span};
4
4
5
5
pub const IMAGE_PLACEHOLDER: &str = "[image]";
6
6
pub const CODE_PADDING: &str = "\u{2004}";
7
pub const EMOJI_PLACEHOLDER: &str = "\u{25a0}\u{25a0}";
7
8
const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];
8
9
const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";
9
10
const BASE_FONT_PIXELS: f32 = 14.;
@@ -71,6 +72,7 @@ pub struct Segment {
71
72
pub range: Range<usize>,
72
73
pub style: StyleFlags,
73
74
pub link: Option<String>,
75
pub emoji: Option<String>,
74
76
}
75
77
76
78
#[derive(Debug, Clone, Default, PartialEq, Eq)]
@@ -87,6 +89,10 @@ impl Inline {
87
89
}
88
90
89
91
fn push(&mut self, text: &str, style: StyleFlags, link: Option<&str>) {
92
self.push_part(text, style, link, None);
93
}
94
95
fn push_part(&mut self, text: &str, style: StyleFlags, link: Option<&str>, emoji: Option<&str>) {
90
96
if text.is_empty() {
91
97
return;
92
98
}
@@ -94,6 +100,8 @@ impl Inline {
94
100
self.text.push_str(text);
95
101
let end = self.text.len();
96
102
if let Some(last) = self.segments.last_mut()
103
&& emoji.is_none()
104
&& last.emoji.is_none()
97
105
&& last.style == style
98
106
&& last.link.as_deref() == link
99
107
&& last.range.end == start
@@ -105,11 +113,23 @@ impl Inline {
105
113
range: start..end,
106
114
style,
107
115
link: link.map(str::to_owned),
116
emoji: emoji.map(str::to_owned),
108
117
});
109
118
}
110
119
120
pub fn emoji(&self) -> Vec<(Range<usize>, String)> {
121
self.segments
122
.iter()
123
.filter_map(|segment| Some((segment.range.clone(), segment.emoji.clone()?)))
124
.collect()
125
}
126
111
127
pub fn plain_text(&self) -> String {
112
self.text.replace(CODE_PADDING, "")
128
self.segments
129
.iter()
130
.filter(|segment| segment.emoji.is_none())
131
.map(|segment| self.text[segment.range.clone()].replace(CODE_PADDING, ""))
132
.collect()
113
133
}
114
134
115
135
pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline {
@@ -128,7 +148,12 @@ impl Inline {
128
148
let start = segment.range.start.max(range.start);
129
149
let end = segment.range.end.min(range.end);
130
150
if start < end {
131
part.push(&self.text[start..end], segment.style, segment.link.as_deref());
151
part.push_part(
152
&self.text[start..end],
153
segment.style,
154
segment.link.as_deref(),
155
segment.emoji.as_deref(),
156
);
132
157
}
133
158
}
134
159
part
@@ -151,7 +176,7 @@ impl Inline {
151
176
let mut stripped = Inline::default();
152
177
for segment in &self.segments {
153
178
let text = self.text[segment.range.clone()].replace(needle, "");
154
stripped.push(&text, segment.style, segment.link.as_deref());
179
stripped.push_part(&text, segment.style, segment.link.as_deref(), segment.emoji.as_deref());
155
180
}
156
181
stripped.trim_end();
157
182
let leading = stripped.text.len() - stripped.text.trim_start().len();
@@ -160,7 +185,12 @@ impl Inline {
160
185
for segment in &stripped.segments {
161
186
let text = stripped.text[segment.range.clone()].to_owned();
162
187
let skip = leading.saturating_sub(segment.range.start).min(text.len());
163
trimmed.push(&text[skip..], segment.style, segment.link.as_deref());
188
trimmed.push_part(
189
&text[skip..],
190
segment.style,
191
segment.link.as_deref(),
192
segment.emoji.as_deref(),
193
);
164
194
}
165
195
return trimmed;
166
196
}
@@ -344,6 +374,30 @@ pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {
344
374
.collect()
345
375
}
346
376
377
pub fn emoji_urls(blocks: &[Block]) -> Vec<String> {
378
let mut urls: Vec<String> = Vec::new();
379
let mut add = |inline: &Inline| {
380
for (_, url) in inline.emoji() {
381
if !urls.contains(&url) {
382
urls.push(url);
383
}
384
}
385
};
386
let mut pending: Vec<&Block> = blocks.iter().collect();
387
while let Some(block) = pending.pop() {
388
match block {
389
Block::Paragraph(inline) | Block::Heading { inline, .. } => add(inline),
390
Block::Table { rows, .. } => rows.iter().flatten().for_each(&mut add),
391
Block::Reply { children, .. } | Block::Quote(children) | Block::Indent { children, .. } => {
392
pending.extend(children)
393
}
394
Block::List { items, .. } => pending.extend(items.iter().flatten()),
395
Block::Code { .. } | Block::CodeLine { .. } | Block::Rule | Block::Image { .. } => {}
396
}
397
}
398
urls
399
}
400
347
401
pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {
348
402
layout_blocks_with(spans, true, true)
349
403
}
@@ -720,6 +774,7 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu
720
774
}
721
775
}
722
776
Span::Image { .. } => out.push(IMAGE_PLACEHOLDER, style, link),
777
Span::CustomEmoji { url, .. } => out.push_part(EMOJI_PLACEHOLDER, style, link, Some(url)),
723
778
}
724
779
}
725
780
}
@@ -797,6 +852,26 @@ mod tests {
797
852
Span::Text(value.to_owned())
798
853
}
799
854
855
#[test]
856
fn org_emoji_sit_in_the_text_and_stay_out_of_copied_text() {
857
let emoji = |url: &str| Span::CustomEmoji {
858
name: "cat".into(),
859
url: url.into(),
860
};
861
let blocks = layout_blocks(&[text("hi "), emoji("a"), emoji("a"), text(" ok")]);
862
let Block::Paragraph(inline) = &blocks[0] else {
863
panic!("paragraph expected");
864
};
865
assert_eq!(inline.emoji().len(), 2);
866
assert_eq!(inline.plain_text(), "hi ok");
867
assert_eq!(emoji_urls(&blocks), vec!["a".to_owned()]);
868
let trailing = layout_blocks(&[text("bye "), emoji("b")]);
869
let Block::Paragraph(inline) = &trailing[0] else {
870
panic!("paragraph expected");
871
};
872
assert_eq!(inline.emoji().len(), 1);
873
}
874
800
875
#[test]
801
876
fn plain_text_is_one_paragraph() {
802
877
let blocks = layout_blocks(&[text("hello ")]);
@@ -4,6 +4,7 @@ use teams_core::{FontSize, PROFILE_LINK_PREFIX, Span};4
4
5
pub const IMAGE_PLACEHOLDER: &str = "[image]";5
pub const IMAGE_PLACEHOLDER: &str = "[image]";6
pub const CODE_PADDING: &str = "\u{2004}";6
pub const CODE_PADDING: &str = "\u{2004}";7
pub const EMOJI_PLACEHOLDER: &str = "\u{25a0}\u{25a0}";7
const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];8
const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];8
const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";9
const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";9
const BASE_FONT_PIXELS: f32 = 14.;10
const BASE_FONT_PIXELS: f32 = 14.;@@ -71,6 +72,7 @@ pub struct Segment {71
pub range: Range<usize>,72
pub range: Range<usize>,72
pub style: StyleFlags,73
pub style: StyleFlags,73
pub link: Option<String>,74
pub link: Option<String>,75
pub emoji: Option<String>,74
}76
}75
77
76
#[derive(Debug, Clone, Default, PartialEq, Eq)]78
#[derive(Debug, Clone, Default, PartialEq, Eq)]@@ -87,6 +89,10 @@ impl Inline {87
}89
}88
90
89
fn push(&mut self, text: &str, style: StyleFlags, link: Option<&str>) {91
fn push(&mut self, text: &str, style: StyleFlags, link: Option<&str>) {92
self.push_part(text, style, link, None);93
}94
95
fn push_part(&mut self, text: &str, style: StyleFlags, link: Option<&str>, emoji: Option<&str>) {90
if text.is_empty() {96
if text.is_empty() {91
return;97
return;92
}98
}@@ -94,6 +100,8 @@ impl Inline {94
self.text.push_str(text);100
self.text.push_str(text);95
let end = self.text.len();101
let end = self.text.len();96
if let Some(last) = self.segments.last_mut()102
if let Some(last) = self.segments.last_mut()103
&& emoji.is_none()104
&& last.emoji.is_none()97
&& last.style == style105
&& last.style == style98
&& last.link.as_deref() == link106
&& last.link.as_deref() == link99
&& last.range.end == start107
&& last.range.end == start@@ -105,11 +113,23 @@ impl Inline {105
range: start..end,113
range: start..end,106
style,114
style,107
link: link.map(str::to_owned),115
link: link.map(str::to_owned),116
emoji: emoji.map(str::to_owned),108
});117
});109
}118
}110
119
120
pub fn emoji(&self) -> Vec<(Range<usize>, String)> {121
self.segments122
.iter()123
.filter_map(|segment| Some((segment.range.clone(), segment.emoji.clone()?)))124
.collect()125
}126
111
pub fn plain_text(&self) -> String {127
pub fn plain_text(&self) -> String {112
self.text.replace(CODE_PADDING, "")128
self.segments129
.iter()130
.filter(|segment| segment.emoji.is_none())131
.map(|segment| self.text[segment.range.clone()].replace(CODE_PADDING, ""))132
.collect()113
}133
}114
134
115
pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline {135
pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline {@@ -128,7 +148,12 @@ impl Inline {128
let start = segment.range.start.max(range.start);148
let start = segment.range.start.max(range.start);129
let end = segment.range.end.min(range.end);149
let end = segment.range.end.min(range.end);130
if start < end {150
if start < end {131
part.push(&self.text[start..end], segment.style, segment.link.as_deref());151
part.push_part(152
&self.text[start..end],153
segment.style,154
segment.link.as_deref(),155
segment.emoji.as_deref(),156
);132
}157
}133
}158
}134
part159
part@@ -151,7 +176,7 @@ impl Inline {151
let mut stripped = Inline::default();176
let mut stripped = Inline::default();152
for segment in &self.segments {177
for segment in &self.segments {153
let text = self.text[segment.range.clone()].replace(needle, "");178
let text = self.text[segment.range.clone()].replace(needle, "");154
stripped.push(&text, segment.style, segment.link.as_deref());179
stripped.push_part(&text, segment.style, segment.link.as_deref(), segment.emoji.as_deref());155
}180
}156
stripped.trim_end();181
stripped.trim_end();157
let leading = stripped.text.len() - stripped.text.trim_start().len();182
let leading = stripped.text.len() - stripped.text.trim_start().len();@@ -160,7 +185,12 @@ impl Inline {160
for segment in &stripped.segments {185
for segment in &stripped.segments {161
let text = stripped.text[segment.range.clone()].to_owned();186
let text = stripped.text[segment.range.clone()].to_owned();162
let skip = leading.saturating_sub(segment.range.start).min(text.len());187
let skip = leading.saturating_sub(segment.range.start).min(text.len());163
trimmed.push(&text[skip..], segment.style, segment.link.as_deref());188
trimmed.push_part(189
&text[skip..],190
segment.style,191
segment.link.as_deref(),192
segment.emoji.as_deref(),193
);164
}194
}165
return trimmed;195
return trimmed;166
}196
}@@ -344,6 +374,30 @@ pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {344
.collect()374
.collect()345
}375
}346
376
377
pub fn emoji_urls(blocks: &[Block]) -> Vec<String> {378
let mut urls: Vec<String> = Vec::new();379
let mut add = |inline: &Inline| {380
for (_, url) in inline.emoji() {381
if !urls.contains(&url) {382
urls.push(url);383
}384
}385
};386
let mut pending: Vec<&Block> = blocks.iter().collect();387
while let Some(block) = pending.pop() {388
match block {389
Block::Paragraph(inline) | Block::Heading { inline, .. } => add(inline),390
Block::Table { rows, .. } => rows.iter().flatten().for_each(&mut add),391
Block::Reply { children, .. } | Block::Quote(children) | Block::Indent { children, .. } => {392
pending.extend(children)393
}394
Block::List { items, .. } => pending.extend(items.iter().flatten()),395
Block::Code { .. } | Block::CodeLine { .. } | Block::Rule | Block::Image { .. } => {}396
}397
}398
urls399
}400
347
pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {401
pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {348
layout_blocks_with(spans, true, true)402
layout_blocks_with(spans, true, true)349
}403
}@@ -720,6 +774,7 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu720
}774
}721
}775
}722
Span::Image { .. } => out.push(IMAGE_PLACEHOLDER, style, link),776
Span::Image { .. } => out.push(IMAGE_PLACEHOLDER, style, link),777
Span::CustomEmoji { url, .. } => out.push_part(EMOJI_PLACEHOLDER, style, link, Some(url)),723
}778
}724
}779
}725
}780
}@@ -797,6 +852,26 @@ mod tests {797
Span::Text(value.to_owned())852
Span::Text(value.to_owned())798
}853
}799
854
855
#[test]856
fn org_emoji_sit_in_the_text_and_stay_out_of_copied_text() {857
let emoji = |url: &str| Span::CustomEmoji {858
name: "cat".into(),859
url: url.into(),860
};861
let blocks = layout_blocks(&[text("hi "), emoji("a"), emoji("a"), text(" ok")]);862
let Block::Paragraph(inline) = &blocks[0] else {863
panic!("paragraph expected");864
};865
assert_eq!(inline.emoji().len(), 2);866
assert_eq!(inline.plain_text(), "hi ok");867
assert_eq!(emoji_urls(&blocks), vec!["a".to_owned()]);868
let trailing = layout_blocks(&[text("bye "), emoji("b")]);869
let Block::Paragraph(inline) = &trailing[0] else {870
panic!("paragraph expected");871
};872
assert_eq!(inline.emoji().len(), 1);873
}874
800
#[test]875
#[test]801
fn plain_text_is_one_paragraph() {876
fn plain_text_is_one_paragraph() {802
let blocks = layout_blocks(&[text("hello ")]);877
let blocks = layout_blocks(&[text("hello ")]);@@ -372,6 +372,23 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement
372
372
.filter(|segment| segment.style.code)
373
373
.map(|segment| (segment.range.clone(), mono.clone()))
374
374
.collect();
375
let emoji = inline.emoji();
376
let highlights = highlights
377
.into_iter()
378
.chain(emoji.iter().map(|(range, _)| {
379
(
380
range.clone(),
381
HighlightStyle {
382
color: Some(transparent_black()),
383
..Default::default()
384
},
385
)
386
}))
387
.collect::<Vec<_>>();
388
let inline_images = emoji
389
.into_iter()
390
.filter_map(|(range, url)| Some((range, super::hooks::inline_image(&url, cx)?)))
391
.collect();
375
392
let pills = inline
376
393
.segments
377
394
.iter()
@@ -387,7 +404,13 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement
387
404
.iter()
388
405
.map(|segment| FlowSegment {
389
406
range: segment.range.clone(),
390
highlight: highlight_for(segment.style, own),
407
highlight: match segment.emoji {
408
Some(_) => HighlightStyle {
409
color: Some(transparent_black()),
410
..Default::default()
411
},
412
None => highlight_for(segment.style, own),
413
},
391
414
family: segment.style.code.then(|| mono.clone()),
392
415
scale: segment.style.font_scale(),
393
416
raise: segment.style.baseline_raise(),
@@ -410,7 +433,8 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement
410
433
SelectableRichText::new(ElementId::Name(id.into()), inline.text.clone(), highlights)
411
434
.links(inline.links())
412
435
.font_overrides(font_overrides)
413
.pills(pills),
436
.pills(pills)
437
.inline_images(inline_images),
414
438
)
415
439
.into_any_element()
416
440
}
@@ -372,6 +372,23 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement372
.filter(|segment| segment.style.code)372
.filter(|segment| segment.style.code)373
.map(|segment| (segment.range.clone(), mono.clone()))373
.map(|segment| (segment.range.clone(), mono.clone()))374
.collect();374
.collect();375
let emoji = inline.emoji();376
let highlights = highlights377
.into_iter()378
.chain(emoji.iter().map(|(range, _)| {379
(380
range.clone(),381
HighlightStyle {382
color: Some(transparent_black()),383
..Default::default()384
},385
)386
}))387
.collect::<Vec<_>>();388
let inline_images = emoji389
.into_iter()390
.filter_map(|(range, url)| Some((range, super::hooks::inline_image(&url, cx)?)))391
.collect();375
let pills = inline392
let pills = inline376
.segments393
.segments377
.iter()394
.iter()@@ -387,7 +404,13 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement387
.iter()404
.iter()388
.map(|segment| FlowSegment {405
.map(|segment| FlowSegment {389
range: segment.range.clone(),406
range: segment.range.clone(),390
highlight: highlight_for(segment.style, own),407
highlight: match segment.emoji {408
Some(_) => HighlightStyle {409
color: Some(transparent_black()),410
..Default::default()411
},412
None => highlight_for(segment.style, own),413
},391
family: segment.style.code.then(|| mono.clone()),414
family: segment.style.code.then(|| mono.clone()),392
scale: segment.style.font_scale(),415
scale: segment.style.font_scale(),393
raise: segment.style.baseline_raise(),416
raise: segment.style.baseline_raise(),@@ -410,7 +433,8 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement410
SelectableRichText::new(ElementId::Name(id.into()), inline.text.clone(), highlights)433
SelectableRichText::new(ElementId::Name(id.into()), inline.text.clone(), highlights)411
.links(inline.links())434
.links(inline.links())412
.font_overrides(font_overrides)435
.font_overrides(font_overrides)413
.pills(pills),436
.pills(pills)437
.inline_images(inline_images),414
)438
)415
.into_any_element()439
.into_any_element()416
}440
}@@ -4,6 +4,7 @@ use gpui_kit::*;
4
4
pub struct RenderHooks {
5
5
pub open_profile_link: fn(&str, Point<Pixels>, &mut App) -> bool,
6
6
pub jump_to_quoted: fn(String, &mut App),
7
pub inline_image: fn(&str, &App) -> Option<std::path::PathBuf>,
7
8
}
8
9
9
10
impl Global for RenderHooks {}
@@ -20,3 +21,8 @@ pub fn jump_to_quoted(message_id: String, cx: &mut App) {
20
21
(hooks.jump_to_quoted)(message_id, cx);
21
22
}
22
23
}
24
25
pub fn inline_image(url: &str, cx: &App) -> Option<std::path::PathBuf> {
26
let hooks = cx.try_global::<RenderHooks>().copied()?;
27
(hooks.inline_image)(url, cx)
28
}
@@ -4,6 +4,7 @@ use gpui_kit::*;4
pub struct RenderHooks {4
pub struct RenderHooks {5
pub open_profile_link: fn(&str, Point<Pixels>, &mut App) -> bool,5
pub open_profile_link: fn(&str, Point<Pixels>, &mut App) -> bool,6
pub jump_to_quoted: fn(String, &mut App),6
pub jump_to_quoted: fn(String, &mut App),7
pub inline_image: fn(&str, &App) -> Option<std::path::PathBuf>,7
}8
}8
9
9
impl Global for RenderHooks {}10
impl Global for RenderHooks {}@@ -20,3 +21,8 @@ pub fn jump_to_quoted(message_id: String, cx: &mut App) {20
(hooks.jump_to_quoted)(message_id, cx);21
(hooks.jump_to_quoted)(message_id, cx);21
}22
}22
}23
}24
25
pub fn inline_image(url: &str, cx: &App) -> Option<std::path::PathBuf> {26
let hooks = cx.try_global::<RenderHooks>().copied()?;27
(hooks.inline_image)(url, cx)28
}@@ -1,5 +1,6 @@
1
1
use std::cell::RefCell;
2
2
use std::ops::Range;
3
use std::path::PathBuf;
3
4
use std::rc::Rc;
4
5
5
6
use gpui_kit::base::{
@@ -7,7 +8,7 @@ use gpui_kit::base::{
7
8
};
8
9
use gpui_kit::*;
9
10
10
use super::blocks::CODE_PADDING;
11
use super::blocks::{CODE_PADDING, EMOJI_PLACEHOLDER};
11
12
use super::hooks::open_profile_link;
12
13
13
14
pub(super) const TIME_ROOM: char = '\u{2007}';
@@ -43,6 +44,7 @@ impl Participant {
43
44
}
44
45
45
46
pub(super) const PILL_OUTSET: f32 = 3.;
47
const INLINE_IMAGE_SIZE: f32 = 20.;
46
48
pub(super) const PILL_INSET_Y: f32 = 1.;
47
49
48
50
#[derive(Clone, Debug)]
@@ -60,6 +62,7 @@ pub struct SelectableRichText {
60
62
styled_text: StyledText,
61
63
links: Vec<(Range<usize>, String)>,
62
64
pills: Vec<Pill>,
65
inline_images: Vec<(Range<usize>, PathBuf)>,
63
66
}
64
67
65
68
impl SelectableRichText {
@@ -75,6 +78,7 @@ impl SelectableRichText {
75
78
text,
76
79
links: Vec::new(),
77
80
pills: Vec::new(),
81
inline_images: Vec::new(),
78
82
}
79
83
}
80
84
@@ -83,6 +87,11 @@ impl SelectableRichText {
83
87
self
84
88
}
85
89
90
pub fn inline_images(mut self, images: Vec<(Range<usize>, PathBuf)>) -> Self {
91
self.inline_images = images;
92
self
93
}
94
86
95
pub fn font_overrides(mut self, overrides: Vec<(Range<usize>, SharedString)>) -> Self {
87
96
if !overrides.is_empty() {
88
97
let styled_text = std::mem::replace(&mut self.styled_text, StyledText::new(""));
@@ -97,6 +106,36 @@ impl SelectableRichText {
97
106
}
98
107
}
99
108
109
fn paint_inline_images(
110
images: &[(Range<usize>, PathBuf)],
111
text: &str,
112
layout: &TextLayout,
113
window: &mut Window,
114
cx: &mut App,
115
) {
116
let line_height = layout.line_height();
117
let left = layout.bounds().left();
118
for (range, path) in images {
119
let Some(line) = pill_lines(text, range.clone(), left, |index| {
120
layout.position_for_index(index)
121
})
122
.into_iter()
123
.next() else {
124
continue;
125
};
126
let Some(Ok(image)) =
127
window.use_asset::<ImgResourceLoader>(&Resource::Path(path.clone().into()), cx)
128
else {
129
continue;
130
};
131
let side = line_height.min(px(INLINE_IMAGE_SIZE));
132
let center_x = line.left + (line.right - line.left) / 2.;
133
let origin = point(center_x - side / 2., line.top + (line_height - side) / 2.);
134
let image_bounds = Bounds::new(origin, size(side, side));
135
let _ = window.paint_image(image_bounds, image_bounds, Corners::default(), image, 0, false);
136
}
137
}
138
100
139
fn paint_pills(pills: &[Pill], text: &str, layout: &TextLayout, window: &mut Window) {
101
140
let line_height = layout.line_height();
102
141
let bounds = layout.bounds();
@@ -307,7 +346,11 @@ impl Element for SelectableRichText {
307
346
if end_index <= range.start {
308
347
continue;
309
348
}
310
copied.push_str(&self.text[range.start..end_index].replace(CODE_PADDING, ""));
349
copied.push_str(
350
&self.text[range.start..end_index]
351
.replace(CODE_PADDING, "")
352
.replace(EMOJI_PLACEHOLDER, ""),
353
);
311
354
let (Some(start), Some(end)) = (
312
355
layout.position_for_index(range.start),
313
356
layout.position_for_index(end_index),
@@ -328,6 +371,7 @@ impl Element for SelectableRichText {
328
371
window,
329
372
cx,
330
373
);
374
paint_inline_images(&self.inline_images, &self.text, &layout, window, cx);
331
375
332
376
let hovered_link = hitbox.is_hovered(window)
333
377
&& link_at(&layout, &self.links, window.mouse_position()).is_some();
@@ -1,5 +1,6 @@1
use std::cell::RefCell;1
use std::cell::RefCell;2
use std::ops::Range;2
use std::ops::Range;3
use std::path::PathBuf;3
use std::rc::Rc;4
use std::rc::Rc;4
5
5
use gpui_kit::base::{6
use gpui_kit::base::{@@ -7,7 +8,7 @@ use gpui_kit::base::{7
};8
};8
use gpui_kit::*;9
use gpui_kit::*;9
10
10
use super::blocks::CODE_PADDING;11
use super::blocks::{CODE_PADDING, EMOJI_PLACEHOLDER};11
use super::hooks::open_profile_link;12
use super::hooks::open_profile_link;12
13
13
pub(super) const TIME_ROOM: char = '\u{2007}';14
pub(super) const TIME_ROOM: char = '\u{2007}';@@ -43,6 +44,7 @@ impl Participant {43
}44
}44
45
45
pub(super) const PILL_OUTSET: f32 = 3.;46
pub(super) const PILL_OUTSET: f32 = 3.;47
const INLINE_IMAGE_SIZE: f32 = 20.;46
pub(super) const PILL_INSET_Y: f32 = 1.;48
pub(super) const PILL_INSET_Y: f32 = 1.;47
49
48
#[derive(Clone, Debug)]50
#[derive(Clone, Debug)]@@ -60,6 +62,7 @@ pub struct SelectableRichText {60
styled_text: StyledText,62
styled_text: StyledText,61
links: Vec<(Range<usize>, String)>,63
links: Vec<(Range<usize>, String)>,62
pills: Vec<Pill>,64
pills: Vec<Pill>,65
inline_images: Vec<(Range<usize>, PathBuf)>,63
}66
}64
67
65
impl SelectableRichText {68
impl SelectableRichText {@@ -75,6 +78,7 @@ impl SelectableRichText {75
text,78
text,76
links: Vec::new(),79
links: Vec::new(),77
pills: Vec::new(),80
pills: Vec::new(),81
inline_images: Vec::new(),78
}82
}79
}83
}80
84
@@ -83,6 +87,11 @@ impl SelectableRichText {83
self87
self84
}88
}85
89
90
pub fn inline_images(mut self, images: Vec<(Range<usize>, PathBuf)>) -> Self {91
self.inline_images = images;92
self93
}94
86
pub fn font_overrides(mut self, overrides: Vec<(Range<usize>, SharedString)>) -> Self {95
pub fn font_overrides(mut self, overrides: Vec<(Range<usize>, SharedString)>) -> Self {87
if !overrides.is_empty() {96
if !overrides.is_empty() {88
let styled_text = std::mem::replace(&mut self.styled_text, StyledText::new(""));97
let styled_text = std::mem::replace(&mut self.styled_text, StyledText::new(""));@@ -97,6 +106,36 @@ impl SelectableRichText {97
}106
}98
}107
}99
108
109
fn paint_inline_images(110
images: &[(Range<usize>, PathBuf)],111
text: &str,112
layout: &TextLayout,113
window: &mut Window,114
cx: &mut App,115
) {116
let line_height = layout.line_height();117
let left = layout.bounds().left();118
for (range, path) in images {119
let Some(line) = pill_lines(text, range.clone(), left, |index| {120
layout.position_for_index(index)121
})122
.into_iter()123
.next() else {124
continue;125
};126
let Some(Ok(image)) =127
window.use_asset::<ImgResourceLoader>(&Resource::Path(path.clone().into()), cx)128
else {129
continue;130
};131
let side = line_height.min(px(INLINE_IMAGE_SIZE));132
let center_x = line.left + (line.right - line.left) / 2.;133
let origin = point(center_x - side / 2., line.top + (line_height - side) / 2.);134
let image_bounds = Bounds::new(origin, size(side, side));135
let _ = window.paint_image(image_bounds, image_bounds, Corners::default(), image, 0, false);136
}137
}138
100
fn paint_pills(pills: &[Pill], text: &str, layout: &TextLayout, window: &mut Window) {139
fn paint_pills(pills: &[Pill], text: &str, layout: &TextLayout, window: &mut Window) {101
let line_height = layout.line_height();140
let line_height = layout.line_height();102
let bounds = layout.bounds();141
let bounds = layout.bounds();@@ -307,7 +346,11 @@ impl Element for SelectableRichText {307
if end_index <= range.start {346
if end_index <= range.start {308
continue;347
continue;309
}348
}310
copied.push_str(&self.text[range.start..end_index].replace(CODE_PADDING, ""));349
copied.push_str(350
&self.text[range.start..end_index]351
.replace(CODE_PADDING, "")352
.replace(EMOJI_PLACEHOLDER, ""),353
);311
let (Some(start), Some(end)) = (354
let (Some(start), Some(end)) = (312
layout.position_for_index(range.start),355
layout.position_for_index(range.start),313
layout.position_for_index(end_index),356
layout.position_for_index(end_index),@@ -328,6 +371,7 @@ impl Element for SelectableRichText {328
window,371
window,329
cx,372
cx,330
);373
);374
paint_inline_images(&self.inline_images, &self.text, &layout, window, cx);331
375
332
let hovered_link = hitbox.is_hovered(window)376
let hovered_link = hitbox.is_hovered(window)333
&& link_at(&layout, &self.links, window.mouse_position()).is_some();377
&& link_at(&layout, &self.links, window.mouse_position()).is_some();@@ -84,6 +84,11 @@ impl RenderEnv {
84
84
.iter()
85
85
.filter_map(ReactionChip::custom_emoji_image),
86
86
)
87
.chain(
88
app_ui_kit::render::blocks::emoji_urls(&message.blocks)
89
.into_iter()
90
.map(inline_emoji_image),
91
)
87
92
.filter(|image| self.app.read(cx).directory.image(&image.url).is_none())
88
93
.collect();
89
94
if !missing_images.is_empty() {
@@ -524,3 +529,16 @@ impl RenderEnv {
524
529
.into_any_element()
525
530
}
526
531
}
532
533
fn inline_emoji_image(url: String) -> ImageRef {
534
let hash = url.bytes().fold(0x811c_9dc5_u32, |hash, byte| {
535
(hash ^ u32::from(byte)).wrapping_mul(0x0100_0193)
536
});
537
ImageRef {
538
id: format!("emoji-{hash:08x}"),
539
url,
540
width: None,
541
height: None,
542
alt: None,
543
}
544
}
@@ -84,6 +84,11 @@ impl RenderEnv {84
.iter()84
.iter()85
.filter_map(ReactionChip::custom_emoji_image),85
.filter_map(ReactionChip::custom_emoji_image),86
)86
)87
.chain(88
app_ui_kit::render::blocks::emoji_urls(&message.blocks)89
.into_iter()90
.map(inline_emoji_image),91
)87
.filter(|image| self.app.read(cx).directory.image(&image.url).is_none())92
.filter(|image| self.app.read(cx).directory.image(&image.url).is_none())88
.collect();93
.collect();89
if !missing_images.is_empty() {94
if !missing_images.is_empty() {@@ -524,3 +529,16 @@ impl RenderEnv {524
.into_any_element()529
.into_any_element()525
}530
}526
}531
}532
533
fn inline_emoji_image(url: String) -> ImageRef {534
let hash = url.bytes().fold(0x811c_9dc5_u32, |hash, byte| {535
(hash ^ u32::from(byte)).wrapping_mul(0x0100_0193)536
});537
ImageRef {538
id: format!("emoji-{hash:08x}"),539
url,540
width: None,541
height: None,542
alt: None,543
}544
}@@ -100,9 +100,16 @@ pub fn install_globals(state: &Entity<AppState>, user_input: Arc<UserInput>, cx:
100
100
cx.set_global(RenderHooks {
101
101
open_profile_link: super::profile_card::open_profile_link,
102
102
jump_to_quoted,
103
inline_image,
103
104
});
104
105
}
105
106
107
fn inline_image(url: &str, cx: &App) -> Option<std::path::PathBuf> {
108
let handle = cx.try_global::<crate::app_state::AppHandle>()?;
109
let entry = handle.0.read(cx).directory.image(url)?;
110
Some(entry.path.clone())
111
}
112
106
113
fn jump_to_quoted(message_id: String, cx: &mut App) {
107
114
let Some(handle) = cx.try_global::<crate::app_state::AppHandle>() else {
108
115
return;
@@ -100,9 +100,16 @@ pub fn install_globals(state: &Entity<AppState>, user_input: Arc<UserInput>, cx:100
cx.set_global(RenderHooks {100
cx.set_global(RenderHooks {101
open_profile_link: super::profile_card::open_profile_link,101
open_profile_link: super::profile_card::open_profile_link,102
jump_to_quoted,102
jump_to_quoted,103
inline_image,103
});104
});104
}105
}105
106
107
fn inline_image(url: &str, cx: &App) -> Option<std::path::PathBuf> {108
let handle = cx.try_global::<crate::app_state::AppHandle>()?;109
let entry = handle.0.read(cx).directory.image(url)?;110
Some(entry.path.clone())111
}112
106
fn jump_to_quoted(message_id: String, cx: &mut App) {113
fn jump_to_quoted(message_id: String, cx: &mut App) {107
let Some(handle) = cx.try_global::<crate::app_state::AppHandle>() else {114
let Some(handle) = cx.try_global::<crate::app_state::AppHandle>() else {108
return;115
return;@@ -2506,7 +2506,7 @@ impl SpanLines {
2506
2506
self.lines.push(table_line(Table::from_rows(rows)));
2507
2507
self.open = false;
2508
2508
}
2509
Span::Image { .. } | Span::Quote { .. } => {}
2509
Span::Image { .. } | Span::Quote { .. } | Span::CustomEmoji { .. } => {}
2510
2510
}
2511
2511
}
2512
2512
}
@@ -2506,7 +2506,7 @@ impl SpanLines {2506
self.lines.push(table_line(Table::from_rows(rows)));2506
self.lines.push(table_line(Table::from_rows(rows)));2507
self.open = false;2507
self.open = false;2508
}2508
}2509
Span::Image { .. } | Span::Quote { .. } => {}2509
Span::Image { .. } | Span::Quote { .. } | Span::CustomEmoji { .. } => {}2510
}2510
}2511
}2511
}2512
}2512
}@@ -110,6 +110,11 @@ fn collect(spans: &[Span], parts: &mut BodyParts) {
110
110
parts.text.push(' ');
111
111
}
112
112
Span::Mention { name, .. } => parts.text.push_str(name),
113
Span::CustomEmoji { name, .. } => {
114
parts.text.push(':');
115
parts.text.push_str(name);
116
parts.text.push(':');
117
}
113
118
Span::Quote { .. } => {}
114
119
Span::Image { hosted_content_url } if is_giphy_url(hosted_content_url) => {
115
120
parts.gifs += 1
@@ -110,6 +110,11 @@ fn collect(spans: &[Span], parts: &mut BodyParts) {110
parts.text.push(' ');110
parts.text.push(' ');111
}111
}112
Span::Mention { name, .. } => parts.text.push_str(name),112
Span::Mention { name, .. } => parts.text.push_str(name),113
Span::CustomEmoji { name, .. } => {114
parts.text.push(':');115
parts.text.push_str(name);116
parts.text.push(':');117
}113
Span::Quote { .. } => {}118
Span::Quote { .. } => {}114
Span::Image { hosted_content_url } if is_giphy_url(hosted_content_url) => {119
Span::Image { hosted_content_url } if is_giphy_url(hosted_content_url) => {115
parts.gifs += 1120
parts.gifs += 1@@ -56,6 +56,10 @@ pub enum Span {
56
56
Image {
57
57
hosted_content_url: String,
58
58
},
59
CustomEmoji {
60
name: String,
61
url: String,
62
},
59
63
Quote {
60
64
message_id: Option<String>,
61
65
children: Vec<Span>,
@@ -184,6 +188,7 @@ fn convert_unindented(element: ElementRef<'_>, spans: &mut Vec<Span>) {
184
188
}),
185
189
"blockquote" => spans.push(Span::BlockQuote(convert_children(element))),
186
190
"emoji" => push_emoji(element, spans),
191
"customemoji" => push_custom_emoji(element, spans),
187
192
"img" => push_image(element, spans),
188
193
_ => spans.extend(convert_children(element)),
189
194
}
@@ -422,6 +427,19 @@ fn push_emoji(element: ElementRef<'_>, spans: &mut Vec<Span>) {
422
427
push_text(spans, &without_repeated_skin_tone(&glyph));
423
428
}
424
429
430
fn push_custom_emoji(element: ElementRef<'_>, spans: &mut Vec<Span>) {
431
let value = element.value();
432
let name = value.attr("alt").unwrap_or_default().to_owned();
433
match value.attr("source").filter(|source| !source.is_empty()) {
434
Some(source) => spans.push(Span::CustomEmoji {
435
name,
436
url: source.to_owned(),
437
}),
438
None if !name.is_empty() => push_text(spans, &format!(":{name}:")),
439
None => {}
440
}
441
}
442
425
443
fn push_image(element: ElementRef<'_>, spans: &mut Vec<Span>) {
426
444
let value = element.value();
427
445
let is_emoji = value
@@ -56,6 +56,10 @@ pub enum Span {56
Image {56
Image {57
hosted_content_url: String,57
hosted_content_url: String,58
},58
},59
CustomEmoji {60
name: String,61
url: String,62
},59
Quote {63
Quote {60
message_id: Option<String>,64
message_id: Option<String>,61
children: Vec<Span>,65
children: Vec<Span>,@@ -184,6 +188,7 @@ fn convert_unindented(element: ElementRef<'_>, spans: &mut Vec<Span>) {184
}),188
}),185
"blockquote" => spans.push(Span::BlockQuote(convert_children(element))),189
"blockquote" => spans.push(Span::BlockQuote(convert_children(element))),186
"emoji" => push_emoji(element, spans),190
"emoji" => push_emoji(element, spans),191
"customemoji" => push_custom_emoji(element, spans),187
"img" => push_image(element, spans),192
"img" => push_image(element, spans),188
_ => spans.extend(convert_children(element)),193
_ => spans.extend(convert_children(element)),189
}194
}@@ -422,6 +427,19 @@ fn push_emoji(element: ElementRef<'_>, spans: &mut Vec<Span>) {422
push_text(spans, &without_repeated_skin_tone(&glyph));427
push_text(spans, &without_repeated_skin_tone(&glyph));423
}428
}424
429
430
fn push_custom_emoji(element: ElementRef<'_>, spans: &mut Vec<Span>) {431
let value = element.value();432
let name = value.attr("alt").unwrap_or_default().to_owned();433
match value.attr("source").filter(|source| !source.is_empty()) {434
Some(source) => spans.push(Span::CustomEmoji {435
name,436
url: source.to_owned(),437
}),438
None if !name.is_empty() => push_text(spans, &format!(":{name}:")),439
None => {}440
}441
}442
425
fn push_image(element: ElementRef<'_>, spans: &mut Vec<Span>) {443
fn push_image(element: ElementRef<'_>, spans: &mut Vec<Span>) {426
let value = element.value();444
let value = element.value();427
let is_emoji = value445
let is_emoji = value@@ -535,6 +535,11 @@ pub(crate) fn push_plain(text: &mut String, spans: &[Span]) {
535
535
}
536
536
}
537
537
Span::Image { .. } => {}
538
Span::CustomEmoji { name, .. } => {
539
text.push(':');
540
text.push_str(name);
541
text.push(':');
542
}
538
543
}
539
544
}
540
545
}
@@ -535,6 +535,11 @@ pub(crate) fn push_plain(text: &mut String, spans: &[Span]) {535
}535
}536
}536
}537
Span::Image { .. } => {}537
Span::Image { .. } => {}538
Span::CustomEmoji { name, .. } => {539
text.push(':');540
text.push_str(name);541
text.push(':');542
}538
}543
}539
}544
}540
}545
}@@ -514,3 +514,24 @@ fn teams_code_blocks_keep_their_line_breaks() {
514
514
}]
515
515
);
516
516
}
517
518
#[test]
519
fn org_emoji_keep_their_image_and_name() {
520
let source = "https://graph.microsoft.com/v1.0/chats/19:a@thread.v2/messages/1/hostedContents/aWQ9/$value";
521
assert_eq!(
522
html_to_spans(&format!(
523
"<p>hi <customemoji id=\"MC13\" alt=\"crying_cat\" source=\"{source}\"></customemoji></p>"
524
)),
525
vec![
526
text("hi "),
527
Span::CustomEmoji {
528
name: "crying_cat".to_owned(),
529
url: source.to_owned(),
530
},
531
]
532
);
533
assert_eq!(
534
html_to_spans("<p><customemoji alt=\"crying_cat\"></customemoji></p>"),
535
vec![text(":crying_cat:")]
536
);
537
}
@@ -514,3 +514,24 @@ fn teams_code_blocks_keep_their_line_breaks() {514
}]514
}]515
);515
);516
}516
}517
518
#[test]519
fn org_emoji_keep_their_image_and_name() {520
let source = "https://graph.microsoft.com/v1.0/chats/19:a@thread.v2/messages/1/hostedContents/aWQ9/$value";521
assert_eq!(522
html_to_spans(&format!(523
"<p>hi <customemoji id=\"MC13\" alt=\"crying_cat\" source=\"{source}\"></customemoji></p>"524
)),525
vec![526
text("hi "),527
Span::CustomEmoji {528
name: "crying_cat".to_owned(),529
url: source.to_owned(),530
},531
]532
);533
assert_eq!(534
html_to_spans("<p><customemoji alt=\"crying_cat\"></customemoji></p>"),535
vec![text(":crying_cat:")]536
);537
}