ctb_formats_eite/formats/
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 representation formatter and output encoder for EITE.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::Result;
30
31use crate::{
32    dc::{dc_get_script, dc_get_type},
33    formats::dc_to_format,
34};
35use ctb_formats_utilities::FormatLog;
36
37/// Build an HTML fragment (div with pre-wrap) from a Dc array using dc->html conversion.
38pub fn dca_to_html_fragment(dc_array: &[u32]) -> Result<(Vec<u8>, FormatLog)> {
39    let mut out = Vec::new();
40    out.extend_from_slice(b"<div style=\"white-space:pre-wrap\">");
41    let mut log = FormatLog::default();
42    for &dc in dc_array {
43        let (encoded, dc_log) = dc_to_format("html", dc)?;
44        out.extend_from_slice(&encoded);
45        log.merge(&dc_log);
46    }
47    out.extend_from_slice(b"</div>");
48    Ok((out, log))
49}
50
51/// Build a minimal HTML document containing the HTML fragment for a Dc array.
52pub fn dca_to_html(dc_array: &[u32]) -> Result<(Vec<u8>, FormatLog)> {
53    let mut out = Vec::new();
54    out.extend_from_slice(
55        b"<!DOCTYPE html><html><head><title></title></head><body>",
56    );
57    let (fragment, log) = dca_to_html_fragment(dc_array)?;
58    out.extend(fragment);
59    out.extend_from_slice(b"</body></html>");
60    Ok((out, log))
61}
62
63/// Convert Dc array to a full HTML document with color coding legend + fragment.
64pub fn dca_to_colorcoded(dc_array: &[u32]) -> Result<Vec<u8>> {
65    let mut out = Vec::new();
66    out.extend_from_slice(
67        b"<!DOCTYPE html><html><head><title></title></head><body>\
68        <p>Key: <span style=\"color:black\">Letter</span> \
69<span style=\"color:gray\">Control</span> \
70<span style=\"color:blue\">Semantic</span> \
71<span style=\"color:salmon\">Mathematics</span> \
72<span style=\"color:rebeccapurple\">Symbols</span> \
73<span style=\"color:red\">Programming</span> \
74<span style=\"color:green\">Financial</span> \
75<span style=\"color:orange\">Punctuation</span> \
76<span style=\"color:purple\">Emoji</span> \
77<span style=\"color:maroon\">Styling</span> \
78<span style=\"color:brown\">Other</span></p>",
79    );
80    out.extend(dca_to_colorcoded_fragment(dc_array)?);
81    out.extend_from_slice(b"</body></html>");
82    Ok(out)
83}
84
85/// Color-coded fragment (div wrapper) for Dc array.
86pub fn dca_to_colorcoded_fragment(dc_array: &[u32]) -> Result<Vec<u8>> {
87    let mut out = Vec::new();
88    out.extend_from_slice(b"<div style=\"white-space:pre-wrap\">");
89    for &dc in dc_array {
90        out.extend(dc_to_colorcoded(dc)?);
91    }
92    out.extend_from_slice(b"</div>");
93    Ok(out)
94}
95
96/// Color-coded span for a single Dc.
97pub fn dc_to_colorcoded(dc: u32) -> Result<Vec<u8>> {
98    // Determine classification
99    // Reason for fallback: when dc_get_type returns an error or unclassified codepoint, defaulting to empty string falls through to default black text color.
100    let dc_type = dc_get_type(dc).unwrap_or_default();
101    // Reason for fallback: when dc_get_script returns an error or unclassified codepoint, defaulting to empty string falls through to default black text color.
102    let script = dc_get_script(dc).unwrap_or_default();
103    let color = if dc_type.starts_with('L') {
104        // Letter
105        "black"
106    } else if script == "Controls" {
107        "gray"
108    } else if script == "Semantic" {
109        "blue"
110    } else if script == "Mathematics" {
111        "salmon"
112    } else if script == "Symbols" {
113        "rebeccapurple"
114    } else if script.starts_with("EL ") {
115        "red" // Programming
116    } else if script == "Financial" {
117        "green"
118    } else if script == "Punctuation" {
119        "orange"
120    } else if script == "Emoji" {
121        "purple"
122    } else if script == "Colors" {
123        "maroon"
124    } else {
125        "brown"
126    };
127    let mut out = Vec::new();
128    out.extend_from_slice(b"<span style=\"color:");
129    out.extend_from_slice(color.as_bytes());
130    out.extend_from_slice(b"\">");
131    out.extend_from_slice(dc.to_string().as_bytes());
132    out.extend_from_slice(b"</span> ");
133    Ok(out)
134}
135
136#[cfg(test)]
137#[allow(
138    clippy::panic,
139    clippy::expect_used,
140    clippy::unwrap_used,
141    clippy::unwrap_in_result,
142    clippy::panic_in_result_fn,
143    clippy::indexing_slicing,
144    clippy::arithmetic_side_effects,
145    reason = "Standard repository test boilerplate"
146)]
147mod tests {
148    use crate::util::string::str_to_byte_array;
149    use ctb_formats_utilities::assert_vec_u8_ok_eq_no_warnings;
150
151    use super::*;
152
153    #[crate::ctb_test]
154    fn test_dca_to_html_fragment() -> Result<()> {
155        let actual = dca_to_html_fragment(&[39, 46, 40]);
156        let expected = str_to_byte_array(
157            "<div style=\"white-space:pre-wrap\">5&lt;6</div>",
158        )?;
159        assert_vec_u8_ok_eq_no_warnings(&expected, actual);
160        Ok(())
161    }
162
163    #[crate::ctb_test]
164    fn test_format_html() -> Result<()> {
165        // Input Dcs: [39,46,40] expected to produce: "<div style=\"white-space:pre-wrap\">5&lt;6</div>"
166        // Wrapped with full HTML skeleton per original JS dcaToHtml test.
167        let expected_html = "<!DOCTYPE html><html><head><title></title></head><body><div style=\"white-space:pre-wrap\">5&lt;6</div></body></html>";
168        let result = dca_to_html(&[39, 46, 40]);
169        assert_vec_u8_ok_eq_no_warnings(
170            &str_to_byte_array(expected_html)?,
171            result,
172        );
173        Ok(())
174    }
175
176    #[crate::ctb_test]
177    fn test_dca_to_colorcoded_basic() {
178        let dc_array = vec![65, 66]; // Example Dcs
179        let html = dca_to_colorcoded(&dc_array).unwrap();
180        let s = String::from_utf8(html).unwrap();
181        assert!(s.contains("<span style=\"color:"));
182    }
183}