lex_babel/formats/html/
mod.rs

1//! HTML format implementation
2//!
3//! This module implements bidirectional conversion between Lex and HTML5.
4//!
5//! # Library Choice
6//!
7//! We use the `html5ever` + `rcdom` + `markup5ever` ecosystem for HTML parsing and serialization:
8//! - `html5ever`: Browser-grade HTML5 parser from the Servo project
9//! - `markup5ever_rcdom`: Reference-counted DOM tree implementation
10//! - `markup5ever`: Serialization infrastructure
11//!
12//! This choice is based on:
13//! - Complete solution for both parsing and serialization
14//! - Battle-tested with 12M+ downloads
15//! - WHATWG HTML5 specification compliance
16//! - Active maintenance by Servo project
17//! - Handles malformed HTML gracefully
18//!
19//! # Element Mapping Table
20//!
21//! Complete Lex ↔ HTML Mapping:
22//!
23//! | Lex Element      | HTML Equivalent                                    | Export Notes                              | Import Notes                          |
24//! |------------------|----------------------------------------------------|-------------------------------------------|---------------------------------------|
25//! | Document         | `<div class="lex-document">`                       | Root container with document class        | Parse body content                    |
26//! | Session          | `<section class="lex-session lex-session-N">` + `<hN>` | Session → section + heading        | section + heading → Session           |
27//! | Paragraph        | `<p class="lex-paragraph">`                        | Direct mapping with class                 | Direct mapping                        |
28//! | List             | `<ul>`/`<ol>` with `class="lex-list"`              | Ordered/unordered preserved with class    | Detect ul/ol type                     |
29//! | ListItem         | `<li class="lex-list-item">`                       | Direct mapping with class                 | Direct mapping                        |
30//! | Definition       | `<dl class="lex-definition">` `<dt>` `<dd>`        | Term in dt, description in dd             | Parse dl/dt/dd structure              |
31//! | Verbatim         | `<pre class="lex-verbatim">` `<code>`              | Language → data-language attribute        | Extract language from attribute       |
32//! | Annotation       | `<!-- lex:label key=val -->`                       | HTML comment format                       | Parse HTML comment pattern            |
33//! | InlineContent:   |                                                    |                                           |                                       |
34//! |   Text           | Plain text                                         | Direct                                    | Direct                                |
35//! |   Bold           | `<strong>`                                         | Semantic strong tag                       | Parse both strong and b               |
36//! |   Italic         | `<em>`                                             | Semantic emphasis tag                     | Parse both em and i                   |
37//! |   Code           | `<code>`                                           | Inline code tag                           | Direct                                |
38//! |   Math           | `<span class="lex-math">`                          | Preserve $ delimiters in span             | Parse math span                       |
39//! |   Reference      | `<a href="url">text</a>`                           | Convert to anchor with prev word as text  | Parse anchor back to reference        |
40//!
41//! # CSS Classes
42//!
43//! All Lex elements receive CSS classes matching their AST structure:
44//! - `.lex-document`: Root document container
45//! - `.lex-session`, `.lex-session-1`, `.lex-session-2`, etc.: Sessions with depth
46//! - `.lex-paragraph`: Paragraphs
47//! - `.lex-list`: Lists (combined with ul/ol)
48//! - `.lex-list-item`: List items
49//! - `.lex-definition`: Definition lists
50//! - `.lex-verbatim`: Verbatim/code blocks
51//! - `.lex-math`: Math expressions
52//!
53//! This enables:
54//! - Precise CSS targeting for presentation
55//! - Perfect round-trip conversion (HTML → Lex → HTML preserves structure)
56//! - Custom theming without modifying structure
57//!
58//! # CSS and Theming
59//!
60//! HTML export includes embedded CSS from:
61//! - `css/baseline.css`: Browser reset + default modern presentation (always included)
62//! - `css/themes/theme-*.css`: Optional overrides layered on top of the baseline
63//!
64//! The default theme (`HtmlTheme::Modern`) injects an empty stylesheet so the
65//! baseline alone controls rendering. Other themes, like Fancy Serif, only add
66//! targeted overrides.
67//!
68//! Themes use Google Fonts and are mobile-responsive.
69//!
70//! # Output Format
71//!
72//! Export produces a single, self-contained HTML file:
73//! - Complete HTML5 document structure
74//! - Embedded CSS in <style> tag
75//! - No external dependencies (except optionally-linked fonts)
76//! - Mobile-responsive viewport meta tag
77//!
78//! # Lossy Conversions
79//!
80//! The following conversions may lose information on round-trip:
81//! - Lex sessions beyond level 6 → h6 with nested sections (HTML heading limit)
82//! - Lex annotations → HTML comments (exported but parsing is lossy)
83//! - Some whitespace normalization
84//!
85//! # Architecture Notes
86//!
87//! Like the Markdown implementation, we handle the nested-to-flat conversion using the IR
88//! event system (lex-babel/src/common/). HTML is more naturally hierarchical than Markdown,
89//! but sessions still require special handling as they don't map directly to HTML's heading
90//! structure.
91//!
92//! We use semantic HTML elements with CSS classes for styling rather than presentational
93//! elements.
94//!
95//! # Implementation Status
96//!
97//! - [x] Export (Lex → HTML)
98//!   - [ ] Document structure with CSS embedding
99//!   - [ ] Paragraph
100//!   - [ ] Heading (Session) → section + heading
101//!   - [ ] Bold, Italic, Code inlines
102//!   - [ ] Lists - ordered/unordered
103//!   - [ ] Code blocks (Verbatim) with language attribute
104//!   - [ ] Definitions → dl/dt/dd
105//!   - [ ] Annotations → HTML comments
106//!   - [ ] Math → span with class
107//!   - [ ] References → anchors with link conversion
108//! - [ ] Import (HTML → Lex)
109//!   - [ ] All elements (to be implemented after export)
110
111mod serializer;
112
113use crate::error::FormatError;
114use crate::format::Format;
115use lex_core::lex::ast::Document;
116
117/// Format implementation for HTML
118pub struct HtmlFormat {
119    /// CSS theme to use for export
120    theme: HtmlTheme,
121}
122
123/// Available CSS themes for HTML export
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum HtmlTheme {
126    /// Serif typography override (fonts only, layout comes from baseline)
127    FancySerif,
128    /// Baseline modern theme (no-op; relies on baseline.css)
129    Modern,
130}
131
132impl Default for HtmlFormat {
133    fn default() -> Self {
134        Self::new(HtmlTheme::Modern)
135    }
136}
137
138impl HtmlFormat {
139    /// Create a new HTML format with the specified theme
140    pub fn new(theme: HtmlTheme) -> Self {
141        Self { theme }
142    }
143
144    /// Create HTML format with fancy serif theme
145    pub fn with_fancy_serif() -> Self {
146        Self::new(HtmlTheme::FancySerif)
147    }
148
149    /// Create HTML format with modern theme
150    pub fn with_modern() -> Self {
151        Self::new(HtmlTheme::Modern)
152    }
153}
154
155impl Format for HtmlFormat {
156    fn name(&self) -> &str {
157        "html"
158    }
159
160    fn description(&self) -> &str {
161        "HTML5 format with embedded CSS"
162    }
163
164    fn file_extensions(&self) -> &[&str] {
165        &["html", "htm"]
166    }
167
168    fn supports_parsing(&self) -> bool {
169        false // Implement after export is working
170    }
171
172    fn supports_serialization(&self) -> bool {
173        true
174    }
175
176    fn parse(&self, _source: &str) -> Result<Document, FormatError> {
177        Err(FormatError::NotSupported(
178            "HTML import not yet implemented".to_string(),
179        ))
180    }
181
182    fn serialize(&self, doc: &Document) -> Result<String, FormatError> {
183        serializer::serialize_to_html(doc, self.theme)
184    }
185
186    fn serialize_with_options(
187        &self,
188        doc: &Document,
189        options: &std::collections::HashMap<String, String>,
190    ) -> Result<crate::format::SerializedDocument, FormatError> {
191        let mut theme = self.theme;
192        if let Some(theme_str) = options.get("theme") {
193            theme = match theme_str.as_str() {
194                "fancy-serif" => HtmlTheme::FancySerif,
195                "modern" | "default" => HtmlTheme::Modern,
196                _ => {
197                    // Fallback to default for unknown themes, or could error.
198                    // For now, let's fallback to Modern to be safe.
199                    HtmlTheme::Modern
200                }
201            };
202        }
203
204        serializer::serialize_to_html(doc, theme).map(crate::format::SerializedDocument::Text)
205    }
206}