BlueGit

ict rusty-teams

Files

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

selectable.rs

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