1pub(crate) mod tool;
11
12use std::collections::{HashMap, HashSet};
13
14pub(crate) use self::tool::Tool;
15
16const ALWAYS: &[&str] = &["p", "br"];
18
19const BLOCKS: &[&str] = &["p", "br", "h1", "h2", "h3", "li", "blockquote", "pre", "hr"];
21
22pub fn clean(html: &str) -> String {
37 clean_with(html, Tool::ALL.iter().copied())
38}
39
40pub fn text(html: &str) -> String {
52 plain_text(&clean(html))
53}
54
55pub(crate) fn clean_with(html: &str, tools: impl IntoIterator<Item = Tool>) -> String {
61 let mut tags: HashSet<&str> = ALWAYS.iter().copied().collect();
62 let mut attributes: HashMap<&str, HashSet<&str>> = HashMap::new();
63 for tool in tools {
64 for (tag, attrs) in tool.elements() {
65 tags.insert(tag);
66 if !attrs.is_empty() {
67 attributes
68 .entry(tag)
69 .or_default()
70 .extend(attrs.iter().copied());
71 }
72 }
73 }
74 let mut cleaned = ammonia::Builder::empty()
75 .tags(tags)
76 .tag_attributes(attributes)
77 .generic_attributes(HashSet::new())
78 .url_schemes(HashSet::from(["http", "https", "mailto"]))
79 .link_rel(Some("noopener noreferrer nofollow"))
80 .clean(html)
81 .to_string();
82 while let Some(kept) = cleaned.strip_suffix("<p></p>") {
83 cleaned.truncate(kept.len());
84 }
85 if plain_text(&cleaned).chars().all(invisible) {
86 String::new()
87 } else {
88 cleaned
89 }
90}
91
92fn invisible(c: char) -> bool {
94 c.is_whitespace() || matches!(c, '\u{200b}'..='\u{200d}' | '\u{2060}' | '\u{feff}')
95}
96
97pub fn from_text(text: &str) -> String {
110 let text = text.replace("\r\n", "\n");
111 text.split("\n\n")
112 .map(str::trim)
113 .filter(|paragraph| !paragraph.is_empty())
114 .map(|paragraph| {
115 let escaped = paragraph
116 .replace('&', "&")
117 .replace('<', "<")
118 .replace('>', ">")
119 .replace('\n', "<br>");
120 format!("<p>{escaped}</p>")
121 })
122 .collect()
123}
124
125pub(crate) fn plain_text(cleaned: &str) -> String {
128 read_text(cleaned).replace(BREAK, "\n")
129}
130
131pub(crate) fn text_length(cleaned: &str) -> usize {
134 read_text(cleaned).chars().filter(|c| *c != BREAK).count()
135}
136
137const BREAK: char = '\0';
140
141fn read_text(cleaned: &str) -> String {
146 let mut text = String::with_capacity(cleaned.len());
147 let mut pre = 0_usize;
148 let mut rest = cleaned;
149 while let Some(open) = rest.find(['<', '&']) {
150 push_text(&mut text, &rest[..open], pre > 0);
151 rest = &rest[open..];
152 if rest.starts_with('&') {
153 let end = rest.find(';').map_or(rest.len(), |end| end + 1);
154 text.push_str(match &rest[..end] {
155 "&" => "&",
156 "<" => "<",
157 ">" => ">",
158 """ => "\"",
159 " " => "\u{a0}",
160 other => other,
161 });
162 rest = &rest[end..];
163 continue;
164 }
165 let end = tag_end(rest);
166 let closing = rest[1..].starts_with('/');
167 let name: String = rest[1..end]
168 .trim_start_matches('/')
169 .chars()
170 .take_while(char::is_ascii_alphanumeric)
171 .collect();
172 if name == "pre" {
173 pre = if closing {
174 pre.saturating_sub(1)
175 } else {
176 pre + 1
177 };
178 }
179 if BLOCKS.contains(&name.as_str()) && !text.is_empty() && !text.ends_with(['\n', BREAK]) {
180 text.truncate(text.trim_end_matches(' ').len());
181 text.push(BREAK);
182 }
183 rest = &rest[(end + 1).min(rest.len())..];
184 }
185 push_text(&mut text, rest, pre > 0);
186 text.trim_matches(|c: char| c.is_whitespace() || c == BREAK)
187 .to_string()
188}
189
190fn push_text(text: &mut String, raw: &str, pre: bool) {
193 if pre {
194 text.push_str(raw);
195 return;
196 }
197 for c in raw.chars() {
198 if !c.is_ascii_whitespace() {
199 text.push(c);
200 } else if !(text.is_empty() || text.ends_with([' ', '\n', BREAK])) {
201 text.push(' ');
202 }
203 }
204}
205
206fn tag_end(tag: &str) -> usize {
208 let mut quoted = false;
209 for (at, c) in tag.char_indices() {
210 match c {
211 '"' => quoted = !quoted,
212 '>' if !quoted => return at,
213 _ => {}
214 }
215 }
216 tag.len()
217}
218
219pub(crate) const PROSE: &str = "max-w-none text-sm leading-relaxed whitespace-normal \
221 wrap-anywhere [&_p]:my-2 [&_h1]:mt-4 [&_h1]:mb-2 [&_h1]:text-2xl [&_h1]:font-semibold \
222 [&_h2]:mt-4 [&_h2]:mb-2 [&_h2]:text-xl [&_h2]:font-semibold [&_h3]:mt-3 [&_h3]:mb-1.5 \
223 [&_h3]:text-lg [&_h3]:font-semibold [&_ul]:my-2 [&_ul]:list-disc [&_ul]:pl-6 [&_ol]:my-2 \
224 [&_ol]:list-decimal [&_ol]:pl-6 [&_li_p]:my-0.5 [&_blockquote]:my-2 [&_blockquote]:border-l-2 \
225 [&_blockquote]:border-border [&_blockquote]:pl-4 [&_blockquote]:text-muted-foreground \
226 [&_a]:text-primary [&_a]:underline [&_a]:underline-offset-2 [&_code]:rounded \
227 [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.85em] \
228 [&_pre]:my-2 [&_pre]:overflow-x-auto [&_pre]:rounded-md [&_pre]:bg-muted [&_pre]:p-3 \
229 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_hr]:my-4 [&_hr]:border-border \
230 [&>:first-child]:mt-0 [&>:last-child]:mb-0";
231
232#[cfg(test)]
233mod tests;