Skip to main content

xrack_runtime/
styled_text.rs

1use crate::Color;
2use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};
3use std::{borrow::Cow, sync::Arc};
4use unicode_segmentation::UnicodeSegmentation;
5
6#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
7pub struct TextStyle {
8    pub bold: bool,
9    pub italic: bool,
10    pub monospace: bool,
11    pub strikethrough: bool,
12    pub underline: bool,
13    pub color: Option<Color>,
14}
15
16/// A half-open UTF-8 byte range. Gaps use the element's base style.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub struct StyledRun {
19    pub start: usize,
20    pub end: usize,
21    pub style: TextStyle,
22}
23
24/// A link's visible text range and its application-defined destination.
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct StyledLink {
27    pub start: usize,
28    pub end: usize,
29    pub href: Cow<'static, str>,
30}
31
32#[derive(Clone, Debug)]
33enum Storage {
34    Compiled(&'static str, &'static [StyledRun], &'static [StyledLink]),
35    Owned(Arc<str>, Arc<[StyledRun]>, Arc<[StyledLink]>),
36}
37
38/// Immutable text with inline styles. Cloning shares the underlying data.
39#[derive(Clone, Debug)]
40pub struct StyledText(Storage);
41
42#[derive(Debug, thiserror::Error, PartialEq, Eq)]
43pub enum StyledTextError {
44    #[error("style ranges must be ordered, nonempty and aligned to grapheme boundaries")]
45    InvalidRange,
46    #[error("link ranges must be ordered, nonempty and aligned to grapheme boundaries")]
47    InvalidLinkRange,
48    #[error("unsupported Markdown syntax: {0}")]
49    Unsupported(&'static str),
50}
51
52impl StyledText {
53    #[doc(hidden)]
54    pub const fn from_compiled(text: &'static str, runs: &'static [StyledRun]) -> Self {
55        Self::from_compiled_parts(text, runs, &[])
56    }
57
58    #[doc(hidden)]
59    pub const fn from_compiled_parts(
60        text: &'static str,
61        runs: &'static [StyledRun],
62        links: &'static [StyledLink],
63    ) -> Self {
64        Self(Storage::Compiled(text, runs, links))
65    }
66
67    pub fn from_plain_text(text: impl Into<String>) -> Self {
68        Self(Storage::Owned(
69            text.into().into(),
70            Arc::default(),
71            Arc::default(),
72        ))
73    }
74
75    pub fn from_runs(
76        text: impl Into<String>,
77        runs: Vec<StyledRun>,
78    ) -> Result<Self, StyledTextError> {
79        Self::from_parts(text, runs, Vec::new())
80    }
81
82    pub fn from_parts(
83        text: impl Into<String>,
84        runs: Vec<StyledRun>,
85        links: Vec<StyledLink>,
86    ) -> Result<Self, StyledTextError> {
87        let text = text.into();
88        if !valid_ranges(&text, runs.iter().map(|run| (run.start, run.end))) {
89            return Err(StyledTextError::InvalidRange);
90        }
91        if !valid_ranges(&text, links.iter().map(|link| (link.start, link.end))) {
92            return Err(StyledTextError::InvalidLinkRange);
93        }
94        Ok(Self(Storage::Owned(text.into(), runs.into(), links.into())))
95    }
96
97    pub fn text(&self) -> &str {
98        match &self.0 {
99            Storage::Compiled(text, ..) => text,
100            Storage::Owned(text, ..) => text,
101        }
102    }
103
104    pub fn runs(&self) -> &[StyledRun] {
105        match &self.0 {
106            Storage::Compiled(_, runs, _) => runs,
107            Storage::Owned(_, runs, _) => runs,
108        }
109    }
110
111    pub fn links(&self) -> &[StyledLink] {
112        match &self.0 {
113            Storage::Compiled(_, _, links) => links,
114            Storage::Owned(_, _, links) => links,
115        }
116    }
117
118    pub fn from_markdown(source: &str) -> Result<Self, StyledTextError> {
119        let mut builder = Markdown::default();
120        let mut style = TextStyle::default();
121        let mut stack = Vec::new();
122        for event in Parser::new_ext(source, Options::ENABLE_STRIKETHROUGH) {
123            match event {
124                Event::Start(tag) => {
125                    stack.push(style);
126                    match tag {
127                        Tag::Paragraph => {}
128                        Tag::Strong | Tag::Heading { .. } => style.bold = true,
129                        Tag::Emphasis => style.italic = true,
130                        Tag::CodeBlock(_) => style.monospace = true,
131                        Tag::Strikethrough => style.strikethrough = true,
132                        Tag::HtmlBlock => return Err(StyledTextError::Unsupported("HTML")),
133                        Tag::Link { dest_url, .. } => builder.begin_link(dest_url.into_string()),
134                        Tag::Image { .. } => return Err(StyledTextError::Unsupported("images")),
135                        _ => return Err(StyledTextError::Unsupported("block or inline element")),
136                    }
137                }
138                Event::End(tag) => {
139                    style = stack.pop().unwrap_or_default();
140                    if tag == TagEnd::Link {
141                        builder.end_link();
142                    }
143                    if matches!(
144                        tag,
145                        TagEnd::Paragraph | TagEnd::Heading(_) | TagEnd::CodeBlock
146                    ) {
147                        builder.paragraph_break = true;
148                    }
149                }
150                Event::Text(text) => builder.append(&text, style),
151                Event::Code(text) => builder.append(
152                    &text,
153                    TextStyle {
154                        monospace: true,
155                        ..style
156                    },
157                ),
158                Event::SoftBreak => builder.append(" ", style),
159                Event::HardBreak => builder.append("\n", style),
160                Event::Html(_) | Event::InlineHtml(_) => {
161                    return Err(StyledTextError::Unsupported("HTML"));
162                }
163                _ => return Err(StyledTextError::Unsupported("inline element")),
164            }
165        }
166        Ok(builder.finish())
167    }
168}
169
170impl Default for StyledText {
171    fn default() -> Self {
172        Self::from_compiled("", &[])
173    }
174}
175
176impl PartialEq for StyledText {
177    fn eq(&self, other: &Self) -> bool {
178        self.text() == other.text() && self.runs() == other.runs() && self.links() == other.links()
179    }
180}
181
182impl Eq for StyledText {}
183
184fn valid_ranges(text: &str, ranges: impl Iterator<Item = (usize, usize)>) -> bool {
185    let mut boundaries = text
186        .grapheme_indices(true)
187        .map(|(index, _)| index)
188        .chain(std::iter::once(text.len()))
189        .peekable();
190    let mut previous_end = 0;
191    for (start, end) in ranges {
192        if start < previous_end || start >= end {
193            return false;
194        }
195        for offset in [start, end] {
196            while boundaries.peek().is_some_and(|&index| index < offset) {
197                boundaries.next();
198            }
199            if boundaries.peek().copied() != Some(offset) {
200                return false;
201            }
202        }
203        previous_end = end;
204    }
205    true
206}
207
208#[derive(Default)]
209struct Markdown {
210    text: String,
211    runs: Vec<StyledRun>,
212    links: Vec<StyledLink>,
213    active_link: Option<StyledLink>,
214    paragraph_break: bool,
215}
216
217impl Markdown {
218    fn begin_link(&mut self, href: String) {
219        self.active_link = Some(StyledLink {
220            start: 0,
221            end: 0,
222            href: Cow::Owned(href),
223        });
224    }
225
226    fn end_link(&mut self) {
227        if let Some(link) = self.active_link.take().filter(|link| link.start < link.end) {
228            self.links.push(link);
229        }
230    }
231
232    fn append(&mut self, text: &str, style: TextStyle) {
233        if text.is_empty() {
234            return;
235        }
236        if std::mem::take(&mut self.paragraph_break) && !self.text.is_empty() {
237            if !self.text.ends_with('\n') {
238                self.text.push('\n');
239            }
240            if !self.text.ends_with("\n\n") {
241                self.text.push('\n');
242            }
243        }
244        let start = self.text.len();
245        self.text.push_str(text);
246        if let Some(link) = &mut self.active_link {
247            if link.start == link.end {
248                link.start = start;
249            }
250            link.end = self.text.len();
251        }
252        push_run(&mut self.runs, start, self.text.len(), style);
253    }
254
255    fn finish(self) -> StyledText {
256        // Markdown delimiters can fall between the code points of one grapheme.
257        // The base code point's style applies to the entire grapheme in that case.
258        let mut runs = Vec::new();
259        let mut links = self.links.iter().peekable();
260        let mut normalized_links: Vec<StyledLink> = Vec::new();
261        let mut last_link_start = None;
262        let mut index = 0;
263        for (start, grapheme) in self.text.grapheme_indices(true) {
264            while self.runs.get(index).is_some_and(|run| run.end <= start) {
265                index += 1;
266            }
267            while links.peek().is_some_and(|link| link.end <= start) {
268                links.next();
269            }
270            if let Some(link) = links.peek().filter(|link| link.start <= start) {
271                let end = start + grapheme.len();
272                if last_link_start == Some(link.start)
273                    && let Some(previous) = normalized_links.last_mut()
274                {
275                    previous.end = end;
276                } else {
277                    normalized_links.push(StyledLink {
278                        start,
279                        end,
280                        href: link.href.clone(),
281                    });
282                    last_link_start = Some(link.start);
283                }
284            }
285            if let Some(run) = self.runs.get(index).filter(|run| run.start <= start) {
286                push_run(&mut runs, start, start + grapheme.len(), run.style);
287            }
288        }
289        StyledText(Storage::Owned(
290            self.text.into(),
291            runs.into(),
292            normalized_links.into(),
293        ))
294    }
295}
296
297fn push_run(runs: &mut Vec<StyledRun>, start: usize, end: usize, style: TextStyle) {
298    if style == TextStyle::default() {
299        return;
300    }
301    if let Some(last) = runs.last_mut()
302        && last.end == start
303        && last.style == style
304    {
305        last.end = end;
306    } else {
307        runs.push(StyledRun { start, end, style });
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    #[test]
316    fn markdown_merges_nested_styles_and_preserves_paragraphs() {
317        let text = StyledText::from_markdown("**粗体 *italic***\n\n`code` ~~old~~").unwrap();
318        assert_eq!(text.text(), "粗体 italic\n\ncode old");
319        let runs = text.runs();
320        assert_eq!(runs.len(), 4);
321        let value = |run: &StyledRun| &text.text()[run.start..run.end];
322        assert_eq!(value(&runs[0]), "粗体 ");
323        assert!(runs[0].style.bold && !runs[0].style.italic);
324        assert_eq!(value(&runs[1]), "italic");
325        assert!(runs[1].style.bold && runs[1].style.italic);
326        assert_eq!(value(&runs[2]), "code");
327        assert!(runs[2].style.monospace);
328        assert_eq!(value(&runs[3]), "old");
329        assert!(runs[3].style.strikethrough);
330    }
331
332    #[test]
333    fn markdown_link_ranges_keep_graphemes_and_distinguish_adjacent_anchors() {
334        let text = StyledText::from_markdown("[a](#first)&#769;[**b**](#first)").unwrap();
335        assert_eq!(text.text(), "a\u{301}b");
336        assert_eq!(
337            text.links(),
338            &[
339                StyledLink {
340                    start: 0,
341                    end: 3,
342                    href: "#first".into()
343                },
344                StyledLink {
345                    start: 3,
346                    end: 4,
347                    href: "#first".into()
348                },
349            ]
350        );
351        assert!(text.runs()[0].style.bold);
352        assert_eq!(
353            StyledText::from_parts(
354                text.text(),
355                vec![],
356                vec![StyledLink {
357                    start: 0,
358                    end: 1,
359                    href: "#invalid".into()
360                },]
361            )
362            .unwrap_err(),
363            StyledTextError::InvalidLinkRange,
364        );
365    }
366
367    #[test]
368    fn inline_styles_cannot_split_a_grapheme() {
369        let plain = "a\u{301}🧑‍💻";
370        let style = TextStyle {
371            bold: true,
372            ..Default::default()
373        };
374        let invalid = StyledRun {
375            start: 0,
376            end: 1,
377            style,
378        };
379        assert_eq!(
380            StyledText::from_runs(plain, vec![invalid]).unwrap_err(),
381            StyledTextError::InvalidRange
382        );
383        let text = StyledText::from_markdown("**a**&#769;🧑‍💻").unwrap();
384        assert_eq!(text.text(), plain);
385        assert_eq!(
386            text.runs(),
387            &[StyledRun {
388                end: "a\u{301}".len(),
389                ..invalid
390            }]
391        );
392    }
393}