Skip to main content

devpage_core/comments/
anchor.rs

1//! Carrying a thread onto a new version of its page: the page's text as the
2//! page script reads it, and where a thread's quote is in it now. Pure — the
3//! server hands it the new version's HTML and stores what it answers.
4
5use super::Anchor;
6
7/// How much text either side of a quote an anchor keeps: the page script's
8/// `CONTEXT`.
9const CONTEXT: usize = 32;
10
11/// The text of rendered HTML as the page script's text model reads it: the
12/// text between the tags, entities decoded, every run of white space one
13/// space.
14pub fn text(html: &str) -> String {
15    let mut raw = String::new();
16    let mut rest = html;
17    while let Some(start) = rest.find('<') {
18        raw.push_str(&rest[..start]);
19        let tag = &rest[start..];
20        // What a script or a style holds is never on the page.
21        let skipped = ["script", "style"].iter().find_map(|name| {
22            let open = tag.get(1..1 + name.len())?;
23            let ends = tag.as_bytes().get(1 + name.len())?;
24            (open.eq_ignore_ascii_case(name) && (*ends == b'>' || ends.is_ascii_whitespace()))
25                .then(|| format!("</{name}>"))
26        });
27        rest = match skipped {
28            Some(close) => tag
29                .to_ascii_lowercase()
30                .find(&close)
31                .map_or("", |end| &tag[end + close.len()..]),
32            None => tag.find('>').map_or("", |end| &tag[end + 1..]),
33        };
34    }
35    raw.push_str(rest);
36    squeeze(&decode(&raw))
37}
38
39/// Where `anchor`'s quote is in `text` now: the anchor itself when its quote
40/// is still there with its context, a new one with the context it has now
41/// when only the quote is, and `None` when the quote is gone — the thread is
42/// detached.
43pub fn reanchor(anchor: &Anchor, text: &str) -> Option<Anchor> {
44    let quote = squeeze(&anchor.quote);
45    if quote.trim().is_empty() {
46        return None;
47    }
48    let whole = format!(
49        "{}{quote}{}",
50        squeeze(&anchor.prefix),
51        squeeze(&anchor.suffix)
52    );
53    if text.contains(&whole) {
54        return Some(anchor.clone());
55    }
56    let at = text.find(&quote)?;
57    let end = at + quote.len();
58    let before: String = {
59        let chars: Vec<char> = text[..at].chars().collect();
60        chars[chars.len().saturating_sub(CONTEXT)..]
61            .iter()
62            .collect()
63    };
64    let after: String = text[end..].chars().take(CONTEXT).collect();
65    Some(Anchor {
66        quote: anchor.quote.clone(),
67        prefix: before,
68        suffix: after,
69    })
70}
71
72/// Every run of white space as one space, as the page script's model has it.
73fn squeeze(text: &str) -> String {
74    let mut out = String::with_capacity(text.len());
75    for c in text.chars() {
76        if c.is_whitespace() {
77            if !out.ends_with(' ') {
78                out.push(' ');
79            }
80        } else {
81            out.push(c);
82        }
83    }
84    out
85}
86
87/// HTML's character references, as the browser decodes them into text.
88fn decode(text: &str) -> String {
89    let mut out = String::with_capacity(text.len());
90    let mut rest = text;
91    while let Some(at) = rest.find('&') {
92        out.push_str(&rest[..at]);
93        let tail = &rest[at..];
94        let decoded = tail.find(';').filter(|end| *end <= 10).and_then(|end| {
95            let name = &tail[1..end];
96            let c = match name {
97                "amp" => Some('&'),
98                "lt" => Some('<'),
99                "gt" => Some('>'),
100                "quot" => Some('"'),
101                "apos" => Some('\''),
102                "nbsp" => Some('\u{a0}'),
103                _ => name
104                    .strip_prefix("#x")
105                    .or_else(|| name.strip_prefix("#X"))
106                    .and_then(|hex| u32::from_str_radix(hex, 16).ok())
107                    .or_else(|| name.strip_prefix('#').and_then(|n| n.parse().ok()))
108                    .and_then(char::from_u32),
109            }?;
110            Some((c, end + 1))
111        });
112        match decoded {
113            Some((c, len)) => {
114                out.push(c);
115                rest = &tail[len..];
116            }
117            None => {
118                out.push('&');
119                rest = &tail[1..];
120            }
121        }
122    }
123    out.push_str(rest);
124    out
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    fn anchor(prefix: &str, quote: &str, suffix: &str) -> Anchor {
132        Anchor {
133            quote: quote.into(),
134            prefix: prefix.into(),
135            suffix: suffix.into(),
136        }
137    }
138
139    #[test]
140    fn the_text_is_what_the_page_shows() {
141        let html = "<h1>Rollout</h1>\n<p>The client <strong>re</strong>tries every\n  write &amp; read.</p><script>let x = '<p>no</p>';</script><style>p{}</style><p>&#x41;&#66;</p>";
142        assert_eq!(
143            text(html),
144            "Rollout The client retries every write & read.AB"
145        );
146    }
147
148    #[test]
149    fn a_quote_with_its_context_keeps_its_anchor() {
150        let kept = anchor("The client ", "retries every write", " until");
151        let text = "Intro. The client retries every write until it is acknowledged.";
152        assert_eq!(reanchor(&kept, text), Some(kept.clone()));
153    }
154
155    #[test]
156    fn a_quote_whose_context_changed_takes_its_new_context() {
157        let moved = anchor("The client ", "retries every write", " until");
158        let text = "Rewritten: now each client retries every write, capped at five.";
159        let found = reanchor(&moved, text).unwrap();
160        assert_eq!(found.quote, "retries every write");
161        assert_eq!(found.prefix, "Rewritten: now each client ");
162        assert_eq!(found.suffix, ", capped at five.");
163        // What the page script then finds: the quote with its new context.
164        assert!(text.contains(&format!("{}{}{}", found.prefix, found.quote, found.suffix)));
165    }
166
167    #[test]
168    fn a_quote_that_is_gone_is_detached() {
169        let gone = anchor("", "retries are capped at five", "");
170        assert_eq!(reanchor(&gone, "Retries are unlimited now."), None);
171        assert_eq!(reanchor(&anchor("", "  ", ""), "  "), None);
172    }
173
174    #[test]
175    fn context_is_counted_in_characters() {
176        let text = format!("{}é quote ü{}", "ä".repeat(40), "ö".repeat(40));
177        let found = reanchor(&anchor("x", "quote", "y"), &text).unwrap();
178        assert_eq!(found.prefix.chars().count(), CONTEXT);
179        assert_eq!(found.suffix.chars().count(), CONTEXT);
180    }
181}