BlueGit

ict rusty-teams

Files

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

selectable.rs

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