Skip to main content

gpui_material_extras/rich_text/
selectable_text.rs

1use std::{
2    ops::Range,
3    sync::atomic::{AtomicU64, Ordering},
4};
5
6use gpui::{
7    App, Bounds, ElementId, FontWeight, HighlightStyle, Hsla, InteractiveElement, IntoElement,
8    MouseButton, ParentElement, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement,
9    Styled, TextAlign, TextStyleRefinement, WhiteSpace, Window, div, px,
10};
11use gpui_base::{SelectableText as BaseSelectableText, TestSupportExt};
12use gpui_material_foundation::{color, current_material_theme, font_for_style};
13use gpui_material_theme::{ColorRole, Direction, LayoutPolicy, TypeRole, TypographyEmphasis};
14
15static NEXT_GROUP_ORDER_BASE: AtomicU64 = AtomicU64::new(1);
16
17/// Shared reading-order group coordinating multiple [`SelectableText`] elements
18/// that form one continuous selectable document.
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub struct SelectableTextGroup {
21    order_base: u64,
22    label: SharedString,
23}
24
25impl SelectableTextGroup {
26    /// Creates a new shared selection group with a unique document-order namespace.
27    pub fn new(label: impl Into<SharedString>, _cx: &mut App) -> Self {
28        let slot = NEXT_GROUP_ORDER_BASE.fetch_add(1, Ordering::Relaxed);
29        Self {
30            order_base: slot.saturating_mul(1_000_000),
31            label: label.into(),
32        }
33    }
34
35    /// Returns the group label supplied at construction.
36    pub fn label(&self) -> &SharedString {
37        &self.label
38    }
39}
40
41type RevealCallback = Box<dyn Fn(Bounds<Pixels>, &mut Window, &mut App)>;
42
43/// Typography-aware Material 3 text supporting pointer drag selection,
44/// `Ctrl/Cmd+C` clipboard copy (through `MaterialRoot`), and Material
45/// `PrimaryContainer` selection highlights.
46#[derive(IntoElement)]
47pub struct SelectableText {
48    id: ElementId,
49    value: SharedString,
50    role: TypeRole,
51    emphasis: TypographyEmphasis,
52    font_scale: f32,
53    color: Option<ColorRole>,
54    color_override: Option<Hsla>,
55    selection_color: Option<Hsla>,
56    align: Option<TextAlign>,
57    wrap: bool,
58    highlights: Vec<(Range<usize>, HighlightStyle)>,
59    group: Option<SelectableTextGroup>,
60    document_order: u64,
61    reveal_range: Option<Range<usize>>,
62    on_reveal: Option<RevealCallback>,
63    accessible_label: Option<SharedString>,
64}
65
66impl SelectableText {
67    /// Creates selectable text with the default [`TypeRole::BodyLarge`] role and wrapping enabled.
68    pub fn new(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
69        Self {
70            id: id.into(),
71            value: value.into(),
72            role: TypeRole::BodyLarge,
73            emphasis: TypographyEmphasis::Baseline,
74            font_scale: 1.0,
75            color: None,
76            color_override: None,
77            selection_color: None,
78            align: None,
79            wrap: true,
80            highlights: Vec::new(),
81            group: None,
82            document_order: 0,
83            reveal_range: None,
84            on_reveal: None,
85            accessible_label: None,
86        }
87    }
88
89    /// Creates selectable text styled with [`TypeRole::DisplayLarge`].
90    pub fn display_large(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
91        Self::new(id, value).role(TypeRole::DisplayLarge)
92    }
93
94    /// Creates selectable text styled with [`TypeRole::DisplayMedium`].
95    pub fn display_medium(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
96        Self::new(id, value).role(TypeRole::DisplayMedium)
97    }
98
99    /// Creates selectable text styled with [`TypeRole::DisplaySmall`].
100    pub fn display_small(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
101        Self::new(id, value).role(TypeRole::DisplaySmall)
102    }
103
104    /// Creates selectable text styled with [`TypeRole::HeadlineLarge`].
105    pub fn headline_large(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
106        Self::new(id, value).role(TypeRole::HeadlineLarge)
107    }
108
109    /// Creates selectable text styled with [`TypeRole::HeadlineMedium`].
110    pub fn headline_medium(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
111        Self::new(id, value).role(TypeRole::HeadlineMedium)
112    }
113
114    /// Creates selectable text styled with [`TypeRole::HeadlineSmall`].
115    pub fn headline_small(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
116        Self::new(id, value).role(TypeRole::HeadlineSmall)
117    }
118
119    /// Creates selectable text styled with [`TypeRole::TitleLarge`].
120    pub fn title_large(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
121        Self::new(id, value).role(TypeRole::TitleLarge)
122    }
123
124    /// Creates selectable text styled with [`TypeRole::TitleMedium`].
125    pub fn title_medium(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
126        Self::new(id, value).role(TypeRole::TitleMedium)
127    }
128
129    /// Creates selectable text styled with [`TypeRole::TitleSmall`].
130    pub fn title_small(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
131        Self::new(id, value).role(TypeRole::TitleSmall)
132    }
133
134    /// Creates selectable text styled with [`TypeRole::BodyLarge`].
135    pub fn body_large(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
136        Self::new(id, value).role(TypeRole::BodyLarge)
137    }
138
139    /// Creates selectable text styled with [`TypeRole::BodyMedium`].
140    pub fn body_medium(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
141        Self::new(id, value).role(TypeRole::BodyMedium)
142    }
143
144    /// Creates selectable text styled with [`TypeRole::BodySmall`].
145    pub fn body_small(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
146        Self::new(id, value).role(TypeRole::BodySmall)
147    }
148
149    /// Creates selectable text styled with [`TypeRole::LabelLarge`].
150    pub fn label_large(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
151        Self::new(id, value).role(TypeRole::LabelLarge)
152    }
153
154    /// Creates selectable text styled with [`TypeRole::LabelMedium`].
155    pub fn label_medium(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
156        Self::new(id, value).role(TypeRole::LabelMedium)
157    }
158
159    /// Creates selectable text styled with [`TypeRole::LabelSmall`].
160    pub fn label_small(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
161        Self::new(id, value).role(TypeRole::LabelSmall)
162    }
163
164    /// Sets the Material typography scale role. Defaults to [`TypeRole::BodyLarge`].
165    pub fn role(mut self, role: TypeRole) -> Self {
166        self.role = role;
167        self
168    }
169
170    /// Selects emphasized typography weight when `true`, or baseline weight when `false`.
171    pub fn emphasized(mut self, emphasized: bool) -> Self {
172        self.emphasis = if emphasized {
173            TypographyEmphasis::Emphasized
174        } else {
175            TypographyEmphasis::Baseline
176        };
177        self
178    }
179
180    /// Applies an additional font-size multiplier on top of the active theme's typography scale.
181    /// Non-finite or non-positive scales are ignored.
182    pub fn font_scale(mut self, scale: f32) -> Self {
183        if scale.is_finite() && scale > 0.0 {
184            self.font_scale = scale;
185        }
186        self
187    }
188
189    /// Resolves the text color from the active theme's semantic color role.
190    pub fn color(mut self, role: ColorRole) -> Self {
191        self.color = Some(role);
192        self.color_override = None;
193        self
194    }
195
196    /// Sets a literal text color. A later call to [`Self::color`] restores theme-role lookup.
197    pub fn color_override(mut self, color: impl Into<Hsla>) -> Self {
198        self.color_override = Some(color.into());
199        self
200    }
201
202    /// Sets the text color to [`ColorRole::OnSurfaceVariant`].
203    pub fn muted(self) -> Self {
204        self.color(ColorRole::OnSurfaceVariant)
205    }
206
207    /// Overrides the selection highlight background. Defaults to Material
208    /// `PrimaryContainer` with translucent wash for readability.
209    pub fn selection_color(mut self, color: impl Into<Hsla>) -> Self {
210        self.selection_color = Some(color.into());
211        self
212    }
213
214    /// Sets explicit horizontal text alignment. Defaults to the theme's logical start edge.
215    pub fn align(mut self, align: TextAlign) -> Self {
216        self.align = Some(align);
217        self
218    }
219
220    /// Sets whether text wraps at the available width (defaults to `true`).
221    pub fn wrap(mut self, wrap: bool) -> Self {
222        self.wrap = wrap;
223        self
224    }
225
226    /// Applies ordered, non-overlapping UTF-8 byte-range highlights (such as search matches).
227    pub fn highlights(
228        mut self,
229        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
230    ) -> Self {
231        self.highlights = highlights.into_iter().collect();
232        self
233    }
234
235    /// Joins a shared [`SelectableTextGroup`] so drag selection can span multiple elements.
236    pub fn group(mut self, group: &SelectableTextGroup) -> Self {
237        self.group = Some(group.clone());
238        self
239    }
240
241    /// Sets the reading order of this run within its [`SelectableTextGroup`].
242    pub fn document_order(mut self, order: u64) -> Self {
243        self.document_order = order;
244        self
245    }
246
247    /// Requests that the line containing the start of `range` (UTF-8 byte offset) scroll into view.
248    pub fn reveal_range(mut self, range: Range<usize>) -> Self {
249        self.reveal_range = Some(range);
250        self
251    }
252
253    /// Receives the bounds of a revealed line for custom scroll containers.
254    pub fn on_reveal(
255        mut self,
256        handler: impl Fn(Bounds<Pixels>, &mut Window, &mut App) + 'static,
257    ) -> Self {
258        self.on_reveal = Some(Box::new(handler));
259        self
260    }
261
262    /// Overrides the accessible label (defaults to the text value itself).
263    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
264        self.accessible_label = Some(label.into());
265        self
266    }
267}
268
269impl RenderOnce for SelectableText {
270    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
271        let theme = current_material_theme(window, cx);
272        let style = LayoutPolicy::scale_text(
273            theme.typography.style(self.role, self.emphasis),
274            self.font_scale,
275        );
276        let font = font_for_style(&theme.typography, style, cx);
277        let tint = self.color_override.unwrap_or_else(|| {
278            self.color.map_or_else(
279                || color(theme.colors.color(ColorRole::OnSurface)),
280                |role| color(theme.colors.color(role)),
281            )
282        });
283        let selection_bg = self.selection_color.unwrap_or_else(|| {
284            color(theme.colors.color(ColorRole::PrimaryContainer)).opacity(0.75)
285        });
286        let align = self
287            .align
288            .unwrap_or(if theme.layout.direction == Direction::Rtl {
289                TextAlign::Right
290            } else {
291                TextAlign::Left
292            });
293
294        let text_style = TextStyleRefinement {
295            color: Some(tint),
296            font_family: Some(font.family),
297            font_features: Some(font.features),
298            font_fallbacks: font.fallbacks,
299            font_size: Some(px(style.size).into()),
300            line_height: Some(px(style.line_height).into()),
301            font_weight: Some(FontWeight(f32::from(style.weight))),
302            font_style: Some(font.style),
303            text_align: Some(align),
304            white_space: Some(if self.wrap {
305                WhiteSpace::Normal
306            } else {
307                WhiteSpace::Nowrap
308            }),
309            ..Default::default()
310        };
311
312        let run_id = (self.id.clone(), "run");
313        let order = self.group.as_ref().map_or(self.document_order, |group| {
314            group.order_base.saturating_add(self.document_order)
315        });
316        let mut base = BaseSelectableText::new(run_id, self.value.clone())
317            .document_order(order)
318            .text_style(text_style)
319            .selection_color(selection_bg);
320
321        if !self.highlights.is_empty() {
322            base = base.highlights(self.highlights);
323        }
324        if let Some(range) = self.reveal_range {
325            base = base.reveal_range(range);
326        }
327        if let Some(handler) = self.on_reveal {
328            base = base.on_reveal(handler);
329        }
330
331        let accessible_name = self.accessible_label.unwrap_or_else(|| self.value.clone());
332        let focus_handle = window
333            .use_keyed_state((self.id.clone(), "selection-focus"), cx, |_, cx| {
334                cx.focus_handle().tab_stop(false)
335            })
336            .read(cx)
337            .clone();
338        let focus_on_press = focus_handle.clone();
339
340        div()
341            .id(self.id)
342            .test_support()
343            .track_focus(&focus_handle)
344            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
345                focus_on_press.focus(window, cx);
346            })
347            .role(Role::Label)
348            .aria_label(accessible_name)
349            .aria_value(self.value)
350            .min_w_0()
351            .cursor_text()
352            .child(base)
353    }
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359
360    #[test]
361    fn selectable_text_shorthands_and_muted_set_expected_defaults() {
362        let cases = [
363            (
364                SelectableText::display_large("a", "x"),
365                TypeRole::DisplayLarge,
366            ),
367            (
368                SelectableText::headline_medium("b", "x"),
369                TypeRole::HeadlineMedium,
370            ),
371            (SelectableText::title_small("c", "x"), TypeRole::TitleSmall),
372            (SelectableText::body_medium("d", "x"), TypeRole::BodyMedium),
373            (SelectableText::label_small("e", "x"), TypeRole::LabelSmall),
374        ];
375        for (text, role) in cases {
376            assert_eq!(text.role, role);
377            assert!(text.wrap);
378        }
379        let muted = SelectableText::body_small("m", "hint").muted().wrap(false);
380        assert_eq!(muted.color, Some(ColorRole::OnSurfaceVariant));
381        assert!(!muted.wrap);
382    }
383}