Skip to main content

trek_rs/elements/
code.rs

1//! Code block processing
2
3use lol_html::html_content::Element;
4
5/// Process code elements
6pub fn process_code_element(el: &mut Element) {
7    let tag_name = el.tag_name();
8
9    if tag_name == "pre" || tag_name == "code" {
10        // Extract language from class if present
11        if let Some(class_attr) = el.get_attribute("class") {
12            let has_language = class_attr
13                .split_whitespace()
14                .any(|class| class.starts_with("language-"));
15
16            if !has_language && tag_name == "code" {
17                // If code block doesn't have a language class, check parent
18                // Note: lol_html doesn't provide parent access, so we'll just preserve the element
19            }
20        }
21
22        // Remove unwanted attributes but keep class for language info
23        let class_value = el.get_attribute("class");
24        let attrs_to_remove: Vec<String> = el
25            .attributes()
26            .iter()
27            .filter(|attr| attr.name() != "class")
28            .map(lol_html::html_content::Attribute::name)
29            .collect();
30
31        for attr in attrs_to_remove {
32            el.remove_attribute(&attr);
33        }
34
35        // Re-add class if it had language info
36        if let Some(class) = class_value {
37            if class.split_whitespace().any(|c| c.starts_with("language-")) {
38                let _ = el.set_attribute("class", &class);
39            }
40        }
41    }
42}
43
44/// Standardize code blocks to a consistent format
45pub fn standardize_code_block(html: &str) -> String {
46    // This is a simplified version - in production, you'd use lol_html
47    html.to_string()
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn test_standardize_code_block() {
56        let html = r#"<pre><code class="language-rust">fn main() {}</code></pre>"#;
57        let result = standardize_code_block(html);
58        assert!(result.contains("language-rust"));
59    }
60}