gpuikit 0.7.0

A UI toolkit for GPUI applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! Inline text styling for markdown rendering.
//!
//! This module provides types for tracking and rendering inline text styles
//! like bold, italic, strikethrough, inline code, and links within markdown
//! text. Code and links stay *inline* — spans within one text run — rather
//! than being flushed as separate block elements, so a sentence survives
//! having a link or a code chip in the middle of it.

use gpui::{FontStyle, FontWeight, HighlightStyle, Hsla, SharedString, StrikethroughStyle};
use std::ops::Range;

/// Inline text style flags that can be combined.
///
/// `link` is an index into the owning [`RichText`]'s URL table rather than
/// the URL itself, which keeps this type `Copy` and keeps span merging
/// correct: two adjacent links to different URLs have different indices, so
/// they never merge into one clickable range.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct InlineStyle {
    pub bold: bool,
    pub italic: bool,
    pub strikethrough: bool,
    pub code: bool,
    pub link: Option<u32>,
}

/// Theme-resolved colors for the inline styles that need them. Resolved by
/// the element (which has the theme) and passed into
/// [`RichText::to_highlights_with`]; `None` leaves that aspect unstyled.
#[derive(Clone, Copy, Debug, Default)]
pub struct InlinePalette {
    /// Background wash behind inline code spans.
    pub code_background: Option<Hsla>,
    /// Text color for link spans (they are also underlined).
    pub link_color: Option<Hsla>,
}

impl InlineStyle {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_bold(mut self) -> Self {
        self.bold = true;
        self
    }

    pub fn with_italic(mut self) -> Self {
        self.italic = true;
        self
    }

    pub fn with_strikethrough(mut self) -> Self {
        self.strikethrough = true;
        self
    }

    pub fn with_code(mut self) -> Self {
        self.code = true;
        self
    }

    pub fn to_highlight_style(self) -> HighlightStyle {
        self.to_highlight_style_with(&InlinePalette::default())
    }

    pub fn to_highlight_style_with(self, palette: &InlinePalette) -> HighlightStyle {
        let mut style = HighlightStyle::default();

        if self.bold {
            style.font_weight = Some(FontWeight::BOLD);
        }

        if self.italic {
            style.font_style = Some(FontStyle::Italic);
        }

        if self.strikethrough {
            style.strikethrough = Some(StrikethroughStyle {
                thickness: gpui::px(1.0),
                ..Default::default()
            });
        }

        if self.code {
            style.background_color = palette.code_background;
        }

        if self.link.is_some() {
            style.color = palette.link_color;
            style.underline = Some(gpui::UnderlineStyle {
                thickness: gpui::px(1.0),
                color: palette.link_color,
                wavy: false,
            });
        }

        style
    }

    pub fn is_empty(&self) -> bool {
        !self.bold && !self.italic && !self.strikethrough && !self.code && self.link.is_none()
    }
}

/// A span of text with associated styling.
#[derive(Clone, Debug)]
pub struct TextSpan {
    pub text: String,
    pub style: InlineStyle,
}

/// Rich text container that holds styled text spans, plus the URL table that
/// link spans index into.
#[derive(Clone, Debug, Default)]
pub struct RichText {
    spans: Vec<TextSpan>,
    links: Vec<SharedString>,
}

impl RichText {
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a link destination, returning the index for
    /// [`InlineStyle::link`] on the spans that carry its text.
    pub fn add_link(&mut self, url: impl Into<SharedString>) -> u32 {
        self.links.push(url.into());
        (self.links.len() - 1) as u32
    }

    /// The registered link destinations, in registration order.
    pub fn links(&self) -> &[SharedString] {
        &self.links
    }

    /// Byte ranges of the flattened text that are links, with their
    /// destinations — the input for an interactive text element's clickable
    /// ranges. Adjacent spans of the same link merge into one range.
    pub fn link_ranges(&self) -> Vec<(Range<usize>, SharedString)> {
        let mut ranges: Vec<(Range<usize>, u32)> = Vec::new();
        let mut offset = 0;
        for span in &self.spans {
            let end = offset + span.text.len();
            if let Some(link) = span.style.link {
                match ranges.last_mut() {
                    Some((range, last)) if *last == link && range.end == offset => {
                        range.end = end;
                    }
                    _ => ranges.push((offset..end, link)),
                }
            }
            offset = end;
        }
        ranges
            .into_iter()
            .filter_map(|(range, ix)| Some((range, self.links.get(ix as usize)?.clone())))
            .collect()
    }

    pub fn push(&mut self, text: impl Into<String>, style: InlineStyle) {
        let text = text.into();
        if text.is_empty() {
            return;
        }

        if let Some(last) = self.spans.last_mut() {
            if last.style == style {
                last.text.push_str(&text);
                return;
            }
        }

        self.spans.push(TextSpan { text, style });
    }

    pub fn push_plain(&mut self, text: impl Into<String>) {
        self.push(text, InlineStyle::default());
    }

    pub fn is_empty(&self) -> bool {
        self.spans.is_empty() || self.spans.iter().all(|s| s.text.is_empty())
    }

    pub fn clear(&mut self) {
        self.spans.clear();
        self.links.clear();
    }

    pub fn to_plain_text(&self) -> String {
        self.spans.iter().map(|s| s.text.as_str()).collect()
    }

    pub fn to_highlights(&self) -> (String, Vec<(Range<usize>, HighlightStyle)>) {
        self.to_highlights_with(&InlinePalette::default())
    }

    pub fn to_highlights_with(
        &self,
        palette: &InlinePalette,
    ) -> (String, Vec<(Range<usize>, HighlightStyle)>) {
        let mut text = String::new();
        let mut highlights = Vec::new();

        for span in &self.spans {
            let start = text.len();
            text.push_str(&span.text);
            let end = text.len();

            if !span.style.is_empty() {
                highlights.push((start..end, span.style.to_highlight_style_with(palette)));
            }
        }

        (text, highlights)
    }

    pub fn spans(&self) -> &[TextSpan] {
        &self.spans
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_inline_style_default() {
        let style = InlineStyle::new();
        assert!(!style.bold);
        assert!(!style.italic);
        assert!(!style.strikethrough);
        assert!(style.is_empty());
    }

    #[test]
    fn test_inline_style_builders() {
        let bold = InlineStyle::new().with_bold();
        assert!(bold.bold);
        assert!(!bold.italic);
        assert!(!bold.is_empty());

        let italic = InlineStyle::new().with_italic();
        assert!(italic.italic);
        assert!(!italic.bold);

        let strike = InlineStyle::new().with_strikethrough();
        assert!(strike.strikethrough);

        let combined = InlineStyle::new()
            .with_bold()
            .with_italic()
            .with_strikethrough();
        assert!(combined.bold);
        assert!(combined.italic);
        assert!(combined.strikethrough);
    }

    #[test]
    fn test_inline_style_to_highlight() {
        let bold = InlineStyle::new().with_bold();
        let highlight = bold.to_highlight_style();
        assert_eq!(highlight.font_weight, Some(FontWeight::BOLD));
        assert_eq!(highlight.font_style, None);

        let italic = InlineStyle::new().with_italic();
        let highlight = italic.to_highlight_style();
        assert_eq!(highlight.font_style, Some(FontStyle::Italic));
        assert_eq!(highlight.font_weight, None);

        let strike = InlineStyle::new().with_strikethrough();
        let highlight = strike.to_highlight_style();
        assert!(highlight.strikethrough.is_some());
    }

    #[test]
    fn test_rich_text_empty() {
        let rt = RichText::new();
        assert!(rt.is_empty());
        assert_eq!(rt.to_plain_text(), "");
    }

    #[test]
    fn test_rich_text_push_plain() {
        let mut rt = RichText::new();
        rt.push_plain("Hello ");
        rt.push_plain("World");
        assert_eq!(rt.to_plain_text(), "Hello World");
    }

    #[test]
    fn test_rich_text_merge_same_style() {
        let mut rt = RichText::new();
        let bold = InlineStyle::new().with_bold();
        rt.push("Hello ", bold);
        rt.push("World", bold);
        assert_eq!(rt.spans().len(), 1);
        assert_eq!(rt.to_plain_text(), "Hello World");
    }

    #[test]
    fn test_rich_text_different_styles() {
        let mut rt = RichText::new();
        let bold = InlineStyle::new().with_bold();
        let italic = InlineStyle::new().with_italic();
        rt.push("Bold", bold);
        rt.push("Italic", italic);
        assert_eq!(rt.spans().len(), 2);
        assert_eq!(rt.to_plain_text(), "BoldItalic");
    }

    #[test]
    fn test_rich_text_highlights() {
        let mut rt = RichText::new();
        let bold = InlineStyle::new().with_bold();
        rt.push_plain("Hello ");
        rt.push("bold", bold);
        rt.push_plain(" world");

        let (text, highlights) = rt.to_highlights();
        assert_eq!(text, "Hello bold world");
        assert_eq!(highlights.len(), 1);
        assert_eq!(highlights[0].0, 6..10);
        assert_eq!(highlights[0].1.font_weight, Some(FontWeight::BOLD));
    }

    #[test]
    fn test_rich_text_skip_empty() {
        let mut rt = RichText::new();
        rt.push_plain("");
        rt.push_plain("Text");
        rt.push_plain("");
        assert_eq!(rt.spans().len(), 1);
    }

    #[test]
    fn test_code_span_styles_without_backticks() {
        let mut rt = RichText::new();
        rt.push_plain("run ");
        rt.push("cargo test", InlineStyle::new().with_code());
        rt.push_plain(" first");

        let palette = InlinePalette {
            code_background: Some(gpui::hsla(0., 0., 0.5, 1.)),
            link_color: None,
        };
        let (text, highlights) = rt.to_highlights_with(&palette);
        assert_eq!(text, "run cargo test first");
        assert_eq!(highlights.len(), 1);
        assert_eq!(highlights[0].0, 4..14);
        assert_eq!(highlights[0].1.background_color, palette.code_background);
    }

    #[test]
    fn test_link_spans_stay_inline_and_click_ranges_resolve() {
        let mut rt = RichText::new();
        rt.push_plain("see ");
        let a = rt.add_link("https://a.example");
        rt.push(
            "first",
            InlineStyle {
                link: Some(a),
                ..Default::default()
            },
        );
        rt.push_plain(" and ");
        let b = rt.add_link("https://b.example");
        rt.push(
            "second",
            InlineStyle {
                link: Some(b),
                ..Default::default()
            },
        );

        // The sentence survives as one text run…
        let (text, _) = rt.to_highlights();
        assert_eq!(text, "see first and second");

        // …with two distinct clickable ranges pointing at their own URLs.
        let ranges = rt.link_ranges();
        assert_eq!(ranges.len(), 2);
        assert_eq!(ranges[0].0, 4..9);
        assert_eq!(ranges[0].1.as_ref(), "https://a.example");
        assert_eq!(ranges[1].0, 14..20);
        assert_eq!(ranges[1].1.as_ref(), "https://b.example");
    }

    #[test]
    fn test_adjacent_spans_of_different_links_do_not_merge() {
        let mut rt = RichText::new();
        let a = rt.add_link("https://a.example");
        let b = rt.add_link("https://b.example");
        rt.push(
            "one",
            InlineStyle {
                link: Some(a),
                ..Default::default()
            },
        );
        rt.push(
            "two",
            InlineStyle {
                link: Some(b),
                ..Default::default()
            },
        );
        assert_eq!(rt.spans().len(), 2);
        assert_eq!(rt.link_ranges().len(), 2);
    }

    #[test]
    fn test_split_link_spans_merge_into_one_range() {
        // A link whose text is interrupted by emphasis is still one link.
        let mut rt = RichText::new();
        let a = rt.add_link("https://a.example");
        let plain = InlineStyle {
            link: Some(a),
            ..Default::default()
        };
        let bold = InlineStyle {
            link: Some(a),
            bold: true,
            ..Default::default()
        };
        rt.push("very ", plain);
        rt.push("bold", bold);
        rt.push(" link", plain);

        let ranges = rt.link_ranges();
        assert_eq!(ranges.len(), 1);
        assert_eq!(ranges[0].0, 0..14);
    }

    #[test]
    fn test_link_styling_applies_color_and_underline() {
        let mut rt = RichText::new();
        let a = rt.add_link("https://a.example");
        rt.push(
            "link",
            InlineStyle {
                link: Some(a),
                ..Default::default()
            },
        );

        let palette = InlinePalette {
            code_background: None,
            link_color: Some(gpui::hsla(0.6, 0.8, 0.5, 1.)),
        };
        let (_, highlights) = rt.to_highlights_with(&palette);
        assert_eq!(highlights.len(), 1);
        assert_eq!(highlights[0].1.color, palette.link_color);
        assert!(highlights[0].1.underline.is_some());
    }

    #[test]
    fn test_clear_drops_links_too() {
        let mut rt = RichText::new();
        let a = rt.add_link("https://a.example");
        rt.push(
            "x",
            InlineStyle {
                link: Some(a),
                ..Default::default()
            },
        );
        rt.clear();
        assert!(rt.is_empty());
        assert!(rt.links().is_empty());
        assert!(rt.link_ranges().is_empty());
    }
}