Skip to main content

egui_pop_api/tips/
file.rs

1//! Tips declared in files: `tips/<id>.md`, a header between `---` lines,
2//! then a `# Title` heading and the text.
3//!
4//! ```text
5//! ---
6//! id: photos.rate
7//! surface: focusedPanel == 'photos.grid'
8//! command: photos.rate
9//! target: photos.rating
10//! ---
11//! # Rate quickly
12//!
13//! Press {key} to rate the selected photos, **0** to clear the rating.
14//! ```
15//!
16//! | Header | What | Default |
17//! |---|---|---|
18//! | `id` | the tip's id, prefixed by its plugin's | the file's name |
19//! | `surface` | a `when` clause: where the tip makes sense | anywhere |
20//! | `command` | the command it teaches; once used, the tip is not picked | none |
21//! | `target` | the name of what it is about ([`super::target`]) | none: a corner |
22//! | `contextual` | `true`: shown only where the application asks ([`super::hint`]) | `false` |
23//!
24//! The text keeps paragraphs (a blank line), `**bold**`, `` `code` ``,
25//! `{key}` (the command's key binding) and `{key:<command>}` (another
26//! command's).
27
28use std::fmt;
29use std::path::Path;
30
31use egui_pop_model::ids::CommandId;
32
33use super::Tip;
34
35/// What is wrong with a tip's file.
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct TipError {
38    /// The file's name (`photos.rate.md`).
39    pub file: String,
40    /// The line, from 1 (0: the whole file).
41    pub line: usize,
42    pub message: String,
43}
44
45impl fmt::Display for TipError {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        if self.line == 0 {
48            write!(f, "{}: {}", self.file, self.message)
49        } else {
50            write!(f, "{}:{}: {}", self.file, self.line, self.message)
51        }
52    }
53}
54
55impl std::error::Error for TipError {}
56
57/// The header's keys.
58pub const HEADER_KEYS: [&str; 5] = ["id", "surface", "command", "target", "contextual"];
59
60/// Reads a tip from a file's text; `file` is its name (`photos.rate.md`),
61/// whose stem is the id when the header has none.
62pub fn parse(file: &str, source: &str) -> Result<Tip, TipError> {
63    let err = |line: usize, message: String| TipError {
64        file: file.to_string(),
65        line,
66        message,
67    };
68    let stem = file.strip_suffix(".md").unwrap_or(file);
69    let lines: Vec<&str> = source.lines().collect();
70    let mut at = 0;
71    while at < lines.len() && lines[at].trim().is_empty() {
72        at += 1;
73    }
74    let mut header: Vec<(usize, &str, &str)> = Vec::new();
75    if lines.get(at).map(|l| l.trim()) == Some("---") {
76        at += 1;
77        loop {
78            let Some(line) = lines.get(at) else {
79                return Err(err(at, "the header has no closing `---`".into()));
80            };
81            at += 1;
82            let line = line.trim();
83            if line == "---" {
84                break;
85            }
86            if line.is_empty() || line.starts_with('#') {
87                continue;
88            }
89            let Some((k, v)) = line.split_once(':') else {
90                return Err(err(at, format!("`{line}` is not `key: value`")));
91            };
92            let (k, v) = (k.trim(), v.trim());
93            if !HEADER_KEYS.contains(&k) {
94                return Err(err(
95                    at,
96                    format!("unknown key `{k}` (known: {})", HEADER_KEYS.join(", ")),
97                ));
98            }
99            if header.iter().any(|(_, h, _)| *h == k) {
100                return Err(err(at, format!("`{k}` is given twice")));
101            }
102            header.push((at, k, v));
103        }
104    }
105    let get = |k: &str| {
106        header
107            .iter()
108            .find(|(_, h, _)| *h == k)
109            .map(|(_, _, v)| unquote(v))
110    };
111    let id = get("id").unwrap_or(stem).to_string();
112    if id.is_empty() || id.chars().any(char::is_whitespace) {
113        return Err(err(0, format!("`{id}` is not a tip id")));
114    }
115    while at < lines.len() && lines[at].trim().is_empty() {
116        at += 1;
117    }
118    let Some(title) = lines
119        .get(at)
120        .and_then(|l| l.trim().strip_prefix("# "))
121        .map(str::trim)
122        .filter(|t| !t.is_empty())
123    else {
124        return Err(err(
125            at + 1,
126            "the text starts with a `# Title` heading".into(),
127        ));
128    };
129    at += 1;
130    let text = paragraphs(&lines[at..]);
131    if text.is_empty() {
132        return Err(err(0, "the tip has no text".into()));
133    }
134    let contextual = match get("contextual") {
135        None | Some("false") => false,
136        Some("true") => true,
137        Some(v) => {
138            return Err(err(
139                0,
140                format!("`contextual` is `true` or `false`, not `{v}`"),
141            ));
142        }
143    };
144    let mut tip = Tip::new(&id, title, &text);
145    tip.contextual = contextual;
146    tip.surface = get("surface").unwrap_or_default().to_string();
147    tip.command = match get("command").filter(|c| !c.is_empty()) {
148        None => None,
149        Some(c) => Some(CommandId::new(c).map_err(|e| err(0, e.to_string()))?),
150    };
151    tip.target = get("target").filter(|t| !t.is_empty()).map(str::to_string);
152    Ok(tip)
153}
154
155/// A value without its quotes, when it has a pair.
156fn unquote(v: &str) -> &str {
157    for q in ['"', '\''] {
158        if v.len() >= 2 && v.starts_with(q) && v.ends_with(q) {
159            return &v[1..v.len() - 1];
160        }
161    }
162    v
163}
164
165/// The lines as paragraphs: a paragraph's lines joined by a space,
166/// paragraphs by a line break.
167fn paragraphs(lines: &[&str]) -> String {
168    let mut out: Vec<String> = Vec::new();
169    let mut cur: Vec<&str> = Vec::new();
170    for l in lines {
171        let l = l.trim();
172        if l.is_empty() {
173            if !cur.is_empty() {
174                out.push(cur.join(" "));
175                cur.clear();
176            }
177        } else {
178            cur.push(l);
179        }
180    }
181    if !cur.is_empty() {
182        out.push(cur.join(" "));
183    }
184    out.join("\n")
185}
186
187/// Reads every `*.md` file of a folder, in the order of their names:
188/// the tips read, and the files that could not be.
189pub fn read_dir(dir: &Path) -> (Vec<Tip>, Vec<TipError>) {
190    let mut tips = Vec::new();
191    let mut errors = Vec::new();
192    let entries = match std::fs::read_dir(dir) {
193        Ok(e) => e,
194        Err(e) => {
195            errors.push(TipError {
196                file: dir.display().to_string(),
197                line: 0,
198                message: e.to_string(),
199            });
200            return (tips, errors);
201        }
202    };
203    let mut files: Vec<_> = entries
204        .filter_map(Result::ok)
205        .map(|e| e.path())
206        .filter(|p| p.extension().is_some_and(|x| x == "md"))
207        .collect();
208    files.sort();
209    for path in files {
210        let name = path
211            .file_name()
212            .map(|n| n.to_string_lossy().into_owned())
213            .unwrap_or_default();
214        match std::fs::read_to_string(&path) {
215            Ok(text) => match parse(&name, &text) {
216                Ok(t) => tips.push(t),
217                Err(e) => errors.push(e),
218            },
219            Err(e) => errors.push(TipError {
220                file: name,
221                line: 0,
222                message: e.to_string(),
223            }),
224        }
225    }
226    (tips, errors)
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    #[test]
234    fn a_file_gives_its_header_title_and_text() {
235        let t = parse(
236            "photos.rate.md",
237            "---\nsurface: focusedPanel == 'photos.grid'\ncommand: photos.rate\ntarget: \"photos.rating\"\n---\n\n# Rate quickly\n\nPress {key} to rate\nthe photos.\n\nPress **0** to clear.\n",
238        )
239        .unwrap();
240        assert_eq!(t.id, "photos.rate");
241        assert_eq!(t.title, "Rate quickly");
242        assert_eq!(
243            t.text,
244            "Press {key} to rate the photos.\nPress **0** to clear."
245        );
246        assert_eq!(t.surface, "focusedPanel == 'photos.grid'");
247        assert_eq!(t.command.as_ref().map(|c| c.as_str()), Some("photos.rate"));
248        assert_eq!(t.target.as_deref(), Some("photos.rating"));
249        assert!(!t.contextual);
250    }
251
252    #[test]
253    fn a_header_is_optional_and_mistakes_say_where() {
254        let t = parse("a.b.md", "# Title\nText.").unwrap();
255        assert_eq!((t.id.as_str(), t.surface.as_str()), ("a.b", ""));
256        let e = parse("x.md", "---\nwhen: x\n---\n# T\nText").unwrap_err();
257        assert_eq!(e.line, 2);
258        assert!(e.message.contains("unknown key `when`"), "{e}");
259        assert!(parse("x.md", "---\nid: x\n# T\nText").is_err());
260        assert!(parse("x.md", "Text without a title").is_err());
261        assert!(parse("x.md", "# Title only").is_err());
262        assert!(parse("x.md", "---\ncontextual: maybe\n---\n# T\nText").is_err());
263    }
264}