BlueGit

ict rusty-teams

Files

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

selectable.rs

f9ed0525 History
selectable.rs 16.7 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_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 // gpui-base updates the selection on drag without notifying a view, so nothing redraws.
385 window.on_mouse_event(|event: &MouseMoveEvent, phase, window, _| {
386 if phase.bubble() && event.pressed_button == Some(MouseButton::Left) {
387 window.refresh();
388 }
389 });
390 if self.links.is_empty() {
391 return;
392 }
393 let links = std::mem::take(&mut self.links);
394 let hitbox = hitbox.clone();
395 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
396 if !phase.bubble() || event.button != MouseButton::Left || !hitbox.is_hovered(window) {
397 return;
398 }
399 if !TextSelection::selected_text(window, cx).is_empty() {
400 return;
401 }
402 if let Some(url) = link_at(&layout, &links, event.position)
403 && !open_profile_link(&url, event.position, cx)
404 {
405 cx.open_url(&url);
406 }
407 });
408 }
409}
410
411#[cfg(test)]
412mod tests {
413 use gpui_kit::base::TextSelection;
414 use gpui_kit::test::TestWindowExt as _;
415 use gpui_kit::{
416 AnyWindowHandle, AppContext as _, Bounds, Context, FontWeight, HighlightStyle, IntoElement,
417 ParentElement as _, Point, Render, Styled as _, TestAppContext, Window, WindowBounds,
418 WindowOptions, div, point, px, size,
419 };
420
421 use super::{PillLine, SelectableRichText, pill_lines};
422
423 const TEXT: &str = "plain bold link";
424
425 struct Message;
426
427 impl Render for Message {
428 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
429 let bold = HighlightStyle {
430 font_weight: Some(FontWeight::BOLD),
431 ..Default::default()
432 };
433 div().w(px(400.)).child(
434 SelectableRichText::new("message", TEXT, vec![(6..10, bold)])
435 .links(vec![(11..15, "https://example.com".to_owned())]),
436 )
437 }
438 }
439
440 fn mount(cx: &mut TestAppContext) -> AnyWindowHandle {
441 cx.update(gpui_kit::init);
442 cx.update(|cx| {
443 let options = WindowOptions {
444 window_bounds: Some(WindowBounds::Windowed(Bounds {
445 origin: Point::default(),
446 size: size(px(400.), px(100.)),
447 })),
448 ..Default::default()
449 };
450 gpui_kit::open_window(options, cx, |_, cx| cx.new(|_| Message))
451 .expect("open test window")
452 .0
453 })
454 }
455
456 #[gpui_kit::test]
457 fn drag_selects_styled_text_for_copy(cx: &mut TestAppContext) {
458 let handle = mount(cx);
459 let selected = cx
460 .update_window(handle, |_, window, cx| {
461 window.render_frame(cx);
462 window.drag(point(px(1.), px(8.)), point(px(399.), px(8.)), cx);
463 window.render_frame(cx);
464 TextSelection::selected_text(window, cx)
465 })
466 .unwrap();
467 assert_eq!(selected, TEXT);
468 assert_eq!(cx.opened_url(), None);
469 }
470
471 #[gpui_kit::test]
472 fn click_on_a_link_opens_it_but_plain_text_does_not(cx: &mut TestAppContext) {
473 let handle = mount(cx);
474 let click = |x: f32, cx: &mut TestAppContext| {
475 cx.update_window(handle, |_, window, cx| {
476 window.render_frame(cx);
477 window.drag(point(px(x), px(8.)), point(px(x), px(8.)), cx);
478 })
479 .unwrap();
480 };
481 click(2., cx);
482 assert_eq!(cx.opened_url(), None);
483 let link_x = (40..400).map(|x| x as f32).find(|x| {
484 click(*x, cx);
485 cx.opened_url().is_some()
486 });
487 assert!(link_x.is_some());
488 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
489 }
490
491 #[test]
492 fn pill_wrapped_whole_onto_next_line_paints_only_there() {
493 let text = "the code";
494 let position = |index: usize| {
495 Some(if index <= 4 {
496 point(px(index as f32 * 10.), px(0.))
497 } else {
498 point(px((index - 4) as f32 * 10.), px(20.))
499 })
500 };
501 assert_eq!(
502 pill_lines(text, 4..8, px(0.), position),
503 vec![PillLine {
504 left: px(0.),
505 right: px(40.),
506 top: px(20.),
507 }]
508 );
509 }
510
511 #[test]
512 fn pill_split_by_a_wrap_paints_one_piece_per_line_without_the_trailing_space() {
513 let text = "ab cd";
514 let position = |index: usize| {
515 Some(if index <= 3 {
516 point(px(index as f32 * 10.), px(0.))
517 } else {
518 point(px((index - 3) as f32 * 10.), px(20.))
519 })
520 };
521 assert_eq!(
522 pill_lines(text, 0..5, px(0.), position),
523 vec![
524 PillLine {
525 left: px(0.),
526 right: px(20.),
527 top: px(0.),
528 },
529 PillLine {
530 left: px(0.),
531 right: px(20.),
532 top: px(20.),
533 },
534 ]
535 );
536 }
537}