BlueGit

ict rusty-teams

Files

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

selectable.rs

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