Skip to main content

devpage_core/
html.rs

1//! HTML as devpage reads and writes it: text escaped into it and back, a
2//! tag's attributes, every value one attribute takes in a page, and what a
3//! link's address names.
4
5/// `text` safe in HTML: in an element's text and in a double-quoted
6/// attribute value.
7pub fn escape(text: &str) -> String {
8    text.replace('&', "&")
9        .replace('<', "&lt;")
10        .replace('>', "&gt;")
11        .replace('"', "&quot;")
12}
13
14/// The text `escape` was given back.
15pub(crate) fn unescape(html: &str) -> String {
16    html.replace("&lt;", "<")
17        .replace("&gt;", ">")
18        .replace("&quot;", "\"")
19        .replace("&amp;", "&")
20}
21
22/// The length of the tag `html` starts with: up to and including its closing
23/// `>`, skipping any `>` inside a quoted attribute value.
24pub(crate) fn tag_end(html: &str) -> usize {
25    let mut quote = None;
26    for (i, c) in html.char_indices() {
27        match (quote, c) {
28            (None, '"' | '\'') => quote = Some(c),
29            (Some(q), c) if c == q => quote = None,
30            (None, '>') => return i + 1,
31            _ => {}
32        }
33    }
34    html.len()
35}
36
37/// A tag's attributes, from just after its name up to its closing `>`: each
38/// name with its value — double-quoted, single-quoted, unquoted, or empty for
39/// a bare name — separated by any whitespace. Values are as written, still
40/// escaped.
41pub(crate) fn attributes(tag: &str) -> Vec<(String, String)> {
42    let mut attributes = Vec::new();
43    let mut chars = tag.char_indices().peekable();
44    loop {
45        while chars
46            .next_if(|(_, c)| c.is_ascii_whitespace() || *c == '/')
47            .is_some()
48        {}
49        let Some(&(start, c)) = chars.peek() else {
50            break;
51        };
52        if c == '>' {
53            break;
54        }
55        let mut end = start;
56        while let Some((i, c)) =
57            chars.next_if(|(_, c)| !c.is_ascii_whitespace() && !matches!(c, '=' | '>' | '/'))
58        {
59            end = i + c.len_utf8();
60        }
61        let name = tag[start..end].to_string();
62        while chars.next_if(|(_, c)| c.is_ascii_whitespace()).is_some() {}
63        let mut value = String::new();
64        if chars.next_if(|(_, c)| *c == '=').is_some() {
65            while chars.next_if(|(_, c)| c.is_ascii_whitespace()).is_some() {}
66            match chars.peek() {
67                Some(&(_, quote @ ('"' | '\''))) => {
68                    chars.next();
69                    for (_, c) in chars.by_ref() {
70                        if c == quote {
71                            break;
72                        }
73                        value.push(c);
74                    }
75                }
76                _ => {
77                    while let Some((_, c)) =
78                        chars.next_if(|(_, c)| !c.is_ascii_whitespace() && *c != '>')
79                    {
80                        value.push(c);
81                    }
82                }
83            }
84        }
85        if name.is_empty() {
86            // Not a name at all (a stray `=`): skip one character and go on.
87            chars.next();
88            continue;
89        }
90        attributes.push((name, value));
91    }
92    attributes
93}
94
95/// Every value the attribute `name` takes in `html`'s tags, in order and
96/// unescaped, its name matched in any case. Comments hold no tags, and text
97/// holds none either: escaped, it has no `<`.
98pub(crate) fn values(html: &str, name: &str) -> Vec<String> {
99    let mut values = Vec::new();
100    let mut rest = html;
101    while let Some(at) = rest.find('<') {
102        rest = &rest[at..];
103        if let Some(comment) = rest.strip_prefix("<!--") {
104            rest = comment.find("-->").map_or("", |end| &comment[end + 3..]);
105            continue;
106        }
107        let named = rest[1..].len()
108            - rest[1..]
109                .trim_start_matches(|c: char| c.is_ascii_alphanumeric())
110                .len();
111        if named == 0 {
112            rest = &rest[1..];
113            continue;
114        }
115        let end = tag_end(rest);
116        values.extend(
117            attributes(&rest[1 + named..end])
118                .into_iter()
119                .filter(|(attribute, _)| attribute.eq_ignore_ascii_case(name))
120                .map(|(_, value)| unescape(&value)),
121        );
122        rest = &rest[end..];
123    }
124    values
125}
126
127/// What a link's address names, read from how it is written.
128#[derive(Debug, PartialEq)]
129pub(crate) enum Link<'a> {
130    /// An address on the web, `http:` or `https:`, as written.
131    Web(&'a str),
132    /// An address with any other scheme — `mailto:`, `tel:`, `data:` —
133    /// which devpage neither follows nor rewrites.
134    Elsewhere,
135    /// A file, by its path from where the link is written and the fragment
136    /// after any `#`. An empty path is the page itself.
137    File { path: &'a str, fragment: &'a str },
138}
139
140impl<'a> Link<'a> {
141    /// What `address` names. A scheme is letters, digits, `+`, `-` and `.`
142    /// starting with a letter, before a `:` that comes ahead of any `/`, `?`
143    /// or `#`; anything else is a path.
144    pub(crate) fn classify(address: &'a str) -> Link<'a> {
145        let scheme = address
146            .split_once(':')
147            .map(|(scheme, _)| scheme)
148            .filter(|scheme| {
149                scheme.starts_with(|c: char| c.is_ascii_alphabetic())
150                    && scheme
151                        .chars()
152                        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
153            });
154        match scheme {
155            Some(scheme)
156                if scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") =>
157            {
158                Link::Web(address)
159            }
160            Some(_) => Link::Elsewhere,
161            None => {
162                let (path, fragment) = address.split_once('#').unwrap_or((address, ""));
163                Link::File { path, fragment }
164            }
165        }
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn escaped_text_is_safe_in_text_and_in_a_quoted_attribute_and_comes_back() {
175        let text = r#"<a href="x">Tom & "Jerry"</a>"#;
176        let escaped = escape(text);
177        assert_eq!(
178            escaped,
179            "&lt;a href=&quot;x&quot;&gt;Tom &amp; &quot;Jerry&quot;&lt;/a&gt;"
180        );
181        assert_eq!(unescape(&escaped), text);
182        // An escaped `&lt;` stays text, not a tag.
183        assert_eq!(unescape(&escape("&lt;")), "&lt;");
184    }
185
186    #[test]
187    fn a_tags_attributes_are_read_however_they_are_quoted_and_spaced() {
188        assert_eq!(
189            attributes(r#" SRC = 'a b.png' alt="x > y" width=10 hidden/>"#),
190            [
191                ("SRC".to_string(), "a b.png".to_string()),
192                ("alt".to_string(), "x > y".to_string()),
193                ("width".to_string(), "10".to_string()),
194                ("hidden".to_string(), String::new()),
195            ]
196        );
197        assert_eq!(tag_end(r#"<a title="a>b">rest"#), 15);
198    }
199
200    #[test]
201    fn every_value_of_an_attribute_is_found_in_tags_only() {
202        let html = concat!(
203            r#"<p><a href="one.md">1</a> <a class="x" HREF='two.md?a=1&amp;b=2'>2</a></p>"#,
204            r#"<!-- <a href="commented.md"> -->"#,
205            r#"<pre><code>&lt;a href=&quot;code.md&quot;&gt;</code></pre>"#,
206            r#"<p>a < b and href="text.md"</p>"#,
207            r#"<img src="pic.png"><svg><a xlink:href="drawn.md"></a></svg>"#,
208        );
209        assert_eq!(values(html, "href"), ["one.md", "two.md?a=1&b=2"]);
210        assert_eq!(values(html, "src"), ["pic.png"]);
211    }
212
213    #[test]
214    fn an_address_is_on_the_web_elsewhere_or_a_file() {
215        for web in ["http://example.com", "https://example.com/a#b", "HTTPS://x"] {
216            assert_eq!(Link::classify(web), Link::Web(web));
217        }
218        for elsewhere in [
219            "mailto:a@b.c",
220            "tel:+1",
221            "data:image/png;base64,AA",
222            "ftp://x",
223        ] {
224            assert_eq!(Link::classify(elsewhere), Link::Elsewhere, "{elsewhere}");
225        }
226        for (address, path, fragment) in [
227            ("b.md", "b.md", ""),
228            ("../b.md#two", "../b.md", "two"),
229            ("#top", "", "top"),
230            ("", "", ""),
231            ("notes/a:b.md", "notes/a:b.md", ""),
232            ("b.md#at:10", "b.md", "at:10"),
233            ("/root.md", "/root.md", ""),
234        ] {
235            assert_eq!(
236                Link::classify(address),
237                Link::File { path, fragment },
238                "{address}"
239            );
240        }
241    }
242}