| 1 | use std::cell::RefCell; |
| 2 | use std::ops::Range; |
| 3 | use std::rc::Rc; |
| 4 | |
| 5 | use gpui_kit::base::{ |
| 6 | TextSelection, TextSelectionHandle, TextSelectionRegistration, TextSelectionRun, Theme, |
| 7 | }; |
| 8 | use gpui_kit::*; |
| 9 | |
| 10 | use super::blocks::CODE_PADDING; |
| 11 | |
| 12 | const TIME_ROOM: char = '\u{2007}'; |
| 13 | const HIT_SLOP: f32 = 12.; |
| 14 | |
| 15 | #[derive(Clone)] |
| 16 | pub struct Participant { |
| 17 | handle: TextSelectionHandle, |
| 18 | copied: Rc<RefCell<String>>, |
| 19 | } |
| 20 | |
| 21 | const PILL_OUTSET: f32 = 3.; |
| 22 | const PILL_INSET_Y: f32 = 1.; |
| 23 | |
| 24 | #[derive(Clone, Debug)] |
| 25 | pub struct Pill { |
| 26 | pub range: Range<usize>, |
| 27 | pub fill: Hsla, |
| 28 | pub border: Option<Hsla>, |
| 29 | pub radius: Pixels, |
| 30 | } |
| 31 | |
| 32 | /// Styled text that takes part in the window text selection, with clickable link ranges. |
| 33 | pub struct SelectableRichText { |
| 34 | id: ElementId, |
| 35 | text: SharedString, |
| 36 | styled_text: StyledText, |
| 37 | links: Vec<(Range<usize>, String)>, |
| 38 | pills: Vec<Pill>, |
| 39 | } |
| 40 | |
| 41 | impl SelectableRichText { |
| 42 | pub fn new( |
| 43 | id: impl Into<ElementId>, |
| 44 | text: impl Into<SharedString>, |
| 45 | highlights: Vec<(Range<usize>, HighlightStyle)>, |
| 46 | ) -> Self { |
| 47 | let text = text.into(); |
| 48 | SelectableRichText { |
| 49 | id: id.into(), |
| 50 | styled_text: StyledText::new(text.clone()).with_highlights(highlights), |
| 51 | text, |
| 52 | links: Vec::new(), |
| 53 | pills: Vec::new(), |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | pub fn links(mut self, links: Vec<(Range<usize>, String)>) -> Self { |
| 58 | self.links = links; |
| 59 | self |
| 60 | } |
| 61 | |
| 62 | pub fn font_overrides(mut self, overrides: Vec<(Range<usize>, SharedString)>) -> Self { |
| 63 | if !overrides.is_empty() { |
| 64 | let styled_text = std::mem::replace(&mut self.styled_text, StyledText::new("")); |
| 65 | self.styled_text = styled_text.with_font_family_overrides(overrides); |
| 66 | } |
| 67 | self |
| 68 | } |
| 69 | |
| 70 | pub fn pills(mut self, pills: Vec<Pill>) -> Self { |
| 71 | self.pills = pills; |
| 72 | self |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | fn paint_pills(pills: &[Pill], layout: &TextLayout, window: &mut Window) { |
| 77 | let line_height = layout.line_height(); |
| 78 | let bounds = layout.bounds(); |
| 79 | for pill in pills { |
| 80 | let (Some(start), Some(end)) = ( |
| 81 | layout.position_for_index(pill.range.start), |
| 82 | layout.position_for_index(pill.range.end), |
| 83 | ) else { |
| 84 | continue; |
| 85 | }; |
| 86 | for line in selection_quads(start, end, bounds, line_height) { |
| 87 | let line = Bounds::from_corners( |
| 88 | point(line.left() - px(PILL_OUTSET), line.top() + px(PILL_INSET_Y)), |
| 89 | point( |
| 90 | line.right() + px(PILL_OUTSET), |
| 91 | line.top() + line_height - px(PILL_INSET_Y), |
| 92 | ), |
| 93 | ); |
| 94 | let (border_width, border_color) = match pill.border { |
| 95 | Some(color) => (px(1.), color), |
| 96 | None => (px(0.), transparent_black()), |
| 97 | }; |
| 98 | window.paint_quad(quad( |
| 99 | line, |
| 100 | pill.radius, |
| 101 | pill.fill, |
| 102 | border_width, |
| 103 | border_color, |
| 104 | BorderStyle::Solid, |
| 105 | )); |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | fn link_at( |
| 111 | layout: &TextLayout, |
| 112 | links: &[(Range<usize>, String)], |
| 113 | position: Point<Pixels>, |
| 114 | ) -> Option<String> { |
| 115 | let index = layout.index_for_position(position).ok()?; |
| 116 | links |
| 117 | .iter() |
| 118 | .find(|(range, _)| range.contains(&index)) |
| 119 | .map(|(_, url)| url.clone()) |
| 120 | } |
| 121 | |
| 122 | fn selection_quads( |
| 123 | start: Point<Pixels>, |
| 124 | end: Point<Pixels>, |
| 125 | bounds: Bounds<Pixels>, |
| 126 | line_height: Pixels, |
| 127 | ) -> Vec<Bounds<Pixels>> { |
| 128 | if start.y == end.y { |
| 129 | return vec![Bounds::from_corners( |
| 130 | start, |
| 131 | point(end.x, end.y + line_height), |
| 132 | )]; |
| 133 | } |
| 134 | let mut quads = vec![Bounds::from_corners( |
| 135 | start, |
| 136 | point(bounds.right(), start.y + line_height), |
| 137 | )]; |
| 138 | if end.y > start.y + line_height { |
| 139 | quads.push(Bounds::from_corners( |
| 140 | point(bounds.left(), start.y + line_height), |
| 141 | point(bounds.right(), end.y), |
| 142 | )); |
| 143 | } |
| 144 | quads.push(Bounds::from_corners( |
| 145 | point(bounds.left(), end.y), |
| 146 | point(end.x, end.y + line_height), |
| 147 | )); |
| 148 | quads |
| 149 | } |
| 150 | |
| 151 | impl IntoElement for SelectableRichText { |
| 152 | type Element = Self; |
| 153 | |
| 154 | fn into_element(self) -> Self::Element { |
| 155 | self |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | impl Element for SelectableRichText { |
| 160 | type RequestLayoutState = Participant; |
| 161 | type PrepaintState = Hitbox; |
| 162 | |
| 163 | fn id(&self) -> Option<ElementId> { |
| 164 | Some(self.id.clone()) |
| 165 | } |
| 166 | |
| 167 | fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { |
| 168 | None |
| 169 | } |
| 170 | |
| 171 | fn request_layout( |
| 172 | &mut self, |
| 173 | global_id: Option<&GlobalElementId>, |
| 174 | inspector_id: Option<&InspectorElementId>, |
| 175 | window: &mut Window, |
| 176 | cx: &mut App, |
| 177 | ) -> (LayoutId, Self::RequestLayoutState) { |
| 178 | let participant = window.with_element_state( |
| 179 | global_id.expect("SelectableRichText has an element id"), |
| 180 | |retained: Option<Participant>, _| { |
| 181 | let participant = retained.unwrap_or_else(|| { |
| 182 | let handle = TextSelectionHandle::new(self.text.clone(), cx); |
| 183 | let copied = Rc::new(RefCell::new(String::new())); |
| 184 | let source = copied.clone(); |
| 185 | handle.copy_with(move |_| source.borrow().clone(), cx); |
| 186 | Participant { handle, copied } |
| 187 | }); |
| 188 | (participant.clone(), participant) |
| 189 | }, |
| 190 | ); |
| 191 | let (layout_id, ()) = self |
| 192 | .styled_text |
| 193 | .request_layout(global_id, inspector_id, window, cx); |
| 194 | (layout_id, participant) |
| 195 | } |
| 196 | |
| 197 | fn prepaint( |
| 198 | &mut self, |
| 199 | global_id: Option<&GlobalElementId>, |
| 200 | inspector_id: Option<&InspectorElementId>, |
| 201 | bounds: Bounds<Pixels>, |
| 202 | participant: &mut Self::RequestLayoutState, |
| 203 | window: &mut Window, |
| 204 | cx: &mut App, |
| 205 | ) -> Self::PrepaintState { |
| 206 | let handle = &participant.handle; |
| 207 | self.styled_text |
| 208 | .prepaint(global_id, inspector_id, bounds, &mut (), window, cx); |
| 209 | let slop = Edges { |
| 210 | left: px(HIT_SLOP), |
| 211 | right: px(HIT_SLOP), |
| 212 | ..Default::default() |
| 213 | }; |
| 214 | let hitbox = window.insert_hitbox(bounds.extend(slop), HitboxBehavior::Normal); |
| 215 | let registration = TextSelectionRegistration::new(hitbox.clone(), bounds) |
| 216 | .with_text_bounds(vec![bounds]) |
| 217 | .with_rendered_element(handle, window, cx); |
| 218 | handle.register(registration, window, cx); |
| 219 | hitbox |
| 220 | } |
| 221 | |
| 222 | fn paint( |
| 223 | &mut self, |
| 224 | global_id: Option<&GlobalElementId>, |
| 225 | inspector_id: Option<&InspectorElementId>, |
| 226 | bounds: Bounds<Pixels>, |
| 227 | participant: &mut Self::RequestLayoutState, |
| 228 | hitbox: &mut Self::PrepaintState, |
| 229 | window: &mut Window, |
| 230 | cx: &mut App, |
| 231 | ) { |
| 232 | let layout = self.styled_text.layout().clone(); |
| 233 | let selected_before = TextSelection::selected_text(window, cx); |
| 234 | let projection = participant.handle.update_runs( |
| 235 | &[TextSelectionRun::new( |
| 236 | self.text.clone(), |
| 237 | layout.clone(), |
| 238 | bounds, |
| 239 | )], |
| 240 | cx, |
| 241 | ); |
| 242 | if selected_before != TextSelection::selected_text(window, cx) { |
| 243 | window.refresh(); |
| 244 | } |
| 245 | paint_pills(&self.pills, &layout, window); |
| 246 | let color = Theme::global(cx).tokens.colors.selection; |
| 247 | let content_end = self.text.trim_end_matches(TIME_ROOM).len(); |
| 248 | let mut copied = String::new(); |
| 249 | for range in projection.ranges().iter().flatten() { |
| 250 | let end_index = range.end.min(content_end); |
| 251 | if end_index <= range.start { |
| 252 | continue; |
| 253 | } |
| 254 | copied.push_str(&self.text[range.start..end_index].replace(CODE_PADDING, "")); |
| 255 | let (Some(start), Some(end)) = ( |
| 256 | layout.position_for_index(range.start), |
| 257 | layout.position_for_index(end_index), |
| 258 | ) else { |
| 259 | continue; |
| 260 | }; |
| 261 | for quad in selection_quads(start, end, layout.bounds(), layout.line_height()) { |
| 262 | window.paint_quad(fill(quad, color)); |
| 263 | } |
| 264 | } |
| 265 | *participant.copied.borrow_mut() = copied; |
| 266 | self.styled_text.paint( |
| 267 | global_id, |
| 268 | inspector_id, |
| 269 | bounds, |
| 270 | &mut (), |
| 271 | &mut (), |
| 272 | window, |
| 273 | cx, |
| 274 | ); |
| 275 | |
| 276 | let hovered_link = hitbox.is_hovered(window) |
| 277 | && link_at(&layout, &self.links, window.mouse_position()).is_some(); |
| 278 | let cursor = if hovered_link { |
| 279 | CursorStyle::PointingHand |
| 280 | } else { |
| 281 | CursorStyle::IBeam |
| 282 | }; |
| 283 | window.set_cursor_style(cursor, hitbox); |
| 284 | // gpui-base updates the selection on drag without notifying a view, so nothing redraws. |
| 285 | window.on_mouse_event(|event: &MouseMoveEvent, phase, window, _| { |
| 286 | if phase.bubble() && event.pressed_button == Some(MouseButton::Left) { |
| 287 | window.refresh(); |
| 288 | } |
| 289 | }); |
| 290 | if self.links.is_empty() { |
| 291 | return; |
| 292 | } |
| 293 | let links = std::mem::take(&mut self.links); |
| 294 | let hitbox = hitbox.clone(); |
| 295 | window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| { |
| 296 | if !phase.bubble() || event.button != MouseButton::Left || !hitbox.is_hovered(window) { |
| 297 | return; |
| 298 | } |
| 299 | if !TextSelection::selected_text(window, cx).is_empty() { |
| 300 | return; |
| 301 | } |
| 302 | if let Some(url) = link_at(&layout, &links, event.position) { |
| 303 | cx.open_url(&url); |
| 304 | } |
| 305 | }); |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | #[cfg(test)] |
| 310 | mod tests { |
| 311 | use gpui_kit::base::TextSelection; |
| 312 | use gpui_kit::test::TestWindowExt as _; |
| 313 | use gpui_kit::{ |
| 314 | AnyWindowHandle, AppContext as _, Bounds, Context, FontWeight, HighlightStyle, IntoElement, |
| 315 | ParentElement as _, Point, Render, Styled as _, TestAppContext, Window, WindowBounds, |
| 316 | WindowOptions, div, point, px, size, |
| 317 | }; |
| 318 | |
| 319 | use super::SelectableRichText; |
| 320 | |
| 321 | const TEXT: &str = "plain bold link"; |
| 322 | |
| 323 | struct Message; |
| 324 | |
| 325 | impl Render for Message { |
| 326 | fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { |
| 327 | let bold = HighlightStyle { |
| 328 | font_weight: Some(FontWeight::BOLD), |
| 329 | ..Default::default() |
| 330 | }; |
| 331 | div().w(px(400.)).child( |
| 332 | SelectableRichText::new("message", TEXT, vec![(6..10, bold)]) |
| 333 | .links(vec![(11..15, "https://example.com".to_owned())]), |
| 334 | ) |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | fn mount(cx: &mut TestAppContext) -> AnyWindowHandle { |
| 339 | cx.update(gpui_kit::init); |
| 340 | cx.update(|cx| { |
| 341 | let options = WindowOptions { |
| 342 | window_bounds: Some(WindowBounds::Windowed(Bounds { |
| 343 | origin: Point::default(), |
| 344 | size: size(px(400.), px(100.)), |
| 345 | })), |
| 346 | ..Default::default() |
| 347 | }; |
| 348 | gpui_kit::open_window(options, cx, |_, cx| cx.new(|_| Message)) |
| 349 | .expect("open test window") |
| 350 | .0 |
| 351 | }) |
| 352 | } |
| 353 | |
| 354 | #[gpui_kit::test] |
| 355 | fn drag_selects_styled_text_for_copy(cx: &mut TestAppContext) { |
| 356 | let handle = mount(cx); |
| 357 | let selected = cx |
| 358 | .update_window(handle, |_, window, cx| { |
| 359 | window.render_frame(cx); |
| 360 | window.drag(point(px(1.), px(8.)), point(px(399.), px(8.)), cx); |
| 361 | window.render_frame(cx); |
| 362 | TextSelection::selected_text(window, cx) |
| 363 | }) |
| 364 | .unwrap(); |
| 365 | assert_eq!(selected, TEXT); |
| 366 | assert_eq!(cx.opened_url(), None); |
| 367 | } |
| 368 | |
| 369 | #[gpui_kit::test] |
| 370 | fn click_on_a_link_opens_it_but_plain_text_does_not(cx: &mut TestAppContext) { |
| 371 | let handle = mount(cx); |
| 372 | let click = |x: f32, cx: &mut TestAppContext| { |
| 373 | cx.update_window(handle, |_, window, cx| { |
| 374 | window.render_frame(cx); |
| 375 | window.drag(point(px(x), px(8.)), point(px(x), px(8.)), cx); |
| 376 | }) |
| 377 | .unwrap(); |
| 378 | }; |
| 379 | click(2., cx); |
| 380 | assert_eq!(cx.opened_url(), None); |
| 381 | let link_x = (40..400).map(|x| x as f32).find(|x| { |
| 382 | click(*x, cx); |
| 383 | cx.opened_url().is_some() |
| 384 | }); |
| 385 | assert!(link_x.is_some()); |
| 386 | assert_eq!(cx.opened_url().as_deref(), Some("https://example.com")); |
| 387 | } |
| 388 | } |