| 1 | use std::ops::Range; |
| 2 | |
| 3 | use gpui_kit::base::{ |
| 4 | TextSelection, TextSelectionHandle, TextSelectionRegistration, TextSelectionRun, Theme, |
| 5 | }; |
| 6 | use gpui_kit::*; |
| 7 | |
| 8 | /// Styled text that takes part in the window text selection, with clickable link ranges. |
| 9 | pub struct SelectableRichText { |
| 10 | id: ElementId, |
| 11 | text: SharedString, |
| 12 | styled_text: StyledText, |
| 13 | links: Vec<(Range<usize>, String)>, |
| 14 | } |
| 15 | |
| 16 | impl SelectableRichText { |
| 17 | pub fn new( |
| 18 | id: impl Into<ElementId>, |
| 19 | text: impl Into<SharedString>, |
| 20 | highlights: Vec<(Range<usize>, HighlightStyle)>, |
| 21 | ) -> Self { |
| 22 | let text = text.into(); |
| 23 | SelectableRichText { |
| 24 | id: id.into(), |
| 25 | styled_text: StyledText::new(text.clone()).with_highlights(highlights), |
| 26 | text, |
| 27 | links: Vec::new(), |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | pub fn links(mut self, links: Vec<(Range<usize>, String)>) -> Self { |
| 32 | self.links = links; |
| 33 | self |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | fn link_at( |
| 38 | layout: &TextLayout, |
| 39 | links: &[(Range<usize>, String)], |
| 40 | position: Point<Pixels>, |
| 41 | ) -> Option<String> { |
| 42 | let index = layout.index_for_position(position).ok()?; |
| 43 | links |
| 44 | .iter() |
| 45 | .find(|(range, _)| range.contains(&index)) |
| 46 | .map(|(_, url)| url.clone()) |
| 47 | } |
| 48 | |
| 49 | fn selection_quads( |
| 50 | start: Point<Pixels>, |
| 51 | end: Point<Pixels>, |
| 52 | bounds: Bounds<Pixels>, |
| 53 | line_height: Pixels, |
| 54 | ) -> Vec<Bounds<Pixels>> { |
| 55 | if start.y == end.y { |
| 56 | return vec![Bounds::from_corners( |
| 57 | start, |
| 58 | point(end.x, end.y + line_height), |
| 59 | )]; |
| 60 | } |
| 61 | let mut quads = vec![Bounds::from_corners( |
| 62 | start, |
| 63 | point(bounds.right(), start.y + line_height), |
| 64 | )]; |
| 65 | if end.y > start.y + line_height { |
| 66 | quads.push(Bounds::from_corners( |
| 67 | point(bounds.left(), start.y + line_height), |
| 68 | point(bounds.right(), end.y), |
| 69 | )); |
| 70 | } |
| 71 | quads.push(Bounds::from_corners( |
| 72 | point(bounds.left(), end.y), |
| 73 | point(end.x, end.y + line_height), |
| 74 | )); |
| 75 | quads |
| 76 | } |
| 77 | |
| 78 | impl IntoElement for SelectableRichText { |
| 79 | type Element = Self; |
| 80 | |
| 81 | fn into_element(self) -> Self::Element { |
| 82 | self |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | impl Element for SelectableRichText { |
| 87 | type RequestLayoutState = TextSelectionHandle; |
| 88 | type PrepaintState = Hitbox; |
| 89 | |
| 90 | fn id(&self) -> Option<ElementId> { |
| 91 | Some(self.id.clone()) |
| 92 | } |
| 93 | |
| 94 | fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { |
| 95 | None |
| 96 | } |
| 97 | |
| 98 | fn request_layout( |
| 99 | &mut self, |
| 100 | global_id: Option<&GlobalElementId>, |
| 101 | inspector_id: Option<&InspectorElementId>, |
| 102 | window: &mut Window, |
| 103 | cx: &mut App, |
| 104 | ) -> (LayoutId, Self::RequestLayoutState) { |
| 105 | let handle = window.with_element_state( |
| 106 | global_id.expect("SelectableRichText has an element id"), |
| 107 | |retained: Option<TextSelectionHandle>, _| { |
| 108 | let handle = |
| 109 | retained.unwrap_or_else(|| TextSelectionHandle::new(self.text.clone(), cx)); |
| 110 | (handle.clone(), handle) |
| 111 | }, |
| 112 | ); |
| 113 | let (layout_id, ()) = self |
| 114 | .styled_text |
| 115 | .request_layout(global_id, inspector_id, window, cx); |
| 116 | (layout_id, handle) |
| 117 | } |
| 118 | |
| 119 | fn prepaint( |
| 120 | &mut self, |
| 121 | global_id: Option<&GlobalElementId>, |
| 122 | inspector_id: Option<&InspectorElementId>, |
| 123 | bounds: Bounds<Pixels>, |
| 124 | handle: &mut Self::RequestLayoutState, |
| 125 | window: &mut Window, |
| 126 | cx: &mut App, |
| 127 | ) -> Self::PrepaintState { |
| 128 | self.styled_text |
| 129 | .prepaint(global_id, inspector_id, bounds, &mut (), window, cx); |
| 130 | let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal); |
| 131 | let registration = TextSelectionRegistration::new(hitbox.clone(), bounds) |
| 132 | .with_text_bounds(vec![bounds]) |
| 133 | .with_rendered_element(handle, window, cx); |
| 134 | handle.register(registration, window, cx); |
| 135 | hitbox |
| 136 | } |
| 137 | |
| 138 | fn paint( |
| 139 | &mut self, |
| 140 | global_id: Option<&GlobalElementId>, |
| 141 | inspector_id: Option<&InspectorElementId>, |
| 142 | bounds: Bounds<Pixels>, |
| 143 | handle: &mut Self::RequestLayoutState, |
| 144 | hitbox: &mut Self::PrepaintState, |
| 145 | window: &mut Window, |
| 146 | cx: &mut App, |
| 147 | ) { |
| 148 | let layout = self.styled_text.layout().clone(); |
| 149 | let selected_before = TextSelection::selected_text(window, cx); |
| 150 | let projection = handle.update_runs( |
| 151 | &[TextSelectionRun::new( |
| 152 | self.text.clone(), |
| 153 | layout.clone(), |
| 154 | bounds, |
| 155 | )], |
| 156 | cx, |
| 157 | ); |
| 158 | if selected_before != TextSelection::selected_text(window, cx) { |
| 159 | window.refresh(); |
| 160 | } |
| 161 | let color = Theme::global(cx).tokens.colors.selection; |
| 162 | for range in projection.ranges().iter().flatten() { |
| 163 | let (Some(start), Some(end)) = ( |
| 164 | layout.position_for_index(range.start), |
| 165 | layout.position_for_index(range.end), |
| 166 | ) else { |
| 167 | continue; |
| 168 | }; |
| 169 | for quad in selection_quads(start, end, layout.bounds(), layout.line_height()) { |
| 170 | window.paint_quad(fill(quad, color)); |
| 171 | } |
| 172 | } |
| 173 | self.styled_text.paint( |
| 174 | global_id, |
| 175 | inspector_id, |
| 176 | bounds, |
| 177 | &mut (), |
| 178 | &mut (), |
| 179 | window, |
| 180 | cx, |
| 181 | ); |
| 182 | |
| 183 | let hovered_link = hitbox.is_hovered(window) |
| 184 | && link_at(&layout, &self.links, window.mouse_position()).is_some(); |
| 185 | let cursor = if hovered_link { |
| 186 | CursorStyle::PointingHand |
| 187 | } else { |
| 188 | CursorStyle::IBeam |
| 189 | }; |
| 190 | window.set_cursor_style(cursor, hitbox); |
| 191 | if self.links.is_empty() { |
| 192 | return; |
| 193 | } |
| 194 | let links = std::mem::take(&mut self.links); |
| 195 | let hitbox = hitbox.clone(); |
| 196 | window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| { |
| 197 | if !phase.bubble() || event.button != MouseButton::Left || !hitbox.is_hovered(window) { |
| 198 | return; |
| 199 | } |
| 200 | if !TextSelection::selected_text(window, cx).is_empty() { |
| 201 | return; |
| 202 | } |
| 203 | if let Some(url) = link_at(&layout, &links, event.position) { |
| 204 | cx.open_url(&url); |
| 205 | } |
| 206 | }); |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | #[cfg(test)] |
| 211 | mod tests { |
| 212 | use gpui_kit::base::TextSelection; |
| 213 | use gpui_kit::test::TestWindowExt as _; |
| 214 | use gpui_kit::{ |
| 215 | AnyWindowHandle, AppContext as _, Bounds, Context, FontWeight, HighlightStyle, IntoElement, |
| 216 | ParentElement as _, Point, Render, Styled as _, TestAppContext, Window, WindowBounds, |
| 217 | WindowOptions, div, point, px, size, |
| 218 | }; |
| 219 | |
| 220 | use super::SelectableRichText; |
| 221 | |
| 222 | const TEXT: &str = "plain bold link"; |
| 223 | |
| 224 | struct Message; |
| 225 | |
| 226 | impl Render for Message { |
| 227 | fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { |
| 228 | let bold = HighlightStyle { |
| 229 | font_weight: Some(FontWeight::BOLD), |
| 230 | ..Default::default() |
| 231 | }; |
| 232 | div().w(px(400.)).child( |
| 233 | SelectableRichText::new("message", TEXT, vec![(6..10, bold)]) |
| 234 | .links(vec![(11..15, "https://example.com".to_owned())]), |
| 235 | ) |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | fn mount(cx: &mut TestAppContext) -> AnyWindowHandle { |
| 240 | cx.update(gpui_kit::init); |
| 241 | cx.update(|cx| { |
| 242 | let options = WindowOptions { |
| 243 | window_bounds: Some(WindowBounds::Windowed(Bounds { |
| 244 | origin: Point::default(), |
| 245 | size: size(px(400.), px(100.)), |
| 246 | })), |
| 247 | ..Default::default() |
| 248 | }; |
| 249 | gpui_kit::open_window(options, cx, |_, cx| cx.new(|_| Message)) |
| 250 | .expect("open test window") |
| 251 | .0 |
| 252 | }) |
| 253 | } |
| 254 | |
| 255 | #[gpui_kit::test] |
| 256 | fn drag_selects_styled_text_for_copy(cx: &mut TestAppContext) { |
| 257 | let handle = mount(cx); |
| 258 | let selected = cx |
| 259 | .update_window(handle, |_, window, cx| { |
| 260 | window.render_frame(cx); |
| 261 | window.drag(point(px(1.), px(8.)), point(px(399.), px(8.)), cx); |
| 262 | window.render_frame(cx); |
| 263 | TextSelection::selected_text(window, cx) |
| 264 | }) |
| 265 | .unwrap(); |
| 266 | assert_eq!(selected, TEXT); |
| 267 | assert_eq!(cx.opened_url(), None); |
| 268 | } |
| 269 | |
| 270 | #[gpui_kit::test] |
| 271 | fn click_on_a_link_opens_it_but_plain_text_does_not(cx: &mut TestAppContext) { |
| 272 | let handle = mount(cx); |
| 273 | let click = |x: f32, cx: &mut TestAppContext| { |
| 274 | cx.update_window(handle, |_, window, cx| { |
| 275 | window.render_frame(cx); |
| 276 | window.drag(point(px(x), px(8.)), point(px(x), px(8.)), cx); |
| 277 | }) |
| 278 | .unwrap(); |
| 279 | }; |
| 280 | click(2., cx); |
| 281 | assert_eq!(cx.opened_url(), None); |
| 282 | let link_x = (40..400).map(|x| x as f32).find(|x| { |
| 283 | click(*x, cx); |
| 284 | cx.opened_url().is_some() |
| 285 | }); |
| 286 | assert!(link_x.is_some()); |
| 287 | assert_eq!(cx.opened_url().as_deref(), Some("https://example.com")); |
| 288 | } |
| 289 | } |