devpage_core/comments/
anchor.rs1use super::Anchor;
6
7const CONTEXT: usize = 32;
10
11pub 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 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
39pub 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("e)?;
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
72fn 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
87fn 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 & read.</p><script>let x = '<p>no</p>';</script><style>p{}</style><p>AB</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 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}