Skip to main content

egui_pop_api/tips/
markup.rs

1//! A tip's text: `{key}` placeholders resolved to the key bindings in
2//! force, then `**bold**` and `` `code` `` drawn.
3
4use egui::text::LayoutJob;
5use egui::{Align, FontSelection, RichText, Style};
6
7/// The commands a text names in `{key:<command>}` placeholders, in
8/// order, each once.
9pub fn named_commands(text: &str) -> Vec<String> {
10    let mut out: Vec<String> = Vec::new();
11    for (inner, _) in placeholders(text) {
12        if let Some(c) = inner.strip_prefix("key:") {
13            let c = c.trim().to_string();
14            if !out.contains(&c) {
15                out.push(c);
16            }
17        }
18    }
19    out
20}
21
22/// Whether a text has a bare `{key}` (its own command's binding).
23pub fn has_own_key(text: &str) -> bool {
24    placeholders(text).iter().any(|(inner, _)| inner == "key")
25}
26
27/// The `{...}` placeholders of a text: what is inside, and where the
28/// whole placeholder is.
29fn placeholders(text: &str) -> Vec<(String, std::ops::Range<usize>)> {
30    let mut out = Vec::new();
31    let mut from = 0;
32    while let Some(open) = text[from..].find('{').map(|i| i + from) {
33        let Some(close) = text[open..].find('}').map(|i| i + open) else {
34            break;
35        };
36        let inner = text[open + 1..close].trim();
37        if inner == "key" || inner.starts_with("key:") {
38            out.push((inner.to_string(), open..close + 1));
39        }
40        from = close + 1;
41    }
42    out
43}
44
45/// Replaces `{key}` with `own`'s text and `{key:<command>}` with
46/// `other(<command>)`'s; a placeholder without an answer stays as it
47/// is.
48pub fn resolve(
49    text: &str,
50    own: Option<&str>,
51    mut other: impl FnMut(&str) -> Option<String>,
52) -> String {
53    let mut out = String::with_capacity(text.len());
54    let mut last = 0;
55    for (inner, range) in placeholders(text) {
56        let with = if inner == "key" {
57            own.map(str::to_string)
58        } else {
59            inner.strip_prefix("key:").and_then(|c| other(c.trim()))
60        };
61        if let Some(with) = with {
62            out.push_str(&text[last..range.start]);
63            out.push_str(&with);
64            last = range.end;
65        }
66    }
67    out.push_str(&text[last..]);
68    out
69}
70
71/// A run of text: plain, bold or code.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub enum Run {
74    Plain,
75    Bold,
76    Code,
77}
78
79/// The text cut into runs (`**bold**`, `` `code` ``; an unclosed mark
80/// is plain text).
81pub fn runs(text: &str) -> Vec<(Run, String)> {
82    let mut out: Vec<(Run, String)> = Vec::new();
83    let mut plain = String::new();
84    let mut rest = text;
85    while !rest.is_empty() {
86        let (mark, kind) = if rest.starts_with("**") {
87            ("**", Run::Bold)
88        } else if rest.starts_with('`') {
89            ("`", Run::Code)
90        } else {
91            let c = rest.chars().next().unwrap_or_default();
92            plain.push(c);
93            rest = &rest[c.len_utf8()..];
94            continue;
95        };
96        let after = &rest[mark.len()..];
97        match after.find(mark) {
98            Some(end) if end > 0 => {
99                if !plain.is_empty() {
100                    out.push((Run::Plain, std::mem::take(&mut plain)));
101                }
102                out.push((kind, after[..end].to_string()));
103                rest = &after[end + mark.len()..];
104            }
105            _ => {
106                plain.push_str(mark);
107                rest = after;
108            }
109        }
110    }
111    if !plain.is_empty() {
112        out.push((Run::Plain, plain));
113    }
114    out
115}
116
117/// The text laid out in a style: bold strong, code in the code style,
118/// wrapping in the width given.
119pub fn job(text: &str, style: &Style, width: f32) -> LayoutJob {
120    let mut job = LayoutJob::default();
121    for (kind, run) in runs(text) {
122        let rich = RichText::new(run);
123        let rich = match kind {
124            Run::Plain => rich,
125            Run::Bold => rich.strong(),
126            Run::Code => rich.code(),
127        };
128        rich.append_to(&mut job, style, FontSelection::Default, Align::Center);
129    }
130    job.wrap.max_width = width;
131    job
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn placeholders_take_the_keys_in_force() {
140        let text = "Press {key}, or {key:app.palette} then {key:none}.";
141        let out = resolve(text, Some("`R`"), |c| {
142            (c == "app.palette").then(|| "`Ctrl+Shift+P`".to_string())
143        });
144        assert_eq!(out, "Press `R`, or `Ctrl+Shift+P` then {key:none}.");
145        assert_eq!(named_commands(text), ["app.palette", "none"]);
146        assert!(has_own_key(text));
147        assert_eq!(resolve("{key}", None, |_| None), "{key}");
148    }
149
150    #[test]
151    fn bold_and_code_are_runs_and_an_unclosed_mark_is_text() {
152        assert_eq!(
153            runs("Press **0** or `R`, a * and a ` stay."),
154            [
155                (Run::Plain, "Press ".to_string()),
156                (Run::Bold, "0".to_string()),
157                (Run::Plain, " or ".to_string()),
158                (Run::Code, "R".to_string()),
159                (Run::Plain, ", a * and a ` stay.".to_string()),
160            ]
161        );
162    }
163}