BlueGit

ict rusty-teams

Files

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

selectable.rs

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