Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
use clap::{Parser, ValueEnum};
use mdx::{render_file_to_file, Config, Error};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::sync::Arc;
use std::time::Duration;

/// MDX: A minimal, elegant Markdown to UI renderer with custom components
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
    /// Path to input Markdown file or directory
    input: String,

    /// Path to output HTML file or directory (defaults to same as input with .html extension)
    output: Option<String>,

    /// Theme to use
    #[arg(short, long, value_enum, default_value_t = ThemeArg::Modern)]
    theme: ThemeArg,

    /// Path to configuration file
    #[arg(short, long)]
    config: Option<PathBuf>,

    /// Path to custom components directory
    #[arg(long)]
    components: Option<PathBuf>,

    /// Watch for changes and rebuild
    #[arg(long)]
    watch: bool,

    /// Start a local preview server
    #[arg(long)]
    serve: Option<Option<u16>>,

    /// Minify HTML and CSS output
    #[arg(long)]
    minify: bool,
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
enum ThemeArg {
    Modern,
    Minimal,
    Dark,
    Light,
}

fn main() -> Result<(), Error> {
    let cli = Cli::parse();

    // Load configuration
    let mut config = match &cli.config {
        Some(path) => Config::from_file(path)?,
        None => Config::default(),
    };

    // Override config with CLI args
    config.theme.name = match cli.theme {
        ThemeArg::Modern => "modern".to_string(),
        ThemeArg::Minimal => "minimal".to_string(),
        ThemeArg::Dark => "dark".to_string(),
        ThemeArg::Light => "light".to_string(),
    };

    config.renderer.minify = cli.minify;

    // Add custom components directory if specified
    if let Some(components_dir) = &cli.components {
        config
            .components
            .push(components_dir.to_string_lossy().to_string());
    }

    // Get the input path
    let input_path = PathBuf::from(&cli.input);

    // If input is a directory, process all markdown files
    if input_path.is_dir() {
        let output_path = match &cli.output {
            Some(output) => PathBuf::from(output),
            None => input_path.clone(),
        };

        if !output_path.exists() {
            fs::create_dir_all(&output_path)?;
        }

        process_directory(&input_path, &output_path, &config)?;

        // Watch for changes if requested
        if cli.watch {
            watch_directory(&input_path, &output_path, &config)?;
        }
    } else {
        // Process a single file
        let output_path = match &cli.output {
            Some(output) => PathBuf::from(output),
            None => {
                let mut output = input_path.clone();
                output.set_extension("html");
                output
            }
        };

        // Create parent directory if it doesn't exist
        if let Some(parent) = output_path.parent() {
            if !parent.exists() {
                fs::create_dir_all(parent)?;
            }
        }

        render_file_to_file(
            input_path.to_str().unwrap(),
            output_path.to_str().unwrap(),
            Some(config.clone()),
        )?;

        println!(
            "Rendered {} to {}",
            input_path.display(),
            output_path.display()
        );

        // Watch for changes if requested
        if cli.watch {
            watch_file(&input_path, &output_path, &config)?;
        }
    }

    // Start server if requested
    if let Some(port_option) = cli.serve {
        let port = port_option.unwrap_or(3000);
        start_server(cli.output.unwrap_or_else(|| cli.input.clone()), port)?;
    }

    Ok(())
}

// Process all markdown files in a directory
fn process_directory(input_dir: &Path, output_dir: &Path, config: &Config) -> Result<(), Error> {
    let entries = fs::read_dir(input_dir)?;

    for entry in entries {
        let entry = entry?;
        let path = entry.path();

        if path.is_dir() {
            let relative_path = path.strip_prefix(input_dir).unwrap();
            let new_output_dir = output_dir.join(relative_path);

            if !new_output_dir.exists() {
                fs::create_dir_all(&new_output_dir)?;
            }

            process_directory(&path, &new_output_dir, config)?;
        } else if is_markdown_file(&path) {
            let relative_path = path.strip_prefix(input_dir).unwrap();
            let mut output_path = output_dir.join(relative_path);
            output_path.set_extension("html");

            // Create parent directory if it doesn't exist
            if let Some(parent) = output_path.parent() {
                if !parent.exists() {
                    fs::create_dir_all(parent)?;
                }
            }

            render_file_to_file(
                path.to_str().unwrap(),
                output_path.to_str().unwrap(),
                Some(config.clone()),
            )?;

            println!("Rendered {} to {}", path.display(), output_path.display());
        }
    }

    Ok(())
}

// Check if a file is a markdown file
fn is_markdown_file(path: &Path) -> bool {
    if let Some(ext) = path.extension() {
        let ext = ext.to_string_lossy().to_lowercase();
        ext == "md" || ext == "markdown"
    } else {
        false
    }
}

// Watch a directory for changes
fn watch_directory(input_dir: &Path, output_dir: &Path, config: &Config) -> Result<(), Error> {
    #[cfg(feature = "server")]
    {
        use notify::{RecommendedWatcher, RecursiveMode, Watcher};

        println!("Watching directory {} for changes...", input_dir.display());

        let (tx, rx) = mpsc::channel();
        let running = Arc::new(AtomicBool::new(true));
        let r = running.clone();

        ctrlc::set_handler(move || {
            r.store(false, Ordering::SeqCst);
        })
        .expect("Error setting Ctrl-C handler");

        let mut watcher = RecommendedWatcher::new(tx, notify::Config::default())?;
        watcher.watch(input_dir, RecursiveMode::Recursive)?;

        while running.load(Ordering::SeqCst) {
            match rx.recv_timeout(Duration::from_secs(1)) {
                Ok(event) => {
                    // Process the event
                    if let Ok(event) = event {
                        for path in event.paths {
                            if path.is_file() && is_markdown_file(&path) {
                                let relative_path = path.strip_prefix(input_dir).unwrap();
                                let mut output_path = output_dir.join(relative_path);
                                output_path.set_extension("html");

                                // Create parent directory if it doesn't exist
                                if let Some(parent) = output_path.parent() {
                                    if !parent.exists() {
                                        fs::create_dir_all(parent)?;
                                    }
                                }

                                match render_file_to_file(
                                    path.to_str().unwrap(),
                                    output_path.to_str().unwrap(),
                                    Some(config.clone()),
                                ) {
                                    Ok(_) => println!(
                                        "Rendered {} to {}",
                                        path.display(),
                                        output_path.display()
                                    ),
                                    Err(e) => {
                                        eprintln!("Error rendering {}: {}", path.display(), e)
                                    }
                                }
                            }
                        }
                    }
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    // No events received, continue
                }
                Err(e) => {
                    eprintln!("Watch error: {:?}", e);
                    break;
                }
            }
        }
    }

    #[cfg(not(feature = "server"))]
    {
        eprintln!("Watch feature is not enabled. Please build with --features server");
    }

    Ok(())
}

// Watch a file for changes
fn watch_file(input_file: &Path, output_file: &Path, config: &Config) -> Result<(), Error> {
    #[cfg(feature = "server")]
    {
        use notify::{RecommendedWatcher, RecursiveMode, Watcher};

        println!("Watching file {} for changes...", input_file.display());

        let (tx, rx) = mpsc::channel();
        let running = Arc::new(AtomicBool::new(true));
        let r = running.clone();

        ctrlc::set_handler(move || {
            r.store(false, Ordering::SeqCst);
        })
        .expect("Error setting Ctrl-C handler");

        let mut watcher = RecommendedWatcher::new(tx, notify::Config::default())?;
        watcher.watch(input_file, RecursiveMode::Recursive)?;

        while running.load(Ordering::SeqCst) {
            match rx.recv_timeout(Duration::from_secs(1)) {
                Ok(event) => {
                    // Process the event
                    if let Ok(event) = event {
                        for path in event.paths {
                            if path == *input_file {
                                match render_file_to_file(
                                    input_file.to_str().unwrap(),
                                    output_file.to_str().unwrap(),
                                    Some(config.clone()),
                                ) {
                                    Ok(_) => println!(
                                        "Rendered {} to {}",
                                        input_file.display(),
                                        output_file.display()
                                    ),
                                    Err(e) => {
                                        eprintln!("Error rendering {}: {}", input_file.display(), e)
                                    }
                                }
                            }
                        }
                    }
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    // No events received, continue
                }
                Err(e) => {
                    eprintln!("Watch error: {:?}", e);
                    break;
                }
            }
        }
    }

    #[cfg(not(feature = "server"))]
    {
        eprintln!("Watch feature is not enabled. Please build with --features server");
    }

    Ok(())
}

// Start a preview server
fn start_server(dir: String, port: u16) -> Result<(), Error> {
    #[cfg(feature = "server")]
    {
        use std::thread;
        use tiny_http::{Method, Response, Server, StatusCode};

        let server_dir = PathBuf::from(&dir);
        if !server_dir.exists() {
            return Err(Error::IoError(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("Directory not found: {}", dir),
            )));
        }

        let server = Server::http(format!("0.0.0.0:{}", port))
            .map_err(|e| Error::IoError(std::io::Error::new(std::io::ErrorKind::Other, e)))?;

        println!("Server started at http://localhost:{}", port);
        println!("Press Ctrl+C to stop the server");

        let running = Arc::new(AtomicBool::new(true));
        let r = running.clone();

        ctrlc::set_handler(move || {
            r.store(false, Ordering::SeqCst);
            println!("Stopping server...");
        })
        .expect("Error setting Ctrl-C handler");

        while running.load(Ordering::SeqCst) {
            if let Ok(Some(request)) = server.try_recv() {
                let method = request.method().clone();
                let url = request.url().to_string();

                // Only handle GET requests
                if method != Method::Get {
                    let response = Response::from_string("Method not allowed")
                        .with_status_code(StatusCode(405));
                    let _ = request.respond(response);
                    continue;
                }

                // Remove query parameters
                let url_path = url.split('?').next().unwrap_or("");

                // Determine file path
                let mut file_path = server_dir.clone();
                if url_path == "/" {
                    file_path.push("index.html");
                } else {
                    let decoded_path = url_decode(url_path);
                    let path = Path::new(&decoded_path);

                    // Remove leading slash and add to file path
                    let path_without_slash = path.strip_prefix("/").unwrap_or(path);
                    file_path.push(path_without_slash);
                }

                // Handle directory requests
                if file_path.is_dir() {
                    let index_path = file_path.join("index.html");
                    if index_path.exists() {
                        file_path = index_path;
                    } else {
                        // Generate directory listing
                        let listing = generate_directory_listing(&file_path, url_path);
                        let response =
                            Response::from_string(&listing).with_header(tiny_http::Header {
                                field: "Content-Type".parse().unwrap(),
                                value: "text/html; charset=utf-8".parse().unwrap(),
                            });
                        let _ = request.respond(response);
                        continue;
                    }
                }

                // If path doesn't have an extension and isn't a real file, try adding .html
                if !file_path.exists() && file_path.extension().is_none() {
                    let html_path = file_path.with_extension("html");
                    if html_path.exists() {
                        file_path = html_path;
                    }
                }

                // Serve the file if it exists
                if file_path.exists() {
                    let content_type = get_content_type(&file_path);

                    match fs::read(&file_path) {
                        Ok(content) => {
                            let response =
                                Response::from_data(content).with_header(tiny_http::Header {
                                    field: "Content-Type".parse().unwrap(),
                                    value: content_type.parse().unwrap(),
                                });
                            let _ = request.respond(response);
                        }
                        Err(e) => {
                            eprintln!("Error reading file {}: {}", file_path.display(), e);
                            let response = Response::from_string(format!("Error: {}", e))
                                .with_status_code(StatusCode(500));
                            let _ = request.respond(response);
                        }
                    }
                } else {
                    // File not found
                    let response =
                        Response::from_string("404 Not Found").with_status_code(StatusCode(404));
                    let _ = request.respond(response);
                }
            } else {
                // Sleep a bit to prevent CPU hogging
                thread::sleep(Duration::from_millis(100));
            }
        }
    }

    #[cfg(not(feature = "server"))]
    {
        eprintln!("Server feature is not enabled. Please build with --features server");
    }

    Ok(())
}

// URL decode a string
fn url_decode(input: &str) -> String {
    let mut result = String::with_capacity(input.len());
    let mut i = 0;
    let bytes = input.as_bytes();

    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let (Some(h), Some(l)) = (from_hex(bytes[i + 1]), from_hex(bytes[i + 2])) {
                result.push(((h << 4) | l) as char);
                i += 3;
            } else {
                result.push('%');
                i += 1;
            }
        } else if bytes[i] == b'+' {
            result.push(' ');
            i += 1;
        } else {
            result.push(bytes[i] as char);
            i += 1;
        }
    }

    result
}

// Convert a hex character to a value
fn from_hex(c: u8) -> Option<u8> {
    match c {
        b'0'..=b'9' => Some(c - b'0'),
        b'A'..=b'F' => Some(c - b'A' + 10),
        b'a'..=b'f' => Some(c - b'a' + 10),
        _ => None,
    }
}

// Get content type based on file extension
fn get_content_type(path: &Path) -> &'static str {
    if let Some(extension) = path.extension() {
        let ext = extension.to_string_lossy().to_lowercase();
        match ext.as_str() {
            "html" | "htm" => "text/html; charset=utf-8",
            "css" => "text/css; charset=utf-8",
            "js" => "application/javascript; charset=utf-8",
            "jpg" | "jpeg" => "image/jpeg",
            "png" => "image/png",
            "gif" => "image/gif",
            "svg" => "image/svg+xml",
            "ico" => "image/x-icon",
            "json" => "application/json; charset=utf-8",
            "pdf" => "application/pdf",
            "xml" => "application/xml; charset=utf-8",
            "md" | "markdown" => "text/markdown; charset=utf-8",
            "txt" => "text/plain; charset=utf-8",
            _ => "application/octet-stream",
        }
    } else {
        "application/octet-stream"
    }
}

// Generate HTML directory listing
fn generate_directory_listing(dir: &Path, url_path: &str) -> String {
    let mut html = String::from(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Directory Listing</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 900px;
            margin: 0 auto;
            padding: 1rem;
        }
        h1 {
            border-bottom: 1px solid #eee;
            padding-bottom: 0.5rem;
        }
        .listing {
            list-style: none;
            padding: 0;
        }
        .listing li {
            padding: 0.5rem;
            border-bottom: 1px solid #f4f4f4;
        }
        .listing li:hover {
            background-color: #f8f9fa;
        }
        .listing a {
            display: block;
            text-decoration: none;
            color: #0366d6;
        }
        .listing a:hover {
            text-decoration: underline;
        }
        .folder:before {
            content: "📁 ";
        }
        .file:before {
            content: "📄 ";
        }
    </style>
</head>
<body>
    <h1>Directory Listing: "#,
    );

    html.push_str(url_path);
    html.push_str("</h1>\n    <ul class=\"listing\">\n");

    // Add parent directory link if not at root
    if url_path != "/" {
        let parent_path = Path::new(url_path)
            .parent()
            .and_then(|p| p.to_str())
            .unwrap_or("/");

        html.push_str(&format!(
            "        <li><a href=\"{}\" class=\"folder\">..</a></li>\n",
            parent_path
        ));
    }

    // Add directory entries
    if let Ok(entries) = fs::read_dir(dir) {
        let mut dirs = Vec::new();
        let mut files = Vec::new();

        for entry in entries.flatten() {
            let path = entry.path();
            let file_name = entry.file_name().to_string_lossy().to_string();

            // Skip hidden files
            if file_name.starts_with('.') {
                continue;
            }

            let mut url = format!(
                "{}{}{}",
                url_path,
                if url_path.ends_with('/') { "" } else { "/" },
                file_name
            );

            if path.is_dir() {
                url.push('/');
                dirs.push((url, file_name, true));
            } else {
                files.push((url, file_name, false));
            }
        }

        // Sort directories and files
        dirs.sort_by(|a, b| a.1.to_lowercase().cmp(&b.1.to_lowercase()));
        files.sort_by(|a, b| a.1.to_lowercase().cmp(&b.1.to_lowercase()));

        // List directories first
        for (url, name, _) in dirs {
            html.push_str(&format!(
                "        <li><a href=\"{}\" class=\"folder\">{}</a></li>\n",
                url, name
            ));
        }

        // Then list files
        for (url, name, _) in files {
            html.push_str(&format!(
                "        <li><a href=\"{}\" class=\"file\">{}</a></li>\n",
                url, name
            ));
        }
    }

    html.push_str(
        r#"    </ul>
    <p><em>Generated by MDX</em></p>
</body>
</html>"#,
    );

    html
}