BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-ui-kit / src / render / selectable.rs

selectable.rs

741f7792 History
selectable.rs 17.2 KiB Download Raw
1use std::cell::RefCell;
2use std::ops::Range;
3use std::path::PathBuf;
4use std::rc::Rc;
5
6use gpui_kit::base::{
7 TextSelection, TextSelectionHandle, TextSelectionRegistration, TextSelectionRun, Theme,
8};
9use gpui_kit::*;
10
11use super::blocks::{CODE_PADDING, EMOJI_PLACEHOLDER};
12use super::hooks::{open_link, open_profile_link};
13
14pub(super) const TIME_ROOM: char = '\u{2007}';
15pub(super) const HIT_SLOP: f32 = 12.;
16
17#[derive(Clone)]
18pub struct Participant {
19 pub(super) handle: TextSelectionHandle,
20 pub(super) copied: Rc<RefCell<String>>,
21}
22
23impl Participant {
24 pub(super) fn retained(
25 global_id: Option<&GlobalElementId>,
26 text: &SharedString,
27 window: &mut Window,
28 cx: &mut App,
29 ) -> Participant {
30 window.with_element_state(
31 global_id.expect("selectable text has an element id"),
32 |retained: Option<Participant>, _| {
33 let participant = retained.unwrap_or_else(|| {
34 let handle = TextSelectionHandle::new(text.clone(), cx);
35 let copied = Rc::new(RefCell::new(String::new()));
36 let source = copied.clone();
37 handle.copy_with(move |_| source.borrow().clone(), cx);
38 Participant { handle, copied }
39 });
40 (participant.clone(), participant)
41 },
42 )
43 }
44}
45
46pub(super) const PILL_OUTSET: f32 = 3.;
47const INLINE_IMAGE_SIZE: f32 = 20.;
48pub(super) const PILL_INSET_Y: f32 = 1.;
49
50#[derive(Clone, Debug)]
51pub struct Pill {
52 pub range: Range<usize>,
53 pub fill: Hsla,
54 pub border: Option<Hsla>,
55 pub radius: Pixels,
56}
57
58/// Styled text that takes part in the window text selection, with clickable link ranges.
59pub struct SelectableRichText {
60 id: ElementId,
61 text: SharedString,
62 styled_text: StyledText,
63 links: Vec<(Range<usize>, String)>,
64 pills: Vec<Pill>,
65 inline_images: Vec<(Range<usize>, PathBuf)>,
66}
67
68impl SelectableRichText {
69 pub fn new(
70 id: impl Into<ElementId>,
71 text: impl Into<SharedString>,
72 highlights: Vec<(Range<usize>, HighlightStyle)>,
73 ) -> Self {
74 let text = text.into();
75 SelectableRichText {
76 id: id.into(),
77 styled_text: StyledText::new(text.clone()).with_highlights(highlights),
78 text,
79 links: Vec::new(),
80 pills: Vec::new(),
81 inline_images: Vec::new(),
82 }
83 }
84
85 pub fn links(mut self, links: Vec<(Range<usize>, String)>) -> Self {
86 self.links = links;
87 self
88 }
89
90 pub fn inline_images(mut self, images: Vec<(Range<usize>, PathBuf)>) -> Self {
91 self.inline_images = images;
92 self
93 }
94
95 pub fn font_overrides(mut self, overrides: Vec<(Range<usize>, SharedString)>) -> Self {
96 if !overrides.is_empty() {
97 let styled_text = std::mem::replace(&mut self.styled_text, StyledText::new(""));
98 self.styled_text = styled_text.with_font_family_overrides(overrides);
99 }
100 self
101 }
102
103 pub fn pills(mut self, pills: Vec<Pill>) -> Self {
104 self.pills = pills;
105 self
106 }
107}
108
109fn 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
139fn paint_pills(pills: &[Pill], text: &str, layout: &TextLayout, window: &mut Window) {
140 let line_height = layout.line_height();
141 let bounds = layout.bounds();
142 for pill in pills {
143 let lines = pill_lines(text, pill.range.clone(), bounds.left(), |index| {
144 layout.position_for_index(index)
145 });
146 for line in lines {
147 let line = Bounds::from_corners(
148 point(line.left - px(PILL_OUTSET), line.top + px(PILL_INSET_Y)),
149 point(
150 line.right + px(PILL_OUTSET),
151 line.top + line_height - px(PILL_INSET_Y),
152 ),
153 );
154 let (border_width, border_color) = match pill.border {
155 Some(color) => (px(1.), color),
156 None => (px(0.), transparent_black()),
157 };
158 window.paint_quad(quad(
159 line,
160 pill.radius,
161 pill.fill,
162 border_width,
163 border_color,
164 BorderStyle::Solid,
165 ));
166 }
167 }
168}
169
170#[derive(Debug, PartialEq)]
171struct PillLine {
172 left: Pixels,
173 right: Pixels,
174 top: Pixels,
175}
176
177fn pill_lines(
178 text: &str,
179 range: Range<usize>,
180 line_left: Pixels,
181 position: impl Fn(usize) -> Option<Point<Pixels>>,
182) -> Vec<PillLine> {
183 let mut lines: Vec<PillLine> = Vec::new();
184 let Some(slice) = text.get(range.clone()) else {
185 return lines;
186 };
187 let mut before = position(range.start);
188 for (offset, character) in slice.char_indices() {
189 let after = position(range.start + offset + character.len_utf8());
190 let (Some(start), Some(end)) = (before, after) else {
191 before = after;
192 continue;
193 };
194 before = after;
195 if character == '\n' {
196 continue;
197 }
198 // gpui places a wrap-boundary index at the end of the previous line.
199 let left = if start.y == end.y { start.x } else { line_left };
200 let right = if character.is_whitespace() {
201 left
202 } else {
203 end.x
204 };
205 match lines.last_mut() {
206 Some(line) if line.top == end.y => line.right = right.max(line.right),
207 _ => lines.push(PillLine {
208 left,
209 right,
210 top: end.y,
211 }),
212 }
213 }
214 lines
215}
216
217fn link_at(
218 layout: &TextLayout,
219 links: &[(Range<usize>, String)],
220 position: Point<Pixels>,
221) -> Option<String> {
222 let index = layout.index_for_position(position).ok()?;
223 links
224 .iter()
225 .find(|(range, _)| range.contains(&index))
226 .map(|(_, url)| url.clone())
227}
228
229fn selection_quads(
230 start: Point<Pixels>,
231 end: Point<Pixels>,
232 bounds: Bounds<Pixels>,
233 line_height: Pixels,
234) -> Vec<Bounds<Pixels>> {
235 if start.y == end.y {
236 return vec![Bounds::from_corners(
237 start,
238 point(end.x, end.y + line_height),
239 )];
240 }
241 let mut quads = vec![Bounds::from_corners(
242 start,
243 point(bounds.right(), start.y + line_height),
244 )];
245 if end.y > start.y + line_height {
246 quads.push(Bounds::from_corners(
247 point(bounds.left(), start.y + line_height),
248 point(bounds.right(), end.y),
249 ));
250 }
251 quads.push(Bounds::from_corners(
252 point(bounds.left(), end.y),
253 point(end.x, end.y + line_height),
254 ));
255 quads
256}
257
258impl IntoElement for SelectableRichText {
259 type Element = Self;
260
261 fn into_element(self) -> Self::Element {
262 self
263 }
264}
265
266impl Element for SelectableRichText {
267 type RequestLayoutState = Participant;
268 type PrepaintState = Hitbox;
269
270 fn id(&self) -> Option<ElementId> {
271 Some(self.id.clone())
272 }
273
274 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
275 None
276 }
277
278 fn request_layout(
279 &mut self,
280 global_id: Option<&GlobalElementId>,
281 inspector_id: Option<&InspectorElementId>,
282 window: &mut Window,
283 cx: &mut App,
284 ) -> (LayoutId, Self::RequestLayoutState) {
285 let participant = Participant::retained(global_id, &self.text, window, cx);
286 let (layout_id, ()) = self
287 .styled_text
288 .request_layout(global_id, inspector_id, window, cx);
289 (layout_id, participant)
290 }
291
292 fn prepaint(
293 &mut self,
294 global_id: Option<&GlobalElementId>,
295 inspector_id: Option<&InspectorElementId>,
296 bounds: Bounds<Pixels>,
297 participant: &mut Self::RequestLayoutState,
298 window: &mut Window,
299 cx: &mut App,
300 ) -> Self::PrepaintState {
301 let handle = &participant.handle;
302 self.styled_text
303 .prepaint(global_id, inspector_id, bounds, &mut (), window, cx);
304 let slop = Edges {
305 left: px(HIT_SLOP),
306 right: px(HIT_SLOP),
307 ..Default::default()
308 };
309 let hitbox = window.insert_hitbox(bounds.extend(slop), HitboxBehavior::Normal);
310 let registration = TextSelectionRegistration::new(hitbox.clone(), bounds)
311 .with_text_bounds(vec![bounds])
312 .with_rendered_element(handle, window, cx);
313 handle.register(registration, window, cx);
314 hitbox
315 }
316
317 fn paint(
318 &mut self,
319 global_id: Option<&GlobalElementId>,
320 inspector_id: Option<&InspectorElementId>,
321 bounds: Bounds<Pixels>,
322 participant: &mut Self::RequestLayoutState,
323 hitbox: &mut Self::PrepaintState,
324 window: &mut Window,
325 cx: &mut App,
326 ) {
327 let layout = self.styled_text.layout().clone();
328 let selected_before = TextSelection::selected_text(window, cx);
329 let projection = participant.handle.update_runs(
330 &[TextSelectionRun::new(
331 self.text.clone(),
332 layout.clone(),
333 bounds,
334 )],
335 cx,
336 );
337 if selected_before != TextSelection::selected_text(window, cx) {
338 window.refresh();
339 }
340 paint_pills(&self.pills, &self.text, &layout, window);
341 let color = Theme::global(cx).tokens.colors.selection;
342 let content_end = self.text.trim_end_matches(TIME_ROOM).len();
343 let mut copied = String::new();
344 for range in projection.ranges().iter().flatten() {
345 let end_index = range.end.min(content_end);
346 if end_index <= range.start {
347 continue;
348 }
349 copied.push_str(
350 &self.text[range.start..end_index]
351 .replace(CODE_PADDING, "")
352 .replace(EMOJI_PLACEHOLDER, ""),
353 );
354 let (Some(start), Some(end)) = (
355 layout.position_for_index(range.start),
356 layout.position_for_index(end_index),
357 ) else {
358 continue;
359 };
360 for quad in selection_quads(start, end, layout.bounds(), layout.line_height()) {
361 window.paint_quad(fill(quad, color));
362 }
363 }
364 *participant.copied.borrow_mut() = copied;
365 self.styled_text.paint(
366 global_id,
367 inspector_id,
368 bounds,
369 &mut (),
370 &mut (),
371 window,
372 cx,
373 );
374 paint_inline_images(&self.inline_images, &self.text, &layout, window, cx);
375
376 let hovered_link = hitbox.is_hovered(window)
377 && link_at(&layout, &self.links, window.mouse_position()).is_some();
378 let cursor = if hovered_link {
379 CursorStyle::PointingHand
380 } else {
381 CursorStyle::IBeam
382 };
383 window.set_cursor_style(cursor, hitbox);
384 if !self.links.is_empty() {
385 let (hover_layout, hover_links, hover_hitbox) = (layout.clone(), self.links.clone(), hitbox.clone());
386 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, _| {
387 let over_link = hover_hitbox.is_hovered(window) && link_at(&hover_layout, &hover_links, event.position).is_some();
388 if phase.bubble() && over_link != hovered_link {
389 window.refresh();
390 }
391 });
392 }
393 // gpui-base updates the selection on drag without notifying a view, so nothing redraws.
394 window.on_mouse_event(|event: &MouseMoveEvent, phase, window, _| {
395 if phase.bubble() && event.pressed_button == Some(MouseButton::Left) {
396 window.refresh();
397 }
398 });
399 if self.links.is_empty() {
400 return;
401 }
402 let links = std::mem::take(&mut self.links);
403 let hitbox = hitbox.clone();
404 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
405 if !phase.bubble() || event.button != MouseButton::Left || !hitbox.is_hovered(window) {
406 return;
407 }
408 if !TextSelection::selected_text(window, cx).is_empty() {
409 return;
410 }
411 if let Some(url) = link_at(&layout, &links, event.position)
412 && !open_profile_link(&url, event.position, cx)
413 {
414 open_link(&url, cx);
415 }
416 });
417 }
418}
419
420#[cfg(test)]
421mod tests {
422 use gpui_kit::base::TextSelection;
423 use gpui_kit::test::TestWindowExt as _;
424 use gpui_kit::{
425 AnyWindowHandle, AppContext as _, Bounds, Context, FontWeight, HighlightStyle, IntoElement,
426 ParentElement as _, Point, Render, Styled as _, TestAppContext, Window, WindowBounds,
427 WindowOptions, div, point, px, size,
428 };
429
430 use super::{PillLine, SelectableRichText, pill_lines};
431
432 const TEXT: &str = "plain bold link";
433
434 struct Message;
435
436 impl Render for Message {
437 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
438 let bold = HighlightStyle {
439 font_weight: Some(FontWeight::BOLD),
440 ..Default::default()
441 };
442 div().w(px(400.)).child(
443 SelectableRichText::new("message", TEXT, vec![(6..10, bold)])
444 .links(vec![(11..15, "https://example.com".to_owned())]),
445 )
446 }
447 }
448
449 fn mount(cx: &mut TestAppContext) -> AnyWindowHandle {
450 cx.update(gpui_kit::init);
451 cx.update(|cx| {
452 let options = WindowOptions {
453 window_bounds: Some(WindowBounds::Windowed(Bounds {
454 origin: Point::default(),
455 size: size(px(400.), px(100.)),
456 })),
457 ..Default::default()
458 };
459 gpui_kit::open_window(options, cx, |_, cx| cx.new(|_| Message))
460 .expect("open test window")
461 .0
462 })
463 }
464
465 #[gpui_kit::test]
466 fn drag_selects_styled_text_for_copy(cx: &mut TestAppContext) {
467 let handle = mount(cx);
468 let selected = cx
469 .update_window(handle, |_, window, cx| {
470 window.render_frame(cx);
471 window.drag(point(px(1.), px(8.)), point(px(399.), px(8.)), cx);
472 window.render_frame(cx);
473 TextSelection::selected_text(window, cx)
474 })
475 .unwrap();
476 assert_eq!(selected, TEXT);
477 assert_eq!(cx.opened_url(), None);
478 }
479
480 #[gpui_kit::test]
481 fn click_on_a_link_opens_it_but_plain_text_does_not(cx: &mut TestAppContext) {
482 let handle = mount(cx);
483 let click = |x: f32, cx: &mut TestAppContext| {
484 cx.update_window(handle, |_, window, cx| {
485 window.render_frame(cx);
486 window.drag(point(px(x), px(8.)), point(px(x), px(8.)), cx);
487 })
488 .unwrap();
489 };
490 click(2., cx);
491 assert_eq!(cx.opened_url(), None);
492 let link_x = (40..400).map(|x| x as f32).find(|x| {
493 click(*x, cx);
494 cx.opened_url().is_some()
495 });
496 assert!(link_x.is_some());
497 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
498 }
499
500 #[test]
501 fn pill_wrapped_whole_onto_next_line_paints_only_there() {
502 let text = "the code";
503 let position = |index: usize| {
504 Some(if index <= 4 {
505 point(px(index as f32 * 10.), px(0.))
506 } else {
507 point(px((index - 4) as f32 * 10.), px(20.))
508 })
509 };
510 assert_eq!(
511 pill_lines(text, 4..8, px(0.), position),
512 vec![PillLine {
513 left: px(0.),
514 right: px(40.),
515 top: px(20.),
516 }]
517 );
518 }
519
520 #[test]
521 fn pill_split_by_a_wrap_paints_one_piece_per_line_without_the_trailing_space() {
522 let text = "ab cd";
523 let position = |index: usize| {
524 Some(if index <= 3 {
525 point(px(index as f32 * 10.), px(0.))
526 } else {
527 point(px((index - 3) as f32 * 10.), px(20.))
528 })
529 };
530 assert_eq!(
531 pill_lines(text, 0..5, px(0.), position),
532 vec![
533 PillLine {
534 left: px(0.),
535 right: px(20.),
536 top: px(0.),
537 },
538 PillLine {
539 left: px(0.),
540 right: px(20.),
541 top: px(20.),
542 },
543 ]
544 );
545 }
546}