Skip to main content

egui_pop_views/viewer/
page.rs

1//! A markdown page read once: cut into its top-level blocks (each drawn
2//! on its own, so find in page and anchors know where they are), with
3//! each block's plain text, its heading's anchor, its links and its
4//! images. No egui here.
5
6use std::collections::BTreeSet;
7
8use egui_pop_model::links::{Policy, Target};
9use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd};
10
11/// The parser's options: egui_commonmark's, with heading attributes
12/// (`# Title {#id}`), so both read a page the same way.
13pub fn options() -> Options {
14    Options::ENABLE_TABLES
15        | Options::ENABLE_TASKLISTS
16        | Options::ENABLE_STRIKETHROUGH
17        | Options::ENABLE_FOOTNOTES
18        | Options::ENABLE_DEFINITION_LIST
19        | Options::ENABLE_HEADING_ATTRIBUTES
20}
21
22/// The schemes a page's links and images may use, from the links
23/// service's policy (the host may have changed it): never those that run
24/// or embed content, `command:` only on the application's own `docs:`
25/// pages, `file:` only on a page that is itself local (`docs:`, `file:`),
26/// never from the network. The policy still decides each open. Images
27/// narrow this further ([`image_schemes`]).
28pub(super) fn schemes(policy: &Policy, page: &str) -> BTreeSet<String> {
29    let mut all: BTreeSet<String> = policy
30        .schemes
31        .iter()
32        .chain(&policy.app_schemes)
33        .map(|s| s.to_ascii_lowercase())
34        .collect();
35    for never in ["javascript", "vbscript", "data", "blob", "about"] {
36        all.remove(never);
37    }
38    let parsed = Target::parse(page).ok();
39    let origin = parsed.as_ref().map(Target::scheme);
40    if origin != Some("docs") {
41        all.remove("command");
42    }
43    if !is_local(origin) {
44        all.remove("file");
45    }
46    all
47}
48
49/// The schemes the viewer reads an image from.
50pub(super) const IMAGE_SCHEMES: &[&str] = &["docs", "file", "http", "https"];
51
52/// The schemes a page's images may use: those of its links, except that a
53/// page from the network may link to the application's `docs:` pages but
54/// not read their files.
55pub(super) fn image_schemes(policy: &Policy, page: &str) -> BTreeSet<String> {
56    let mut all = schemes(policy, page);
57    let parsed = Target::parse(page).ok();
58    if !is_local(parsed.as_ref().map(Target::scheme)) {
59        all.remove("docs");
60    }
61    all
62}
63
64/// Whether a page's scheme says it is the application's or on the disk.
65fn is_local(origin: Option<&str>) -> bool {
66    matches!(origin, Some("docs" | "file"))
67}
68
69/// Whether a page may keep a link: what it resolves to, read as the links
70/// service will read it, uses one of its schemes. An anchor stays.
71fn link_allowed(page: &str, dest: &str, schemes: &BTreeSet<String>) -> bool {
72    let resolved = resolve(page, dest);
73    if resolved.is_empty() || resolved.starts_with('#') {
74        return true;
75    }
76    Target::parse(&resolved).is_ok_and(|t| schemes.contains(t.scheme()))
77}
78
79/// How many times a page's markdown is read for the links it may not keep.
80const STRIP_PASSES: usize = 8;
81
82/// Why a page whose links are tangled is not shown.
83const TANGLED: &str = "its links are nested in each other too deeply to check";
84
85/// A page's markdown with the links it may not keep made plain text, their
86/// emphasis, code and images staying. Their text is escaped, but the brackets
87/// around one (`[[a](b)](c)`) can read as a link once it is gone, so this
88/// reads again until none is left, and gives up visibly: only a page written
89/// to get around this comes near the limit.
90pub(super) fn strip_links(
91    source: &str,
92    page: &str,
93    schemes: &BTreeSet<String>,
94) -> Result<String, &'static str> {
95    let mut text = std::borrow::Cow::Borrowed(source);
96    for _ in 0..STRIP_PASSES {
97        match strip_pass(&text, page, schemes) {
98            Some(next) => text = next.into(),
99            None => return Ok(text.into_owned()),
100        }
101    }
102    Err(TANGLED)
103}
104
105/// One reading of a page's markdown: what is left of it, when a link went.
106fn strip_pass(source: &str, page: &str, schemes: &BTreeSet<String>) -> Option<String> {
107    let mut out = String::with_capacity(source.len());
108    let mut copied = 0;
109    // The end of the link being made text.
110    let mut refused: Option<usize> = None;
111    let mut stripped = false;
112    // A link in an image's alt text is not drawn (`Markdown::parse`).
113    let mut images = 0usize;
114    for (event, range) in Parser::new_ext(source, options()).into_offset_iter() {
115        match event {
116            Event::Start(Tag::Image { .. }) => {
117                if refused.is_some() && images == 0 {
118                    out.push_str(&source[range]);
119                }
120                images += 1;
121            }
122            Event::End(TagEnd::Image) => images = images.saturating_sub(1),
123            _ if images > 0 => {}
124            Event::Start(Tag::Link { dest_url, .. })
125                if refused.is_none() && !link_allowed(page, &dest_url, schemes) =>
126            {
127                out.push_str(&source[copied..range.start]);
128                refused = Some(range.end);
129                stripped = true;
130            }
131            _ if refused.is_none() => {}
132            Event::End(TagEnd::Link) => copied = refused.take().unwrap_or(copied),
133            Event::Text(t) => out.push_str(&escape(&t)),
134            Event::Code(_) => out.push_str(&source[range]),
135            Event::InlineHtml(_) => out.push_str(&escape(&source[range])),
136            Event::SoftBreak | Event::HardBreak => out.push(' '),
137            Event::Start(Tag::Emphasis) | Event::End(TagEnd::Emphasis) => out.push('*'),
138            Event::Start(Tag::Strong) | Event::End(TagEnd::Strong) => out.push_str("**"),
139            Event::Start(Tag::Strikethrough) | Event::End(TagEnd::Strikethrough) => {
140                out.push_str("~~");
141            }
142            _ => {}
143        }
144    }
145    out.push_str(&source[copied..]);
146    stripped.then_some(out)
147}
148
149/// An image in a block: where its markdown is, its alt text and its
150/// address as written.
151#[derive(Clone, Debug, PartialEq, Eq)]
152pub struct ImageRef {
153    /// Its bytes in the block's source.
154    pub range: std::ops::Range<usize>,
155    pub alt: String,
156    pub dest: String,
157}
158
159/// A top-level block of a page.
160#[derive(Clone, Debug, PartialEq, Eq)]
161pub struct Block {
162    /// Its markdown.
163    pub source: String,
164    /// Its text as read (for find in page), lower case.
165    pub text: String,
166    /// Its anchor, when it is a heading.
167    pub anchor: Option<String>,
168    /// Its heading's level (1 to 6).
169    pub level: Option<u8>,
170    /// The links' destinations, as written.
171    pub links: Vec<String>,
172    pub images: Vec<ImageRef>,
173}
174
175/// A markdown page.
176#[derive(Clone, Debug, Default, PartialEq, Eq)]
177pub struct Markdown {
178    pub blocks: Vec<Block>,
179    /// The page's reference definitions (`[id]: target`), given to each
180    /// block so a reference link drawn alone still resolves.
181    pub references: String,
182    /// The first heading's text.
183    pub title: Option<String>,
184}
185
186impl Markdown {
187    /// Reads a page.
188    pub fn parse(source: &str) -> Markdown {
189        let parser = Parser::new_ext(source, options());
190        let mut references = String::new();
191        for (label, def) in parser.reference_definitions().iter() {
192            references.push_str(&format!("\n[{label}]: <{}>", def.dest));
193        }
194        let mut page = Markdown {
195            references,
196            ..Markdown::default()
197        };
198        let mut depth = 0usize;
199        let mut start = 0usize;
200        let mut cur = Pending::default();
201        let mut used: Vec<String> = Vec::new();
202        for (event, range) in parser.into_offset_iter() {
203            match &event {
204                Event::Start(tag) => {
205                    if depth == 0 {
206                        start = range.start;
207                        // Its text starts after the indent that makes it
208                        // code: without it, drawn alone, it would be markup
209                        // nothing here read (an image, a link).
210                        if matches!(tag, Tag::CodeBlock(CodeBlockKind::Indented)) {
211                            start = source[..start].rfind('\n').map_or(0, |at| at + 1);
212                        }
213                        cur = Pending::default();
214                        if let Tag::Heading { level, id, .. } = tag {
215                            cur.level = Some(level_of(*level));
216                            cur.id = id.as_ref().map(ToString::to_string);
217                        }
218                    }
219                    match tag {
220                        // A link in an image's alt text is part of it: not drawn.
221                        Tag::Link { dest_url, .. } if cur.image_depth == 0 => {
222                            cur.links.push(dest_url.to_string());
223                        }
224                        // An image in another's alt text is part of it:
225                        // the outermost is the one drawn.
226                        Tag::Image { dest_url, .. } => {
227                            if cur.image.is_none() {
228                                cur.image =
229                                    Some((range.clone(), dest_url.to_string(), String::new()));
230                            }
231                            cur.image_depth += 1;
232                        }
233                        _ => {}
234                    }
235                    depth += 1;
236                }
237                Event::End(end) => {
238                    if matches!(end, TagEnd::Image) {
239                        cur.image_depth = cur.image_depth.saturating_sub(1);
240                    }
241                    if matches!(end, TagEnd::Image)
242                        && cur.image_depth == 0
243                        && let Some((r, dest, alt)) = cur.image.take()
244                    {
245                        cur.images.push(ImageRef {
246                            range: r.start - start..r.end - start,
247                            alt,
248                            dest,
249                        });
250                    }
251                    if matches!(end, TagEnd::Paragraph | TagEnd::Item | TagEnd::TableCell) {
252                        cur.text.push(' ');
253                    }
254                    depth = depth.saturating_sub(1);
255                    if depth == 0 {
256                        page.push(
257                            &source[start..range.end],
258                            std::mem::take(&mut cur),
259                            &mut used,
260                        );
261                    }
262                }
263                Event::Text(t) | Event::Code(t) | Event::InlineMath(t) | Event::DisplayMath(t) => {
264                    cur.text.push_str(t);
265                    if let Some((_, _, alt)) = &mut cur.image {
266                        alt.push_str(t);
267                    }
268                    if depth == 0 {
269                        page.push(&source[range.clone()], std::mem::take(&mut cur), &mut used);
270                    }
271                }
272                Event::SoftBreak | Event::HardBreak => cur.text.push(' '),
273                Event::Rule | Event::Html(_) | Event::InlineHtml(_) if depth == 0 => {
274                    page.push(&source[range.clone()], Pending::default(), &mut used);
275                }
276                _ => {}
277            }
278        }
279        page
280    }
281
282    fn push(&mut self, source: &str, cur: Pending, used: &mut Vec<String>) {
283        let heading = cur.level.map(|_| cur.text.trim().to_string());
284        let anchor = heading.as_ref().map(|h| {
285            let base = cur.id.clone().unwrap_or_else(|| slug(h));
286            unique(base, used)
287        });
288        if self.title.is_none()
289            && let Some(h) = &heading
290        {
291            self.title = Some(h.clone());
292        }
293        self.blocks.push(Block {
294            source: source.to_string(),
295            text: cur.text.to_lowercase(),
296            anchor,
297            level: cur.level,
298            links: cur.links,
299            images: cur.images,
300        });
301    }
302
303    /// The block a heading's anchor names (`#install`, `install`).
304    pub fn anchor(&self, name: &str) -> Option<usize> {
305        let name = name.trim_start_matches('#');
306        self.blocks
307            .iter()
308            .position(|b| b.anchor.as_deref() == Some(name))
309            .or_else(|| {
310                let s = slug(name);
311                self.blocks
312                    .iter()
313                    .position(|b| b.anchor.as_deref() == Some(s.as_str()))
314            })
315    }
316
317    /// Where `query` is found (case aside): one block index per match,
318    /// in reading order.
319    pub fn find(&self, query: &str) -> Vec<usize> {
320        let q = query.to_lowercase();
321        if q.trim().is_empty() {
322            return Vec::new();
323        }
324        self.blocks
325            .iter()
326            .enumerate()
327            .flat_map(|(i, b)| std::iter::repeat_n(i, b.text.matches(q.as_str()).count()))
328            .collect()
329    }
330
331    /// Every link destination of the page, once each.
332    pub fn links(&self) -> Vec<String> {
333        let mut all: Vec<String> = self.blocks.iter().flat_map(|b| b.links.clone()).collect();
334        all.sort();
335        all.dedup();
336        all
337    }
338
339    /// The page's text as read, for an agent.
340    pub fn text(&self) -> String {
341        self.blocks
342            .iter()
343            .map(|b| b.text.trim())
344            .filter(|t| !t.is_empty())
345            .collect::<Vec<_>>()
346            .join("\n")
347    }
348}
349
350#[derive(Debug, Default)]
351struct Pending {
352    text: String,
353    level: Option<u8>,
354    id: Option<String>,
355    links: Vec<String>,
356    images: Vec<ImageRef>,
357    image: Option<(std::ops::Range<usize>, String, String)>,
358    /// How many images are open around the text being read.
359    image_depth: usize,
360}
361
362fn level_of(level: HeadingLevel) -> u8 {
363    match level {
364        HeadingLevel::H1 => 1,
365        HeadingLevel::H2 => 2,
366        HeadingLevel::H3 => 3,
367        HeadingLevel::H4 => 4,
368        HeadingLevel::H5 => 5,
369        HeadingLevel::H6 => 6,
370    }
371}
372
373/// A heading's anchor as hosting sites make it: lower case, letters,
374/// digits, `-` and `_` kept, spaces made `-`, the rest dropped.
375pub fn slug(text: &str) -> String {
376    text.trim()
377        .to_lowercase()
378        .chars()
379        .filter_map(|c| match c {
380            ' ' => Some('-'),
381            c if c.is_alphanumeric() || c == '-' || c == '_' => Some(c),
382            _ => None,
383        })
384        .collect()
385}
386
387fn unique(base: String, used: &mut Vec<String>) -> String {
388    let mut name = base.clone();
389    let mut n = 1;
390    while used.contains(&name) {
391        name = format!("{base}-{n}");
392        n += 1;
393    }
394    used.push(name.clone());
395    name
396}
397
398/// Text written into markdown as it is (its punctuation escaped).
399pub fn escape(text: &str) -> String {
400    let mut out = String::with_capacity(text.len());
401    for c in text.chars() {
402        if c.is_ascii_punctuation() {
403            out.push('\\');
404        }
405        out.push(c);
406    }
407    out
408}
409
410/// A destination resolved against the page it is on: an anchor stays
411/// an anchor (`#x`), an address with a scheme is kept, a relative one
412/// (`guide.md`, `../img/a.png`) joins the page's folder: a `docs:` page
413/// gives a `docs:` page, a web or file page joins as the web does.
414pub fn resolve(base: &str, dest: &str) -> String {
415    let dest = dest.trim();
416    if dest.is_empty() || dest.starts_with('#') || has_scheme(dest) {
417        return dest.to_string();
418    }
419    if let Some(page) = base.strip_prefix("docs:") {
420        let page = page.split('#').next().unwrap_or_default();
421        let (path, fragment) = match dest.split_once('#') {
422            Some((p, f)) => (p, Some(f)),
423            None => (dest, None),
424        };
425        let mut parts: Vec<&str> = if path.starts_with('/') {
426            Vec::new()
427        } else {
428            let mut p: Vec<&str> = page.split('/').collect();
429            p.pop();
430            p
431        };
432        for seg in path.split('/') {
433            match seg {
434                "" | "." => {}
435                ".." => {
436                    parts.pop();
437                }
438                s => parts.push(s),
439            }
440        }
441        let mut out = format!("docs:{}", parts.join("/"));
442        if let Some(f) = fragment {
443            out.push('#');
444            out.push_str(f);
445        }
446        return out;
447    }
448    match url::Url::parse(base).and_then(|b| b.join(dest)) {
449        Ok(u) => u.to_string(),
450        Err(_) => dest.to_string(),
451    }
452}
453
454/// Whether an address names its scheme (`https:`, `docs:`, `mailto:`);
455/// a Windows drive (`C:\\`) is not one.
456pub fn has_scheme(text: &str) -> bool {
457    match text.split_once(':') {
458        Some((scheme, _)) => {
459            scheme.len() > 1
460                && scheme
461                    .chars()
462                    .next()
463                    .is_some_and(|c| c.is_ascii_alphabetic())
464                && scheme
465                    .chars()
466                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
467        }
468        None => false,
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475
476    const PAGE: &str = "\
477# Getting started
478
479Read [the guide](guide.md#install) and [the site][site].
480
481![A screenshot](img/shot.png)
482
483## Install
484
485Run `cargo add`.
486
487[site]: https://example.org/
488";
489
490    #[test]
491    fn blocks_anchors_links_and_images() {
492        let m = Markdown::parse(PAGE);
493        assert_eq!(m.title.as_deref(), Some("Getting started"));
494        assert_eq!(m.blocks.len(), 5);
495        assert_eq!(m.blocks[0].anchor.as_deref(), Some("getting-started"));
496        assert_eq!(m.anchor("#install"), Some(3));
497        assert_eq!(
498            m.blocks[1].links,
499            ["guide.md#install", "https://example.org/"]
500        );
501        let img = &m.blocks[2].images[0];
502        assert_eq!(
503            (img.alt.as_str(), img.dest.as_str()),
504            ("A screenshot", "img/shot.png")
505        );
506        assert_eq!(
507            &m.blocks[2].source[img.range.clone()],
508            "![A screenshot](img/shot.png)"
509        );
510        assert!(m.references.contains("[site]: <https://example.org/>"));
511        assert_eq!(m.find("INSTALL"), [3]);
512        assert_eq!(m.find("the"), [1, 1]);
513    }
514
515    #[test]
516    fn an_image_inside_an_image_leaves_no_address_unread() {
517        let source = "![a ![b](b.png) c](outer.png) and ![d](d.png)";
518        let m = Markdown::parse(source);
519        let images = &m.blocks[0].images;
520        assert_eq!(images.len(), 2, "{images:?}");
521        assert_eq!(images[0].dest, "outer.png");
522        assert_eq!(images[0].alt, "a b c");
523        assert_eq!(
524            &source[images[0].range.clone()],
525            "![a ![b](b.png) c](outer.png)"
526        );
527        assert_eq!(images[1].dest, "d.png");
528    }
529
530    #[test]
531    fn links_a_page_may_not_keep_become_text() {
532        let web = schemes(&Policy::default(), "https://docs.example.org/a.md");
533        let page = "https://docs.example.org/a.md";
534        let strip = |source: &str| strip_links(source, page, &web).unwrap();
535        for (source, text) in [
536            ("[a](file:///x)", "a"),
537            ("[a](FILE:///x)", "a"),
538            ("[a](command:x)", "a"),
539            ("[a](javascript:x)", "a"),
540            ("[a][r]\n\n[r]: file:///x", "a"),
541            ("[a]\n\n[a]: file:///x", "a"),
542            ("<file:///x>", "file:///x"),
543            ("[a](</some/path>) [b](<//[bad/path>)", "b"),
544            ("# [a](file:///x)", "a"),
545            ("> [a\n> b](file:///x)", "a b"),
546            ("- [a](file:///x)", "a"),
547            ("| h |\n|---|\n| [a\\|b](file:///x) |", "a|b"),
548        ] {
549            let page = Markdown::parse(&strip(source));
550            let links = page.links();
551            assert!(
552                links
553                    .iter()
554                    .all(|l| !l.contains("file") && !l.contains("bad")),
555                "{source}: {links:?}"
556            );
557            assert!(page.text().contains(text), "{source}: {}", page.text());
558        }
559        // What is around, and inside, stays.
560        assert_eq!(strip("a [b](file:///x) c"), "a b c");
561        assert_eq!(
562            strip("[*a* **b** ~~c~~ `d`](file:///x)"),
563            "*a* **b** ~~c~~ `d`"
564        );
565        assert_eq!(strip("[![a](b.png)](file:///x)"), "![a](b.png)");
566        assert_eq!(
567            strip("[a](https://e.example/) [b](next.md) [c](#d) [e](docs:f) [g](mailto:h@i.j)"),
568            "[a](https://e.example/) [b](next.md) [c](#d) [e](docs:f) [g](mailto:h@i.j)"
569        );
570        assert_eq!(strip("`[a](file:///x)`"), "`[a](file:///x)`");
571        // A link uncovered by removing another goes too.
572        for source in [
573            "[[r]](file:///x)\n\n[r]: file:///y",
574            "[a [b](file:///x) c](file:///y)",
575            "[[[a](file:///x)](file:///y)](file:///z)",
576        ] {
577            let read = Markdown::parse(&strip(source));
578            assert_eq!(read.links(), Vec::<String>::new(), "{source}");
579        }
580        // Past what a page does by accident, the page is refused.
581        let tangled = "[".repeat(40) + "a" + &"](file:///x)".repeat(40);
582        assert_eq!(strip_links(&tangled, page, &web), Err(TANGLED));
583        // A local page keeps them.
584        let docs = schemes(&Policy::default(), "docs:a");
585        let source = "[a](file:///x) [b](command:y)";
586        assert_eq!(strip_links(source, "docs:a", &docs).as_deref(), Ok(source));
587    }
588
589    #[test]
590    fn a_block_read_alone_reads_as_it_did_on_its_page() {
591        for source in [
592            "    ![a](docs:img/a.png)\n",
593            "    [a](file:///x)\n",
594            "\t![a](docs:img/a.png)\n",
595            "para\n\n    ![a](docs:b.png)\n",
596            "    x\n\n    ![a](docs:b.png)\n",
597            "> x\n>\n>     ![a](docs:b.png)\n",
598            "- x\n\n      ![a](docs:b.png)\n",
599            "   ```\n   ![a](docs:b.png)\n   ```\n",
600            "<div>\n\n![a](docs:b.png)\n\n</div>\n",
601            "[^1]\n\n[^1]: ![a](docs:b.png) [c](file:///x)\n",
602        ] {
603            for block in Markdown::parse(source).blocks {
604                let alone = Markdown::parse(&block.source);
605                let read: Vec<_> = alone.blocks.iter().flat_map(|b| &b.images).collect();
606                assert_eq!(read.len(), block.images.len(), "{source:?}: {block:?}");
607                assert_eq!(alone.links(), block.links, "{source:?}: {block:?}");
608            }
609        }
610    }
611
612    #[test]
613    fn a_link_in_an_image_alt_text_is_no_link() {
614        let m = Markdown::parse("![a [b](file:///x) c](d.png)");
615        assert_eq!(m.links(), Vec::<String>::new());
616        assert_eq!(m.blocks[0].images[0].alt, "a b c");
617    }
618
619    #[test]
620    fn destinations_resolve_against_their_page() {
621        assert_eq!(
622            resolve("docs:guide/start", "install.md"),
623            "docs:guide/install.md"
624        );
625        assert_eq!(
626            resolve("docs:guide/start", "../img/a.png"),
627            "docs:img/a.png"
628        );
629        assert_eq!(resolve("docs:guide/start", "/index#top"), "docs:index#top");
630        assert_eq!(resolve("docs:a", "#x"), "#x");
631        assert_eq!(
632            resolve("docs:a", "https://example.org/"),
633            "https://example.org/"
634        );
635        assert_eq!(
636            resolve("https://docs.example.org/a/b.md", "c.png"),
637            "https://docs.example.org/a/c.png"
638        );
639        assert!(!has_scheme("C:\\photos"));
640    }
641}