BlueGit

ict rusty-teams

feat(chat): long links are sent shortened like Teams and show their URL on hover (#135)

Co-authored-by: Fülöp Márk <mark.fulop@blackcell.io>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

metis fulopm · pushed by metis

Authored 2026-11-26 · 5 days ago

Hash
5db35bf275dd7e0ca0e0b0eef36a9356e5245ef1
Parent
e99789d1
7 files changed +422 −11
crates/app-ui-kit/src/render/flow_text.rs +140 −4
@@ -7,6 +7,7 @@ use gpui_kit::*;
7 7
8 8 use super::blocks::CODE_PADDING;
9 9 use super::hooks::open_profile_link;
10 use super::link_tooltip::LinkTooltip;
10 11 use super::selectable::{HIT_SLOP, PILL_INSET_Y, PILL_OUTSET, Participant, Pill, TIME_ROOM};
11 12
12 13 const WRAP_TOLERANCE: f32 = 0.5;
@@ -374,6 +375,7 @@ pub struct FlowPrepaint {
374 375 hitbox: Hitbox,
375 376 fragments: Vec<PaintedFragment>,
376 377 lines: Vec<Line>,
378 tooltip: Option<LinkTooltip>,
377 379 }
378 380
379 381 impl IntoElement for FlowText {
@@ -556,7 +558,7 @@ impl Element for FlowText {
556 558
557 559 fn prepaint(
558 560 &mut self,
559 _global_id: Option<&GlobalElementId>,
561 global_id: Option<&GlobalElementId>,
560 562 _inspector_id: Option<&InspectorElementId>,
561 563 bounds: Bounds<Pixels>,
562 564 request: &mut Self::RequestLayoutState,
@@ -619,6 +621,7 @@ impl Element for FlowText {
619 621 hitbox,
620 622 fragments,
621 623 lines: layout.lines.clone(),
624 tooltip: LinkTooltip::prepaint(global_id, !self.links.is_empty(), window),
622 625 }
623 626 }
624 627
@@ -719,6 +722,22 @@ impl Element for FlowText {
719 722 .iter()
720 723 .map(|painted| (painted.layout.clone(), painted.fragment.range.start))
721 724 .collect();
725 if let Some(tooltip) = &prepaint.tooltip {
726 let (tooltip_layouts, tooltip_links) = (hover_layouts.clone(), self.links.clone());
727 tooltip.paint(
728 &prepaint.hitbox,
729 move |position| {
730 tooltip_layouts.iter().find_map(|(layout, start)| {
731 let index = layout.index_for_position(position).ok()?;
732 tooltip_links
733 .iter()
734 .find(|(range, _)| range.contains(&(start + index)))
735 .map(|(_, url)| url.clone())
736 })
737 },
738 window,
739 );
740 }
722 741 let (hover_links, hover_hitbox) = (self.links.clone(), prepaint.hitbox.clone());
723 742 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, _| {
724 743 let over_link = hover_hitbox.is_hovered(window)
@@ -781,9 +800,9 @@ mod tests {
781 800 use gpui_kit::base::TextSelection;
782 801 use gpui_kit::test::TestWindowExt as _;
783 802 use gpui_kit::{
784 AnyWindowHandle, AppContext as _, Bounds, Context, HighlightStyle, IntoElement,
785 ParentElement as _, Pixels, Point, Render, Styled as _, TestAppContext, Window,
786 WindowBounds, WindowOptions, div, point, px, size,
803 AnyWindowHandle, AppContext as _, Bounds, Context, HighlightStyle, IntoElement, Modifiers,
804 MouseButton, ParentElement as _, Pixels, Point, Render, Styled as _, TestAppContext,
805 VisualTestContext, Window, WindowBounds, WindowOptions, div, point, px, size,
787 806 };
788 807
789 808 use super::{FlowLayout, FlowSegment, FlowText, Measured, build_lines, place};
@@ -960,4 +979,121 @@ mod tests {
960 979 assert!(link_x.is_some());
961 980 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
962 981 }
982
983 struct Links {
984 text: &'static str,
985 links: Vec<(Range<usize>, String)>,
986 }
987
988 impl Render for Links {
989 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
990 div().w(px(400.)).text_size(px(14.)).child(
991 FlowText::new(
992 "links",
993 self.text,
994 vec![segment(0..self.text.len(), 1., 0.)],
995 )
996 .links(self.links.clone()),
997 )
998 }
999 }
1000
1001 struct Hover<'a> {
1002 window_cx: &'a mut VisualTestContext,
1003 }
1004
1005 impl Hover<'_> {
1006 fn open<'a>(
1007 cx: &'a mut TestAppContext,
1008 text: &'static str,
1009 links: &[(Range<usize>, &str)],
1010 ) -> Hover<'a> {
1011 cx.update(gpui_kit::init);
1012 let links = links
1013 .iter()
1014 .map(|(range, url)| (range.clone(), (*url).to_owned()))
1015 .collect();
1016 let (_, window_cx) = cx.add_window_view(move |_, _| Links { text, links });
1017 Hover { window_cx }
1018 }
1019
1020 /// Moves the mouse to `x` on the first line, optionally holding the left button, and
1021 /// waits out the tooltip delay. The tooltip's bounds, if one shows.
1022 fn at(&mut self, x: f32, button: Option<MouseButton>) -> Option<Bounds<Pixels>> {
1023 let position = point(px(x), px(8.));
1024 self.window_cx
1025 .simulate_mouse_move(position, button, Modifiers::none());
1026 self.window_cx
1027 .executor()
1028 .advance_clock(std::time::Duration::from_millis(600));
1029 self.window_cx.run_until_parked();
1030 self.window_cx.debug_bounds("tooltip")
1031 }
1032
1033 fn first_tooltip_x(&mut self, from: u32) -> Option<f32> {
1034 (from..400)
1035 .map(|x| x as f32)
1036 .find(|x| self.at(*x, None).is_some())
1037 }
1038 }
1039
1040 #[gpui_kit::test]
1041 fn hovering_a_link_shows_its_url_in_a_tooltip(cx: &mut TestAppContext) {
1042 let mut hover = Hover::open(cx, TEXT, &[(8..12, "https://example.com")]);
1043 assert!(hover.at(2., None).is_none());
1044 assert!(hover.first_tooltip_x(40).is_some());
1045 assert!(hover.at(2., None).is_none());
1046 }
1047
1048 #[gpui_kit::test]
1049 fn a_long_url_tooltip_wraps_inside_its_maximum_width(cx: &mut TestAppContext) {
1050 let url = Box::leak(format!("https://example.com/{}", "a".repeat(600)).into_boxed_str());
1051 let mut hover = Hover::open(cx, "link", &[(0..4, url)]);
1052 let x = hover.first_tooltip_x(0).expect("tooltip over the link");
1053 let bounds = hover.at(x, None).expect("tooltip stays");
1054 assert!(bounds.size.width < px(560.), "{bounds:?}");
1055 assert!(bounds.size.height > px(40.), "{bounds:?}");
1056 }
1057
1058 #[gpui_kit::test]
1059 fn moving_onto_the_next_link_shows_that_links_tooltip(cx: &mut TestAppContext) {
1060 let mut hover = Hover::open(
1061 cx,
1062 "aaaaaaaaaabbbbbbbbbb",
1063 &[(0..10, "https://a.example"), (10..20, "https://b.example")],
1064 );
1065 let first = hover.at(4., None).expect("tooltip over the first link");
1066 let second = (40..200).map(|x| x as f32).find_map(|x| {
1067 hover
1068 .at(x, None)
1069 .filter(|bounds| bounds.origin.x > first.origin.x + px(20.))
1070 });
1071 assert!(second.is_some());
1072 }
1073
1074 #[gpui_kit::test]
1075 fn no_tooltip_while_dragging_a_selection_over_a_link(cx: &mut TestAppContext) {
1076 let mut hover = Hover::open(cx, TEXT, &[(8..12, "https://example.com")]);
1077 let link_x = hover.first_tooltip_x(40).expect("tooltip over the link");
1078 hover.at(2., None);
1079 hover.window_cx.simulate_mouse_down(
1080 point(px(2.), px(8.)),
1081 MouseButton::Left,
1082 Modifiers::none(),
1083 );
1084 assert!(hover.at(link_x, Some(MouseButton::Left)).is_none());
1085 hover.window_cx.simulate_mouse_up(
1086 point(px(link_x), px(8.)),
1087 MouseButton::Left,
1088 Modifiers::none(),
1089 );
1090 hover.at(link_x + 1., None);
1091 assert!(hover.at(link_x, None).is_some());
1092 }
1093
1094 #[gpui_kit::test]
1095 fn a_mention_profile_link_has_no_tooltip(cx: &mut TestAppContext) {
1096 let mut hover = Hover::open(cx, "@Ada Lovelace", &[(0..13, "teams-profile:8:orgid:x")]);
1097 assert_eq!(hover.first_tooltip_x(0), None);
1098 }
963 1099 }
@@ -7,6 +7,7 @@ use gpui_kit::*;
7
7
8use super::blocks::CODE_PADDING;
8use super::blocks::CODE_PADDING;
9use super::hooks::open_profile_link;
9use super::hooks::open_profile_link;
10use super::link_tooltip::LinkTooltip;
10use super::selectable::{HIT_SLOP, PILL_INSET_Y, PILL_OUTSET, Participant, Pill, TIME_ROOM};
11use super::selectable::{HIT_SLOP, PILL_INSET_Y, PILL_OUTSET, Participant, Pill, TIME_ROOM};
11
12
12const WRAP_TOLERANCE: f32 = 0.5;
13const WRAP_TOLERANCE: f32 = 0.5;
@@ -374,6 +375,7 @@ pub struct FlowPrepaint {
374 hitbox: Hitbox,
375 hitbox: Hitbox,
375 fragments: Vec<PaintedFragment>,
376 fragments: Vec<PaintedFragment>,
376 lines: Vec<Line>,
377 lines: Vec<Line>,
378 tooltip: Option<LinkTooltip>,
377}
379}
378
380
379impl IntoElement for FlowText {
381impl IntoElement for FlowText {
@@ -556,7 +558,7 @@ impl Element for FlowText {
556
558
557 fn prepaint(
559 fn prepaint(
558 &mut self,
560 &mut self,
559 _global_id: Option<&GlobalElementId>,
561 global_id: Option<&GlobalElementId>,
560 _inspector_id: Option<&InspectorElementId>,
562 _inspector_id: Option<&InspectorElementId>,
561 bounds: Bounds<Pixels>,
563 bounds: Bounds<Pixels>,
562 request: &mut Self::RequestLayoutState,
564 request: &mut Self::RequestLayoutState,
@@ -619,6 +621,7 @@ impl Element for FlowText {
619 hitbox,
621 hitbox,
620 fragments,
622 fragments,
621 lines: layout.lines.clone(),
623 lines: layout.lines.clone(),
624 tooltip: LinkTooltip::prepaint(global_id, !self.links.is_empty(), window),
622 }
625 }
623 }
626 }
624
627
@@ -719,6 +722,22 @@ impl Element for FlowText {
719 .iter()
722 .iter()
720 .map(|painted| (painted.layout.clone(), painted.fragment.range.start))
723 .map(|painted| (painted.layout.clone(), painted.fragment.range.start))
721 .collect();
724 .collect();
725 if let Some(tooltip) = &prepaint.tooltip {
726 let (tooltip_layouts, tooltip_links) = (hover_layouts.clone(), self.links.clone());
727 tooltip.paint(
728 &prepaint.hitbox,
729 move |position| {
730 tooltip_layouts.iter().find_map(|(layout, start)| {
731 let index = layout.index_for_position(position).ok()?;
732 tooltip_links
733 .iter()
734 .find(|(range, _)| range.contains(&(start + index)))
735 .map(|(_, url)| url.clone())
736 })
737 },
738 window,
739 );
740 }
722 let (hover_links, hover_hitbox) = (self.links.clone(), prepaint.hitbox.clone());
741 let (hover_links, hover_hitbox) = (self.links.clone(), prepaint.hitbox.clone());
723 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, _| {
742 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, _| {
724 let over_link = hover_hitbox.is_hovered(window)
743 let over_link = hover_hitbox.is_hovered(window)
@@ -781,9 +800,9 @@ mod tests {
781 use gpui_kit::base::TextSelection;
800 use gpui_kit::base::TextSelection;
782 use gpui_kit::test::TestWindowExt as _;
801 use gpui_kit::test::TestWindowExt as _;
783 use gpui_kit::{
802 use gpui_kit::{
784 AnyWindowHandle, AppContext as _, Bounds, Context, HighlightStyle, IntoElement,
803 AnyWindowHandle, AppContext as _, Bounds, Context, HighlightStyle, IntoElement, Modifiers,
785 ParentElement as _, Pixels, Point, Render, Styled as _, TestAppContext, Window,
804 MouseButton, ParentElement as _, Pixels, Point, Render, Styled as _, TestAppContext,
786 WindowBounds, WindowOptions, div, point, px, size,
805 VisualTestContext, Window, WindowBounds, WindowOptions, div, point, px, size,
787 };
806 };
788
807
789 use super::{FlowLayout, FlowSegment, FlowText, Measured, build_lines, place};
808 use super::{FlowLayout, FlowSegment, FlowText, Measured, build_lines, place};
@@ -960,4 +979,121 @@ mod tests {
960 assert!(link_x.is_some());
979 assert!(link_x.is_some());
961 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
980 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
962 }
981 }
982
983 struct Links {
984 text: &'static str,
985 links: Vec<(Range<usize>, String)>,
986 }
987
988 impl Render for Links {
989 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
990 div().w(px(400.)).text_size(px(14.)).child(
991 FlowText::new(
992 "links",
993 self.text,
994 vec![segment(0..self.text.len(), 1., 0.)],
995 )
996 .links(self.links.clone()),
997 )
998 }
999 }
1000
1001 struct Hover<'a> {
1002 window_cx: &'a mut VisualTestContext,
1003 }
1004
1005 impl Hover<'_> {
1006 fn open<'a>(
1007 cx: &'a mut TestAppContext,
1008 text: &'static str,
1009 links: &[(Range<usize>, &str)],
1010 ) -> Hover<'a> {
1011 cx.update(gpui_kit::init);
1012 let links = links
1013 .iter()
1014 .map(|(range, url)| (range.clone(), (*url).to_owned()))
1015 .collect();
1016 let (_, window_cx) = cx.add_window_view(move |_, _| Links { text, links });
1017 Hover { window_cx }
1018 }
1019
1020 /// Moves the mouse to `x` on the first line, optionally holding the left button, and
1021 /// waits out the tooltip delay. The tooltip's bounds, if one shows.
1022 fn at(&mut self, x: f32, button: Option<MouseButton>) -> Option<Bounds<Pixels>> {
1023 let position = point(px(x), px(8.));
1024 self.window_cx
1025 .simulate_mouse_move(position, button, Modifiers::none());
1026 self.window_cx
1027 .executor()
1028 .advance_clock(std::time::Duration::from_millis(600));
1029 self.window_cx.run_until_parked();
1030 self.window_cx.debug_bounds("tooltip")
1031 }
1032
1033 fn first_tooltip_x(&mut self, from: u32) -> Option<f32> {
1034 (from..400)
1035 .map(|x| x as f32)
1036 .find(|x| self.at(*x, None).is_some())
1037 }
1038 }
1039
1040 #[gpui_kit::test]
1041 fn hovering_a_link_shows_its_url_in_a_tooltip(cx: &mut TestAppContext) {
1042 let mut hover = Hover::open(cx, TEXT, &[(8..12, "https://example.com")]);
1043 assert!(hover.at(2., None).is_none());
1044 assert!(hover.first_tooltip_x(40).is_some());
1045 assert!(hover.at(2., None).is_none());
1046 }
1047
1048 #[gpui_kit::test]
1049 fn a_long_url_tooltip_wraps_inside_its_maximum_width(cx: &mut TestAppContext) {
1050 let url = Box::leak(format!("https://example.com/{}", "a".repeat(600)).into_boxed_str());
1051 let mut hover = Hover::open(cx, "link", &[(0..4, url)]);
1052 let x = hover.first_tooltip_x(0).expect("tooltip over the link");
1053 let bounds = hover.at(x, None).expect("tooltip stays");
1054 assert!(bounds.size.width < px(560.), "{bounds:?}");
1055 assert!(bounds.size.height > px(40.), "{bounds:?}");
1056 }
1057
1058 #[gpui_kit::test]
1059 fn moving_onto_the_next_link_shows_that_links_tooltip(cx: &mut TestAppContext) {
1060 let mut hover = Hover::open(
1061 cx,
1062 "aaaaaaaaaabbbbbbbbbb",
1063 &[(0..10, "https://a.example"), (10..20, "https://b.example")],
1064 );
1065 let first = hover.at(4., None).expect("tooltip over the first link");
1066 let second = (40..200).map(|x| x as f32).find_map(|x| {
1067 hover
1068 .at(x, None)
1069 .filter(|bounds| bounds.origin.x > first.origin.x + px(20.))
1070 });
1071 assert!(second.is_some());
1072 }
1073
1074 #[gpui_kit::test]
1075 fn no_tooltip_while_dragging_a_selection_over_a_link(cx: &mut TestAppContext) {
1076 let mut hover = Hover::open(cx, TEXT, &[(8..12, "https://example.com")]);
1077 let link_x = hover.first_tooltip_x(40).expect("tooltip over the link");
1078 hover.at(2., None);
1079 hover.window_cx.simulate_mouse_down(
1080 point(px(2.), px(8.)),
1081 MouseButton::Left,
1082 Modifiers::none(),
1083 );
1084 assert!(hover.at(link_x, Some(MouseButton::Left)).is_none());
1085 hover.window_cx.simulate_mouse_up(
1086 point(px(link_x), px(8.)),
1087 MouseButton::Left,
1088 Modifiers::none(),
1089 );
1090 hover.at(link_x + 1., None);
1091 assert!(hover.at(link_x, None).is_some());
1092 }
1093
1094 #[gpui_kit::test]
1095 fn a_mention_profile_link_has_no_tooltip(cx: &mut TestAppContext) {
1096 let mut hover = Hover::open(cx, "@Ada Lovelace", &[(0..13, "teams-profile:8:orgid:x")]);
1097 assert_eq!(hover.first_tooltip_x(0), None);
1098 }
963}
1099}
crates/app-ui-kit/src/render/mod.rs +1 −0
@@ -2,6 +2,7 @@ pub mod blocks;
2 2 pub mod elements;
3 3 mod flow_text;
4 4 pub mod hooks;
5 mod link_tooltip;
5 6 mod selectable;
6 7 mod syntax;
7 8
@@ -2,6 +2,7 @@ pub mod blocks;
2pub mod elements;
2pub mod elements;
3mod flow_text;
3mod flow_text;
4pub mod hooks;
4pub mod hooks;
5mod link_tooltip;
5mod selectable;
6mod selectable;
6mod syntax;
7mod syntax;
7
8
crates/app-ui-kit/src/render/selectable.rs +13 −3
@@ -10,6 +10,7 @@ use gpui_kit::*;
10 10
11 11 use super::blocks::{CODE_PADDING, EMOJI_PLACEHOLDER};
12 12 use super::hooks::{open_link, open_profile_link};
13 use super::link_tooltip::LinkTooltip;
13 14
14 15 pub(super) const TIME_ROOM: char = '\u{2007}';
15 16 pub(super) const HIT_SLOP: f32 = 12.;
@@ -272,7 +273,7 @@ impl IntoElement for SelectableRichText {
272 273
273 274 impl Element for SelectableRichText {
274 275 type RequestLayoutState = Participant;
275 type PrepaintState = Hitbox;
276 type PrepaintState = (Hitbox, Option<LinkTooltip>);
276 277
277 278 fn id(&self) -> Option<ElementId> {
278 279 Some(self.id.clone())
@@ -318,7 +319,8 @@ impl Element for SelectableRichText {
318 319 .with_text_bounds(vec![bounds])
319 320 .with_rendered_element(handle, window, cx);
320 321 handle.register(registration, window, cx);
321 hitbox
322 let tooltip = LinkTooltip::prepaint(global_id, !self.links.is_empty(), window);
323 (hitbox, tooltip)
322 324 }
323 325
324 326 fn paint(
@@ -327,7 +329,7 @@ impl Element for SelectableRichText {
327 329 inspector_id: Option<&InspectorElementId>,
328 330 bounds: Bounds<Pixels>,
329 331 participant: &mut Self::RequestLayoutState,
330 hitbox: &mut Self::PrepaintState,
332 (hitbox, tooltip): &mut Self::PrepaintState,
331 333 window: &mut Window,
332 334 cx: &mut App,
333 335 ) {
@@ -388,6 +390,14 @@ impl Element for SelectableRichText {
388 390 CursorStyle::IBeam
389 391 };
390 392 window.set_cursor_style(cursor, hitbox);
393 if let Some(tooltip) = tooltip {
394 let (tooltip_layout, tooltip_links) = (layout.clone(), self.links.clone());
395 tooltip.paint(
396 hitbox,
397 move |position| link_at(&tooltip_layout, &tooltip_links, position),
398 window,
399 );
400 }
391 401 if !self.links.is_empty() {
392 402 let (hover_layout, hover_links, hover_hitbox) =
393 403 (layout.clone(), self.links.clone(), hitbox.clone());
@@ -10,6 +10,7 @@ use gpui_kit::*;
10
10
11use super::blocks::{CODE_PADDING, EMOJI_PLACEHOLDER};
11use super::blocks::{CODE_PADDING, EMOJI_PLACEHOLDER};
12use super::hooks::{open_link, open_profile_link};
12use super::hooks::{open_link, open_profile_link};
13use super::link_tooltip::LinkTooltip;
13
14
14pub(super) const TIME_ROOM: char = '\u{2007}';
15pub(super) const TIME_ROOM: char = '\u{2007}';
15pub(super) const HIT_SLOP: f32 = 12.;
16pub(super) const HIT_SLOP: f32 = 12.;
@@ -272,7 +273,7 @@ impl IntoElement for SelectableRichText {
272
273
273impl Element for SelectableRichText {
274impl Element for SelectableRichText {
274 type RequestLayoutState = Participant;
275 type RequestLayoutState = Participant;
275 type PrepaintState = Hitbox;
276 type PrepaintState = (Hitbox, Option<LinkTooltip>);
276
277
277 fn id(&self) -> Option<ElementId> {
278 fn id(&self) -> Option<ElementId> {
278 Some(self.id.clone())
279 Some(self.id.clone())
@@ -318,7 +319,8 @@ impl Element for SelectableRichText {
318 .with_text_bounds(vec![bounds])
319 .with_text_bounds(vec![bounds])
319 .with_rendered_element(handle, window, cx);
320 .with_rendered_element(handle, window, cx);
320 handle.register(registration, window, cx);
321 handle.register(registration, window, cx);
321 hitbox
322 let tooltip = LinkTooltip::prepaint(global_id, !self.links.is_empty(), window);
323 (hitbox, tooltip)
322 }
324 }
323
325
324 fn paint(
326 fn paint(
@@ -327,7 +329,7 @@ impl Element for SelectableRichText {
327 inspector_id: Option<&InspectorElementId>,
329 inspector_id: Option<&InspectorElementId>,
328 bounds: Bounds<Pixels>,
330 bounds: Bounds<Pixels>,
329 participant: &mut Self::RequestLayoutState,
331 participant: &mut Self::RequestLayoutState,
330 hitbox: &mut Self::PrepaintState,
332 (hitbox, tooltip): &mut Self::PrepaintState,
331 window: &mut Window,
333 window: &mut Window,
332 cx: &mut App,
334 cx: &mut App,
333 ) {
335 ) {
@@ -388,6 +390,14 @@ impl Element for SelectableRichText {
388 CursorStyle::IBeam
390 CursorStyle::IBeam
389 };
391 };
390 window.set_cursor_style(cursor, hitbox);
392 window.set_cursor_style(cursor, hitbox);
393 if let Some(tooltip) = tooltip {
394 let (tooltip_layout, tooltip_links) = (layout.clone(), self.links.clone());
395 tooltip.paint(
396 hitbox,
397 move |position| link_at(&tooltip_layout, &tooltip_links, position),
398 window,
399 );
400 }
391 if !self.links.is_empty() {
401 if !self.links.is_empty() {
392 let (hover_layout, hover_links, hover_hitbox) =
402 let (hover_layout, hover_links, hover_hitbox) =
393 (layout.clone(), self.links.clone(), hitbox.clone());
403 (layout.clone(), self.links.clone(), hitbox.clone());
crates/core/src/draft.rs +136 −1
@@ -2052,7 +2052,77 @@ fn joined_inline(lines: &[DraftLine]) -> String {
2052 2052 .join("<br>")
2053 2053 }
2054 2054
2055 /// The official client sends a link whose text is its own URL with the text cut to this many
2056 /// characters, the last one an ellipsis; the full URL stays in `href` and `title`.
2057 const LINK_TEXT_LIMIT: usize = 100;
2058 const LINK_ELLIPSIS: char = '…';
2059
2060 struct ShortenedLinks {
2061 content: String,
2062 marks: Vec<Mark>,
2063 urls: Vec<String>,
2064 }
2065
2066 /// Shortens the text of each link that spells out its own URL past `LINK_TEXT_LIMIT`.
2067 fn shortened_links(content: &str, marks: &[Mark]) -> Option<ShortenedLinks> {
2068 let mut long: Vec<(Range<usize>, &String)> = marks
2069 .iter()
2070 .filter_map(|mark| match &mark.kind {
2071 MarkKind::Link(url) => {
2072 let text = content.get(mark.range.clone())?;
2073 let spells_url = text == url || link_url(text).as_ref() == Some(url);
2074 (spells_url && text.chars().count() > LINK_TEXT_LIMIT)
2075 .then(|| (mark.range.clone(), url))
2076 }
2077 _ => None,
2078 })
2079 .collect();
2080 if long.is_empty() {
2081 return None;
2082 }
2083 long.sort_by_key(|(range, _)| range.start);
2084 long.dedup();
2085 let urls = long.iter().map(|(_, url)| (*url).clone()).collect();
2086 let mut text = content.to_owned();
2087 let mut marks = marks.to_vec();
2088 for (range, _) in long.into_iter().rev() {
2089 let kept = content[range.clone()]
2090 .char_indices()
2091 .nth(LINK_TEXT_LIMIT - 1)
2092 .map_or(range.len(), |(offset, _)| offset);
2093 let cut = range.start + kept;
2094 let end = cut + LINK_ELLIPSIS.len_utf8();
2095 text.replace_range(cut..range.end, &LINK_ELLIPSIS.to_string());
2096 let moved = |offset: usize| {
2097 if offset <= cut {
2098 offset
2099 } else if offset >= range.end {
2100 offset - range.end + end
2101 } else {
2102 end
2103 }
2104 };
2105 for mark in &mut marks {
2106 mark.range = moved(mark.range.start)..moved(mark.range.end);
2107 }
2108 }
2109 marks.retain(|mark| !mark.range.is_empty());
2110 Some(ShortenedLinks {
2111 content: text,
2112 marks,
2113 urls,
2114 })
2115 }
2116
2055 2117 fn inline_html(content: &str, marks: &[Mark]) -> String {
2118 if let Some(shortened) = shortened_links(content, marks) {
2119 return inline_html_exact(&shortened.content, &shortened.marks, &shortened.urls);
2120 }
2121 inline_html_exact(content, marks, &[])
2122 }
2123
2124 /// `titled` links carry their URL in `title` too, for the hover a shortened text needs.
2125 fn inline_html_exact(content: &str, marks: &[Mark], titled: &[String]) -> String {
2056 2126 let mut boundaries: Vec<usize> = marks
2057 2127 .iter()
2058 2128 .flat_map(|mark| [mark.range.start, mark.range.end])
@@ -2081,7 +2151,13 @@ fn inline_html(content: &str, marks: &[Mark]) -> String {
2081 2151 html.push_str(kind.close_tag());
2082 2152 }
2083 2153 for kind in &active[common..] {
2084 html.push_str(&kind.open_tag());
2154 match kind {
2155 MarkKind::Link(url) if titled.contains(url) => {
2156 let url = escape_html(url);
2157 html.push_str(&format!("<a href=\"{url}\" title=\"{url}\">"));
2158 }
2159 _ => html.push_str(&kind.open_tag()),
2160 }
2085 2161 }
2086 2162 open.extend(active[common..].iter().copied());
2087 2163 html.push_str(&escape_html(&content[segment]));
@@ -2994,6 +3070,65 @@ mod tests {
2994 3070 assert_eq!(draft.to_html(), "<b>a&lt;<i>b </i></b><i>&amp; c</i>");
2995 3071 }
2996 3072
3073 fn long_url(length: usize) -> String {
3074 let head = "https://portal.example/#@contoso/blade/";
3075 format!("{head}{}", "a".repeat(length - head.len()))
3076 }
3077
3078 #[test]
3079 fn html_shortens_a_long_link_that_shows_its_own_url() {
3080 let url = long_url(140);
3081 let draft = Draft::from_markdown(&format!("see {url} now"));
3082 assert_eq!(
3083 draft.to_html(),
3084 format!(
3085 "see <a href=\"{url}\" title=\"{url}\">{}…</a> now",
3086 &url[..99]
3087 )
3088 );
3089 let www = format!("www.{}", &url["https://".len()..]);
3090 let draft = Draft::from_markdown(&www);
3091 assert_eq!(
3092 draft.to_html(),
3093 format!(
3094 "<a href=\"https://{www}\" title=\"https://{www}\">{}…</a>",
3095 &www[..99]
3096 )
3097 );
3098 }
3099
3100 #[test]
3101 fn html_keeps_short_links_and_labels_whole() {
3102 let exact = long_url(100);
3103 assert_eq!(
3104 Draft::from_markdown(&exact).to_html(),
3105 format!("<a href=\"{exact}\">{exact}</a>")
3106 );
3107 let label = "l".repeat(120);
3108 let url = long_url(140);
3109 assert_eq!(
3110 Draft::from_markdown(&format!("[{label}]({url})")).to_html(),
3111 format!("<a href=\"{url}\">{label}</a>")
3112 );
3113 }
3114
3115 #[test]
3116 fn html_shortening_moves_the_marks_after_the_link() {
3117 let url = long_url(130);
3118 let mut draft = Draft::from_markdown(&format!("{url} tail"));
3119 let length = draft.text().len();
3120 draft.toggle(90..length, MarkKind::Bold);
3121 draft.toggle(120..125, MarkKind::Italic);
3122 assert_eq!(
3123 draft.to_html(),
3124 format!(
3125 "<a href=\"{url}\" title=\"{url}\">{}<b>{}…</b></a><b> tail</b>",
3126 &url[..90],
3127 &url[90..99]
3128 )
3129 );
3130 }
3131
2997 3132 #[test]
2998 3133 fn html_covers_every_format() {
2999 3134 let draft = Draft::from_markdown(
@@ -2052,7 +2052,77 @@ fn joined_inline(lines: &[DraftLine]) -> String {
2052 .join("<br>")
2052 .join("<br>")
2053}
2053}
2054
2054
2055/// The official client sends a link whose text is its own URL with the text cut to this many
2056/// characters, the last one an ellipsis; the full URL stays in `href` and `title`.
2057const LINK_TEXT_LIMIT: usize = 100;
2058const LINK_ELLIPSIS: char = '…';
2059
2060struct ShortenedLinks {
2061 content: String,
2062 marks: Vec<Mark>,
2063 urls: Vec<String>,
2064}
2065
2066/// Shortens the text of each link that spells out its own URL past `LINK_TEXT_LIMIT`.
2067fn shortened_links(content: &str, marks: &[Mark]) -> Option<ShortenedLinks> {
2068 let mut long: Vec<(Range<usize>, &String)> = marks
2069 .iter()
2070 .filter_map(|mark| match &mark.kind {
2071 MarkKind::Link(url) => {
2072 let text = content.get(mark.range.clone())?;
2073 let spells_url = text == url || link_url(text).as_ref() == Some(url);
2074 (spells_url && text.chars().count() > LINK_TEXT_LIMIT)
2075 .then(|| (mark.range.clone(), url))
2076 }
2077 _ => None,
2078 })
2079 .collect();
2080 if long.is_empty() {
2081 return None;
2082 }
2083 long.sort_by_key(|(range, _)| range.start);
2084 long.dedup();
2085 let urls = long.iter().map(|(_, url)| (*url).clone()).collect();
2086 let mut text = content.to_owned();
2087 let mut marks = marks.to_vec();
2088 for (range, _) in long.into_iter().rev() {
2089 let kept = content[range.clone()]
2090 .char_indices()
2091 .nth(LINK_TEXT_LIMIT - 1)
2092 .map_or(range.len(), |(offset, _)| offset);
2093 let cut = range.start + kept;
2094 let end = cut + LINK_ELLIPSIS.len_utf8();
2095 text.replace_range(cut..range.end, &LINK_ELLIPSIS.to_string());
2096 let moved = |offset: usize| {
2097 if offset <= cut {
2098 offset
2099 } else if offset >= range.end {
2100 offset - range.end + end
2101 } else {
2102 end
2103 }
2104 };
2105 for mark in &mut marks {
2106 mark.range = moved(mark.range.start)..moved(mark.range.end);
2107 }
2108 }
2109 marks.retain(|mark| !mark.range.is_empty());
2110 Some(ShortenedLinks {
2111 content: text,
2112 marks,
2113 urls,
2114 })
2115}
2116
2055fn inline_html(content: &str, marks: &[Mark]) -> String {
2117fn inline_html(content: &str, marks: &[Mark]) -> String {
2118 if let Some(shortened) = shortened_links(content, marks) {
2119 return inline_html_exact(&shortened.content, &shortened.marks, &shortened.urls);
2120 }
2121 inline_html_exact(content, marks, &[])
2122}
2123
2124/// `titled` links carry their URL in `title` too, for the hover a shortened text needs.
2125fn inline_html_exact(content: &str, marks: &[Mark], titled: &[String]) -> String {
2056 let mut boundaries: Vec<usize> = marks
2126 let mut boundaries: Vec<usize> = marks
2057 .iter()
2127 .iter()
2058 .flat_map(|mark| [mark.range.start, mark.range.end])
2128 .flat_map(|mark| [mark.range.start, mark.range.end])
@@ -2081,7 +2151,13 @@ fn inline_html(content: &str, marks: &[Mark]) -> String {
2081 html.push_str(kind.close_tag());
2151 html.push_str(kind.close_tag());
2082 }
2152 }
2083 for kind in &active[common..] {
2153 for kind in &active[common..] {
2084 html.push_str(&kind.open_tag());
2154 match kind {
2155 MarkKind::Link(url) if titled.contains(url) => {
2156 let url = escape_html(url);
2157 html.push_str(&format!("<a href=\"{url}\" title=\"{url}\">"));
2158 }
2159 _ => html.push_str(&kind.open_tag()),
2160 }
2085 }
2161 }
2086 open.extend(active[common..].iter().copied());
2162 open.extend(active[common..].iter().copied());
2087 html.push_str(&escape_html(&content[segment]));
2163 html.push_str(&escape_html(&content[segment]));
@@ -2994,6 +3070,65 @@ mod tests {
2994 assert_eq!(draft.to_html(), "<b>a&lt;<i>b </i></b><i>&amp; c</i>");
3070 assert_eq!(draft.to_html(), "<b>a&lt;<i>b </i></b><i>&amp; c</i>");
2995 }
3071 }
2996
3072
3073 fn long_url(length: usize) -> String {
3074 let head = "https://portal.example/#@contoso/blade/";
3075 format!("{head}{}", "a".repeat(length - head.len()))
3076 }
3077
3078 #[test]
3079 fn html_shortens_a_long_link_that_shows_its_own_url() {
3080 let url = long_url(140);
3081 let draft = Draft::from_markdown(&format!("see {url} now"));
3082 assert_eq!(
3083 draft.to_html(),
3084 format!(
3085 "see <a href=\"{url}\" title=\"{url}\">{}…</a> now",
3086 &url[..99]
3087 )
3088 );
3089 let www = format!("www.{}", &url["https://".len()..]);
3090 let draft = Draft::from_markdown(&www);
3091 assert_eq!(
3092 draft.to_html(),
3093 format!(
3094 "<a href=\"https://{www}\" title=\"https://{www}\">{}…</a>",
3095 &www[..99]
3096 )
3097 );
3098 }
3099
3100 #[test]
3101 fn html_keeps_short_links_and_labels_whole() {
3102 let exact = long_url(100);
3103 assert_eq!(
3104 Draft::from_markdown(&exact).to_html(),
3105 format!("<a href=\"{exact}\">{exact}</a>")
3106 );
3107 let label = "l".repeat(120);
3108 let url = long_url(140);
3109 assert_eq!(
3110 Draft::from_markdown(&format!("[{label}]({url})")).to_html(),
3111 format!("<a href=\"{url}\">{label}</a>")
3112 );
3113 }
3114
3115 #[test]
3116 fn html_shortening_moves_the_marks_after_the_link() {
3117 let url = long_url(130);
3118 let mut draft = Draft::from_markdown(&format!("{url} tail"));
3119 let length = draft.text().len();
3120 draft.toggle(90..length, MarkKind::Bold);
3121 draft.toggle(120..125, MarkKind::Italic);
3122 assert_eq!(
3123 draft.to_html(),
3124 format!(
3125 "<a href=\"{url}\" title=\"{url}\">{}<b>{}…</b></a><b> tail</b>",
3126 &url[..90],
3127 &url[90..99]
3128 )
3129 );
3130 }
3131
2997 #[test]
3132 #[test]
2998 fn html_covers_every_format() {
3133 fn html_covers_every_format() {
2999 let draft = Draft::from_markdown(
3134 let draft = Draft::from_markdown(
vendor/gpui-pre/PATCH.md +1 −0
@@ -7,3 +7,4 @@ Upstream: crates.io `gpui-pre 0.3.8`. Wired in via `[patch.crates-io]` in the ro
7 7 | File | Change | Why |
8 8 |---|---|---|
9 9 | `src/text_system/line.rs` | `paint_line` and `paint_line_background` place each wrapped line from its leftmost glyph (`segment_left_edges`) instead of its first glyph | Right-to-left runs come back from shaping in visual order over the unwrapped line, so a wrapped Arabic line started off its own right edge and overflowed (GitHub issue 64) |
10 | `src/elements/div.rs` | `ActiveTooltip`, `set_tooltip_on_window` and `register_tooltip_mouse_handlers` are `pub` instead of `pub(crate)` | The message text elements in `app-ui-kit` show a link's URL in a tooltip on hover, with the same delay and hide rules as `InteractiveText` |
@@ -7,3 +7,4 @@ Upstream: crates.io `gpui-pre 0.3.8`. Wired in via `[patch.crates-io]` in the ro
7| File | Change | Why |
7| File | Change | Why |
8|---|---|---|
8|---|---|---|
9| `src/text_system/line.rs` | `paint_line` and `paint_line_background` place each wrapped line from its leftmost glyph (`segment_left_edges`) instead of its first glyph | Right-to-left runs come back from shaping in visual order over the unwrapped line, so a wrapped Arabic line started off its own right edge and overflowed (GitHub issue 64) |
9| `src/text_system/line.rs` | `paint_line` and `paint_line_background` place each wrapped line from its leftmost glyph (`segment_left_edges`) instead of its first glyph | Right-to-left runs come back from shaping in visual order over the unwrapped line, so a wrapped Arabic line started off its own right edge and overflowed (GitHub issue 64) |
10| `src/elements/div.rs` | `ActiveTooltip`, `set_tooltip_on_window` and `register_tooltip_mouse_handlers` are `pub` instead of `pub(crate)` | The message text elements in `app-ui-kit` show a link's URL in a tooltip on hover, with the same delay and hide rules as `InteractiveText` |
vendor/gpui-pre/src/elements/div.rs +10 −3
@@ -3652,7 +3652,10 @@ pub struct ElementHoverState {
3652 3652 pub element: bool,
3653 3653 }
3654 3654
3655 pub(crate) enum ActiveTooltip {
3655 /// The tooltip state an element keeps between frames. Public so custom elements can show a
3656 /// tooltip over part of their content with [register_tooltip_mouse_handlers].
3657 #[allow(missing_docs)]
3658 pub enum ActiveTooltip {
3656 3659 /// Currently delaying before showing the tooltip.
3657 3660 WaitingForShow { _task: Task<()> },
3658 3661 /// Tooltip is visible, element was hovered or for hoverable tooltips, the tooltip was hovered.
@@ -3696,7 +3699,8 @@ pub(crate) fn clear_active_tooltip_if_not_hoverable(
3696 3699 }
3697 3700 }
3698 3701
3699 pub(crate) fn set_tooltip_on_window(
3702 /// Puts a visible tooltip on the window. Call it from a custom element's prepaint.
3703 pub fn set_tooltip_on_window(
3700 3704 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3701 3705 window: &mut Window,
3702 3706 ) -> Option<TooltipId> {
@@ -3709,7 +3713,10 @@ pub(crate) fn set_tooltip_on_window(
3709 3713 Some(window.set_tooltip(tooltip))
3710 3714 }
3711 3715
3712 pub(crate) fn register_tooltip_mouse_handlers(
3716 /// Shows and hides a tooltip as the mouse moves, after the usual delay. Call it from a custom
3717 /// element's paint, with the id [set_tooltip_on_window] returned in prepaint.
3718 #[allow(clippy::too_many_arguments)]
3719 pub fn register_tooltip_mouse_handlers(
3713 3720 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3714 3721 tooltip_id: Option<TooltipId>,
3715 3722 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
@@ -3652,7 +3652,10 @@ pub struct ElementHoverState {
3652 pub element: bool,
3652 pub element: bool,
3653}
3653}
3654
3654
3655pub(crate) enum ActiveTooltip {
3655/// The tooltip state an element keeps between frames. Public so custom elements can show a
3656/// tooltip over part of their content with [register_tooltip_mouse_handlers].
3657#[allow(missing_docs)]
3658pub enum ActiveTooltip {
3656 /// Currently delaying before showing the tooltip.
3659 /// Currently delaying before showing the tooltip.
3657 WaitingForShow { _task: Task<()> },
3660 WaitingForShow { _task: Task<()> },
3658 /// Tooltip is visible, element was hovered or for hoverable tooltips, the tooltip was hovered.
3661 /// Tooltip is visible, element was hovered or for hoverable tooltips, the tooltip was hovered.
@@ -3696,7 +3699,8 @@ pub(crate) fn clear_active_tooltip_if_not_hoverable(
3696 }
3699 }
3697}
3700}
3698
3701
3699pub(crate) fn set_tooltip_on_window(
3702/// Puts a visible tooltip on the window. Call it from a custom element's prepaint.
3703pub fn set_tooltip_on_window(
3700 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3704 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3701 window: &mut Window,
3705 window: &mut Window,
3702) -> Option<TooltipId> {
3706) -> Option<TooltipId> {
@@ -3709,7 +3713,10 @@ pub(crate) fn set_tooltip_on_window(
3709 Some(window.set_tooltip(tooltip))
3713 Some(window.set_tooltip(tooltip))
3710}
3714}
3711
3715
3712pub(crate) fn register_tooltip_mouse_handlers(
3716/// Shows and hides a tooltip as the mouse moves, after the usual delay. Call it from a custom
3717/// element's paint, with the id [set_tooltip_on_window] returned in prepaint.
3718#[allow(clippy::too_many_arguments)]
3719pub fn register_tooltip_mouse_handlers(
3713 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3720 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3714 tooltip_id: Option<TooltipId>,
3721 tooltip_id: Option<TooltipId>,
3715 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3722 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,