Skip to main content

tablo_core/
rich_text.rs

1//! Rich text (ADR-0032): the [`Tool`]s a toolbar offers, the HTML each produces, and
2//! the cleaning that keeps a value to the elements its tools produce. A rich text field cleans what
3//! it reads and [`RichTextColumn`](crate::RichTextColumn) what it renders; a page of the app's own
4//! renders a stored value through [`clean`].
5//!
6//! Rich text sits behind the `rich-text` feature, on by default. An app that turns the default
7//! features off and leaves it out has no rich text field, column or module, and builds without
8//! `ammonia` and its HTML parser.
9
10pub(crate) mod tool;
11
12use std::collections::{HashMap, HashSet};
13
14pub(crate) use self::tool::Tool;
15
16/// The elements every document holds, whatever its tools: paragraphs and line breaks.
17const ALWAYS: &[&str] = &["p", "br"];
18
19/// The elements that end a line of a document's text.
20const BLOCKS: &[&str] = &["p", "br", "h1", "h2", "h3", "li", "blockquote", "pre", "hr"];
21
22/// `html` keeping only what some [`Tool`] produces, or `""` when it holds no text: HTML a page
23/// may render unescaped, as a [`RichTextColumn`](crate::RichTextColumn) does.
24///
25/// ```rust
26/// use tablo_core::rich_text::clean;
27///
28/// assert_eq!(
29///     clean(r#"<p onclick="steal()">Hi <script>alert(1)</script><b>there</b></p>"#),
30///     "<p>Hi there</p>",
31/// );
32/// ```
33///
34/// A rich text field stores its value cleaned already, with its own toolbar's tools; cleaning
35/// again keeps a value the column's other writers stored to the same rules.
36pub fn clean(html: &str) -> String {
37    clean_with(html, Tool::ALL.iter().copied())
38}
39
40/// The text a reader sees in `html`, with a line break after each block: a summary, a search
41/// index or a word count.
42///
43/// ```rust
44/// use tablo_core::rich_text::text;
45///
46/// assert_eq!(
47///     text("<h2>Tea &amp; cake</h2><p>Two <em>slices</em></p>"),
48///     "Tea & cake\nTwo slices"
49/// );
50/// ```
51pub fn text(html: &str) -> String {
52    plain_text(&clean(html))
53}
54
55/// `html` keeping only what `tools` produce, or `""` when it holds no text, so a blank document
56/// reads as an empty submission. No allowlist keeps a `style` or an event handler, a link takes
57/// only an `http`, `https`, `mailto` or relative URL, and every link gets
58/// `rel="noopener noreferrer nofollow"`. The empty paragraphs ending a document, which the
59/// editor keeps after a list, a heading or a code block, are dropped.
60pub(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
92/// Whether `c` shows nothing: whitespace, or a zero-width character.
93fn invisible(c: char) -> bool {
94    c.is_whitespace() || matches!(c, '\u{200b}'..='\u{200d}' | '\u{2060}' | '\u{feff}')
95}
96
97/// A rich text document showing `text`: a paragraph for each run of lines between blank lines, a
98/// line break for each single newline, and `&`, `<` and `>` escaped. It moves a plain text column
99/// to rich text, whose fields read their stored value as HTML.
100///
101/// ```rust
102/// use tablo_core::rich_text::from_text;
103///
104/// assert_eq!(
105///     from_text("Use Vec<String>.\nOr not.\n\nThe end"),
106///     "<p>Use Vec&lt;String&gt;.<br>Or not.</p><p>The end</p>"
107/// );
108/// ```
109pub 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('&', "&amp;")
117                .replace('<', "&lt;")
118                .replace('>', "&gt;")
119                .replace('\n', "<br>");
120            format!("<p>{escaped}</p>")
121        })
122        .collect()
123}
124
125/// The text a reader sees in `cleaned`, the output of [`clean`], with a line break after each
126/// block and the ends trimmed.
127pub(crate) fn plain_text(cleaned: &str) -> String {
128    read_text(cleaned).replace(BREAK, "\n")
129}
130
131/// How many characters a reader sees in `cleaned`: its text without the line breaks between
132/// blocks.
133pub(crate) fn text_length(cleaned: &str) -> usize {
134    read_text(cleaned).chars().filter(|c| *c != BREAK).count()
135}
136
137/// Where [`read_text`] ends a block: a character no cleaned document holds, since the parser
138/// drops every NUL.
139const BREAK: char = '\0';
140
141/// The text a reader sees in `cleaned`, a [`BREAK`] after each block and the ends trimmed.
142/// Outside a `<pre>`, a run of whitespace reads as one space, as a browser shows it. It reads
143/// the serializer's output only: every tag closes its quoted attributes, and text escapes only
144/// `&`, `<`, `>` and the no-break space.
145fn 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                "&amp;" => "&",
156                "&lt;" => "<",
157                "&gt;" => ">",
158                "&quot;" => "\"",
159                "&nbsp;" => "\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
190/// Appends the text node `raw` to `text`: as written inside a `<pre>`, else with each run of
191/// whitespace read as one space and none at the start of a line.
192fn 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
206/// The index of the `>` closing the tag `tag` starts with, past any quoted attribute value.
207fn 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
219/// The Tailwind classes a rich text value renders in, on a detail page and in its editor.
220pub(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;