# Markdown to HTML Examples

Quick examples showing all the ways to use the markdown-to-HTML functionality.

## Example 1: Convert a Blog Post

```rust
use herolib_web::markdown;
use std::fs;

fn main() -> std::io::Result<()> {
    let markdown = fs::read_to_string("blog.md")?;
    let html = markdown::markdown_to_html_page(&markdown, "My Blog Post");
    fs::write("blog.html", &html)?;
    println!("Blog post converted!");
    Ok(())
}
```

## Example 2: Convert README to Documentation

```rust
use herolib_web::markdown;
use std::fs;

fn main() -> std::io::Result<()> {
    let readme = fs::read_to_string("README.md")?;
    let html = markdown::markdown_to_html_page(&readme, "Project Documentation");
    fs::write("docs/index.html", &html)?;
    Ok(())
}
```

## Example 3: Generate Table of Contents

```rust
use herolib_web::markdown;
use std::fs;

fn main() -> std::io::Result<()> {
    let markdown = fs::read_to_string("manual.md")?;
    
    // Generate HTML page
    let html = markdown::markdown_to_html_page(&markdown, "User Manual");
    fs::write("manual.html", &html)?;
    
    // Generate table of contents
    let toc = markdown::markdown_to_toc_bootstrap(&markdown);
    fs::write("manual_toc.html", &toc)?;
    
    Ok(())
}
```

## Example 4: Embed in Web Framework

```rust
use herolib_web::markdown;
use actix_web::{web, HttpResponse};

async fn render_article(
    article: web::Path<String>,
) -> HttpResponse {
    let markdown = format!("# {}\n\nContent here", article);
    let html = markdown::markdown_to_html_bootstrap(&markdown);
    
    let page = format!(
        r#"<!DOCTYPE html>
<html>
<head>
    <title>{}</title>
</head>
<body>
{}
</body>
</html>"#,
        article, html
    );
    
    HttpResponse::Ok()
        .content_type("text/html; charset=utf-8")
        .body(page)
}
```

## Example 5: Static Site Generator

```rust
use herolib_web::markdown;
use std::fs;
use std::path::Path;

fn generate_site(source_dir: &str, output_dir: &str) -> std::io::Result<()> {
    fs::create_dir_all(output_dir)?;
    
    for entry in fs::read_dir(source_dir)? {
        let entry = entry?;
        let path = entry.path();
        
        if path.extension().map_or(false, |ext| ext == "md") {
            let markdown = fs::read_to_string(&path)?;
            let filename = path.file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("page");
            
            let html = markdown::markdown_to_html_page(&markdown, filename);
            
            let output_path = Path::new(output_dir)
                .join(format!("{}.html", filename));
            
            fs::write(output_path, html)?;
            println!("Generated: {}.html", filename);
        }
    }
    
    Ok(())
}

fn main() -> std::io::Result<()> {
    generate_site("./markdown", "./dist")
}
```

## Example 6: Newsletter Generator

```rust
use herolib_web::markdown;

fn generate_newsletter(
    title: &str,
    content: &str,
) -> String {
    let markdown = format!(
        "# {}\n\nDate: {}\n\n{}",
        title,
        chrono::Local::now().format("%B %d, %Y"),
        content
    );
    
    markdown::markdown_to_html_page(&markdown, title)
}

fn main() {
    let newsletter = generate_newsletter(
        "Weekly Newsletter",
        r#"
## Highlights

- New feature released
- Bug fixes
- Performance improvements

## Featured Content

Read our latest article about web development.

## What's Next

Stay tuned!
"#
    );
    
    // Send as email
    println!("{}", newsletter);
}
```

## Example 7: Documentation API

```rust
use herolib_web::markdown;

pub struct DocGenerator;

impl DocGenerator {
    /// Convert markdown to standalone HTML page
    pub fn to_page(markdown: &str, title: &str) -> String {
        markdown::markdown_to_html_page(markdown, title)
    }
    
    /// Convert markdown to embeddable HTML
    pub fn to_fragment(markdown: &str) -> String {
        markdown::markdown_to_html_bootstrap(markdown)
    }
    
    /// Extract table of contents
    pub fn extract_toc(markdown: &str) -> String {
        markdown::markdown_to_toc_bootstrap(markdown)
    }
    
    /// Get document statistics
    pub fn stats(markdown: &str) -> DocumentStats {
        DocumentStats {
            headings: markdown::extract_headings(markdown).len(),
            words: markdown::count_words(markdown),
            lines: markdown::count_lines(markdown),
        }
    }
}

struct DocumentStats {
    headings: usize,
    words: usize,
    lines: usize,
}

fn main() {
    let md = "# Title\n\nContent";
    
    println!("Page: {}", DocGenerator::to_page(md, "Title").len());
    println!("Fragment: {}", DocGenerator::to_fragment(md).len());
    println!("TOC: {}", DocGenerator::extract_toc(md).len());
    
    let stats = DocGenerator::stats(md);
    println!("Headings: {}, Words: {}, Lines: {}",
             stats.headings, stats.words, stats.lines);
}
```

## Example 8: Batch Conversion

```rust
use herolib_web::markdown;
use std::fs;
use std::path::Path;

fn convert_all_markdown_files(
    input_dir: &str,
    output_dir: &str,
) -> std::io::Result<usize> {
    fs::create_dir_all(output_dir)?;
    
    let mut count = 0;
    
    for entry in fs::read_dir(input_dir)? {
        let entry = entry?;
        let path = entry.path();
        
        if path.is_file() && path.extension()
            .map_or(false, |ext| ext == "md") {
            
            let markdown = fs::read_to_string(&path)?;
            let stem = path.file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("document");
            
            let html = markdown::markdown_to_html_page(&markdown, stem);
            
            let output_file = Path::new(output_dir)
                .join(format!("{}.html", stem));
            
            fs::write(output_file, html)?;
            count += 1;
            println!("✓ Converted: {}", stem);
        }
    }
    
    Ok(count)
}

fn main() -> std::io::Result<()> {
    let count = convert_all_markdown_files("./markdown", "./html")?;
    println!("\nConverted {} files", count);
    Ok(())
}
```

## Example 9: Process with Custom Title

```rust
use herolib_web::markdown;
use std::fs;

fn convert_with_metadata(md_file: &str) -> std::io::Result<()> {
    let content = fs::read_to_string(md_file)?;
    
    // Extract title from first heading
    let title = markdown::extract_headings(&content)
        .first()
        .map(|(_, text)| text.clone())
        .unwrap_or_else(|| "Document".to_string());
    
    let html = markdown::markdown_to_html_page(&content, &title);
    
    let output_file = md_file.replace(".md", ".html");
    fs::write(output_file, html)?;
    
    Ok(())
}

fn main() -> std::io::Result<()> {
    convert_with_metadata("document.md")?;
    Ok(())
}
```

## Example 10: Multi-format Export

```rust
use herolib_web::markdown;
use std::fs;

fn export_document(
    markdown_file: &str,
    output_dir: &str,
) -> std::io::Result<()> {
    let markdown = fs::read_to_string(markdown_file)?;
    let title = markdown_file.replace(".md", "");
    
    fs::create_dir_all(output_dir)?;
    
    // Export 1: Full HTML page
    let html = markdown::markdown_to_html_page(&markdown, &title);
    fs::write(
        format!("{}/{}_page.html", output_dir, title),
        html
    )?;
    
    // Export 2: Fragment for embedding
    let fragment = markdown::markdown_to_html_bootstrap(&markdown);
    fs::write(
        format!("{}/{}_fragment.html", output_dir, title),
        fragment
    )?;
    
    // Export 3: Table of contents
    let toc = markdown::markdown_to_toc_bootstrap(&markdown);
    fs::write(
        format!("{}/{}_toc.html", output_dir, title),
        toc
    )?;
    
    // Export 4: Plain HTML (no Bootstrap)
    let plain = markdown::markdown_to_html(&markdown);
    fs::write(
        format!("{}/{}_plain.html", output_dir, title),
        plain
    )?;
    
    println!("Exported: {}", title);
    println!("  - Full page");
    println!("  - Fragment");
    println!("  - Table of contents");
    println!("  - Plain HTML");
    
    Ok(())
}

fn main() -> std::io::Result<()> {
    export_document("README.md", "./exports")?;
    Ok(())
}
```

## Markdown Syntax Examples

All standard Markdown is supported:

```markdown
# Heading 1
## Heading 2
### Heading 3

**Bold text** and *italic text*

- Bullet point 1
- Bullet point 2
  - Nested item

1. Ordered item 1
2. Ordered item 2

> This is a blockquote
> with multiple lines

[Link text](https://example.com)

![Image alt text](image.jpg)

`inline code`

\`\`\`rust
fn main() {
    println!("Code block");
}
\`\`\`

---

| Table | Header |
|-------|--------|
| Cell  | Data   |
```

## Testing Your Generated HTML

```rust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_conversion() {
        let md = "# Test\n\nContent";
        let html = markdown::markdown_to_html_page(md, "Test");
        
        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("<h1>Test</h1>"));
        assert!(html.contains("<p>Content</p>"));
        assert!(html.contains("bootstrap"));
    }
}
```

## Performance Tips

- For large documents (>1MB), consider processing in chunks
- Regex patterns are cached, so first call may be slightly slower
- File I/O is the main bottleneck for bulk operations
- Use parallel processing for batch conversions

## Integration Checklist

- [ ] Add `herolib-web` to your `Cargo.toml`
- [ ] Import `markdown` module: `use herolib_web::markdown;`
- [ ] Choose conversion function based on use case
- [ ] Test with sample markdown files
- [ ] Customize CSS if needed
- [ ] Integrate with your workflow

