ctb_formats_html/
html.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! HTML parsing, plain text rendering, and HTML table extraction utilities.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use include_dir::{Dir, include_dir};
30use std::iter;
31
32pub mod entities;
33pub mod markdown;
34pub mod text_clipper;
35pub mod text_decorator;
36
37static HTML_DATA_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/data");
38
39pub(crate) fn get_html_data(key: &str) -> Option<Vec<u8>> {
40    get_embedded_asset(&HTML_DATA_DIR, key)
41}
42
43/// Convert HTML bytes to plain text with default width 80.
44pub fn html2text(html: Vec<u8>) -> Result<Vec<u8>> {
45    html2text_with_width(html, 80)
46}
47
48/// Convert HTML bytes to plain text wrapped to the specified width.
49pub fn html2text_with_width(html: Vec<u8>, width: u16) -> Result<Vec<u8>> {
50    let width_usize = usize::from(width);
51    let text = html2text::from_read_with_decorator(
52        html.as_slice(),
53        width_usize,
54        crate::text_decorator::PlainTextDecorator::new(),
55    )
56    .map_err(|e| anyhow::anyhow!("Failed to parse HTML to text: {e}"))?;
57    Ok(text.into_bytes())
58}
59
60pub fn sanitize_html(document: Vec<u8>) -> Vec<u8> {
61    let mut builder = ammonia::Builder::default();
62
63    builder.add_generic_attributes(iter::once("class").chain(iter::once("id")));
64
65    builder
66        .clean(&String::from_utf8_lossy(&document))
67        .to_string()
68        .into_bytes()
69}
70
71#[cfg(test)]
72#[allow(
73    clippy::panic,
74    clippy::expect_used,
75    clippy::unwrap_used,
76    clippy::unwrap_in_result,
77    clippy::panic_in_result_fn,
78    clippy::indexing_slicing,
79    clippy::arithmetic_side_effects,
80    reason = "Standard repository test boilerplate"
81)]
82mod tests {
83    use super::*;
84
85    #[crate::ctb_test]
86    fn test_html2text_no_markdown_links() -> Result<()> {
87        let html = b"<p>Visit <a href=\"https://example.com/\">our website</a> for more details.</p>";
88        let text = html2text(html.to_vec())?;
89        let text_str = String::from_utf8(text)?;
90        assert_eq!(text_str.trim(), "Visit our website for more details.");
91        Ok(())
92    }
93
94    #[crate::ctb_test]
95    fn test_html2text_preserves_lists_and_quotes() -> Result<()> {
96        let html = b"<ul><li>Alpha</li><li>Beta</li></ul><blockquote><p>Quote text</p></blockquote>";
97        let text = html2text(html.to_vec())?;
98        let text_str = String::from_utf8(text)?;
99        assert!(text_str.contains("* Alpha"));
100        assert!(text_str.contains("* Beta"));
101        assert!(text_str.contains("> Quote text"));
102        Ok(())
103    }
104}