sherwood 0.5.0

A static site generator with built-in development server
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
use super::parser::MarkdownFile;
use crate::presentation::templates::TemplateManager;
use anyhow::Result;
use chrono::NaiveDate;
use pulldown_cmark::{Options, Parser, html};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

#[derive(Debug)]
struct SortConfig {
    field: String,
    order: String,
}

impl SortConfig {
    fn from_frontmatter(frontmatter: &super::parser::Frontmatter) -> Self {
        let field = frontmatter
            .sort_by
            .as_ref()
            .map(|s| s.to_lowercase())
            .unwrap_or_else(|| "date".to_string());

        let order = frontmatter
            .sort_order
            .as_ref()
            .map(|s| s.to_lowercase())
            .unwrap_or_else(|| {
                if field == "date" {
                    "desc".to_string()
                } else {
                    "asc".to_string()
                }
            });

        Self { field, order }
    }

    fn is_valid_field(field: &str) -> bool {
        matches!(field, "date" | "title" | "filename")
    }

    fn is_valid_order(order: &str) -> bool {
        matches!(order, "asc" | "desc")
    }
}

pub struct HtmlRenderer {
    input_dir: PathBuf,
    template_manager: TemplateManager,
}

impl HtmlRenderer {
    pub fn new(input_dir: &Path, template_manager: TemplateManager) -> Self {
        Self {
            input_dir: input_dir.to_path_buf(),
            template_manager,
        }
    }

    fn sort_markdown_files(&self, files: &mut [MarkdownFile], sort_config: &SortConfig) {
        // Validate sort configuration
        let field = if SortConfig::is_valid_field(&sort_config.field) {
            &sort_config.field
        } else {
            eprintln!(
                "Warning: Invalid sort field '{}', falling back to 'date'",
                sort_config.field
            );
            "date"
        };

        let order = if SortConfig::is_valid_order(&sort_config.order) {
            &sort_config.order
        } else {
            eprintln!(
                "Warning: Invalid sort order '{}', falling back to 'asc'",
                sort_config.order
            );
            "asc"
        };

        files.sort_by(|a, b| {
            let comparison = match field {
                "date" => self.compare_by_date(a, b),
                "title" => a.title.cmp(&b.title),
                "filename" => self.compare_by_filename(a, b),
                _ => Ordering::Equal, // Should not reach here due to validation
            };

            if order == "desc" {
                comparison.reverse()
            } else {
                comparison
            }
        });
    }

    fn compare_by_date(&self, a: &MarkdownFile, b: &MarkdownFile) -> Ordering {
        match (&a.frontmatter.date, &b.frontmatter.date) {
            (Some(date_a), Some(date_b)) => {
                match (self.parse_date(date_a), self.parse_date(date_b)) {
                    (Some(parsed_a), Some(parsed_b)) => parsed_a.cmp(&parsed_b),
                    (Some(_), None) => Ordering::Less, // Valid date comes before invalid
                    (None, Some(_)) => Ordering::Greater,
                    (None, None) => self.compare_by_filename(a, b), // Both invalid, fall back to filename
                }
            }
            (Some(_), None) => Ordering::Less, // File with date comes before file without
            (None, Some(_)) => Ordering::Greater,
            (None, None) => self.compare_by_filename(a, b), // Neither has date, fall back to filename
        }
    }

    fn compare_by_filename(&self, a: &MarkdownFile, b: &MarkdownFile) -> Ordering {
        a.path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("")
            .cmp(b.path.file_name().and_then(|n| n.to_str()).unwrap_or(""))
    }

    fn parse_date(&self, date_str: &str) -> Option<NaiveDate> {
        // Try ISO format first (YYYY-MM-DD)
        if let Ok(date) = NaiveDate::parse_from_str(date_str.trim(), "%Y-%m-%d") {
            return Some(date);
        }

        // Try other common formats
        let formats = [
            "%B %d, %Y", // "January 15, 2024"
            "%b %d, %Y", // "Jan 15, 2024"
            "%d/%m/%Y",  // "15/01/2024"
            "%m/%d/%Y",  // "01/15/2024"
            "%Y-%m-%d",  // "2024-01-15" (duplicate but ensures we try again)
        ];

        for format in &formats {
            if let Ok(date) = NaiveDate::parse_from_str(date_str.trim(), format) {
                return Some(date);
            }
        }

        None
    }

    pub fn markdown_to_semantic_html(&self, markdown: &str) -> Result<String> {
        let mut options = Options::empty();
        options.insert(Options::ENABLE_STRIKETHROUGH);
        options.insert(Options::ENABLE_TABLES);
        options.insert(Options::ENABLE_FOOTNOTES);

        let parser = Parser::new_ext(markdown, options);
        let mut html_output = String::new();
        html::push_html(&mut html_output, parser);

        Ok(self.enhance_semantics(&html_output))
    }

    pub fn generate_blog_list_content(
        &self,
        dir: &Path,
        list_pages: &HashMap<PathBuf, &MarkdownFile>,
    ) -> Result<String> {
        // Find the list page for this directory to get sort configuration
        let sort_config = list_pages
            .get(dir)
            .map(|list_page| SortConfig::from_frontmatter(&list_page.frontmatter))
            .unwrap_or_else(|| SortConfig {
                field: "date".to_string(),
                order: "desc".to_string(),
            });

        let mut markdown_files = Vec::new();

        // Collect all markdown files in this directory (excluding index.md)
        for entry in std::fs::read_dir(self.input_dir.join(dir))? {
            let entry = entry?;
            let path = entry.path();

            if path.is_file()
                && let Some(extension) = path.extension()
                && (extension == "md" || extension == "markdown")
            {
                let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");

                // Skip index files and other list pages
                if !file_name.starts_with("index") {
                    let parsed = super::parser::MarkdownParser::parse_markdown_file(&path)?;
                    markdown_files.push(parsed);
                }
            }
        }

        // Sort the collected files
        self.sort_markdown_files(&mut markdown_files, &sort_config);

        // Generate HTML content
        let mut list_content = String::new();
        for parsed in markdown_files {
            // Generate post list entry using template
            let date = parsed.frontmatter.date.as_deref();
            let relative_url_path = parsed
                .path
                .strip_prefix(&self.input_dir)
                .unwrap_or(&parsed.path)
                .with_extension("");
            let relative_url = relative_url_path.to_string_lossy();

            // Extract first paragraph as excerpt
            let excerpt = if !self.extract_first_paragraph(&parsed.content).is_empty() {
                let first_paragraph = self.extract_first_paragraph(&parsed.content);
                let parser = Parser::new(&first_paragraph);
                let mut excerpt_html = String::new();
                html::push_html(&mut excerpt_html, parser);
                Some(excerpt_html)
            } else {
                None
            };

            // Use the template to render each content item
            let content_item_html = self.template_manager.render_content_item(
                &parsed.title,
                &relative_url,
                date,
                excerpt.as_deref(),
            )?;

            list_content.push_str(&content_item_html);
            list_content.push_str("\n\n");
        }

        // If no list content was found, return empty string
        if list_content.is_empty() {
            Ok("<!-- No posts found -->".to_string())
        } else {
            Ok(list_content)
        }
    }

    pub fn extract_first_paragraph(&self, content: &str) -> String {
        let mut in_code_block = false;
        let mut lines_since_heading = 0;

        for line in content.lines() {
            let trimmed = line.trim();

            // Skip code blocks
            if trimmed.starts_with("```") {
                in_code_block = !in_code_block;
                continue;
            }
            if in_code_block {
                continue;
            }

            // Skip headings and empty lines right after headings
            if trimmed.starts_with('#') {
                lines_since_heading = 0;
                continue;
            }
            if lines_since_heading < 1 {
                lines_since_heading += 1;
                continue;
            }

            // Skip empty lines
            if trimmed.is_empty() {
                continue;
            }

            // Found a paragraph, return it
            return trimmed.to_string();
        }

        String::new()
    }

    fn enhance_semantics(&self, html: &str) -> String {
        let mut enhanced = html.to_string();

        // Wrap paragraphs in semantic sections if they seem like articles
        enhanced = wrap_articles(&enhanced);

        // Add semantic structure to lists
        enhanced = enhance_lists(&enhanced);

        enhanced
    }
}

fn wrap_articles(html: &str) -> String {
    // Simple heuristic: if content has multiple headings, wrap in article tags
    let heading_count = html.matches("<h").count();
    if heading_count > 1 {
        format!("<article>\n{}\n</article>", html)
    } else {
        html.to_string()
    }
}

fn enhance_lists(html: &str) -> String {
    // Convert plain lists to more semantic versions when appropriate
    html.replace("<ul>", "<ul class=\"content-list\">")
        .replace("<ol>", "<ol class=\"numbered-list\">")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::content::parser::{Frontmatter, MarkdownParser};
    use std::fs;
    use std::path::PathBuf;
    use tempfile::tempdir;

    fn create_test_markdown_file(
        temp_dir: &tempfile::TempDir,
        filename: &str,
        frontmatter: &str,
        content: &str,
    ) -> std::path::PathBuf {
        let file_path = temp_dir.path().join(filename);
        let full_content = format!("{}\n\n{}", frontmatter, content);
        fs::write(&file_path, full_content).unwrap();
        file_path
    }

    fn create_test_html_renderer() -> HtmlRenderer {
        use crate::presentation::templates::TemplateManager;
        let temp_dir = tempdir().unwrap();
        let template_manager = TemplateManager::new(temp_dir.path()).unwrap();
        HtmlRenderer::new(temp_dir.path(), template_manager)
    }

    #[test]
    fn test_sort_config_from_frontmatter() {
        let frontmatter = Frontmatter {
            sort_by: Some("title".to_string()),
            sort_order: Some("desc".to_string()),
            ..Default::default()
        };

        let config = SortConfig::from_frontmatter(&frontmatter);
        assert_eq!(config.field, "title");
        assert_eq!(config.order, "desc");
    }

    #[test]
    fn test_sort_config_defaults() {
        let frontmatter = Frontmatter::default();

        let config = SortConfig::from_frontmatter(&frontmatter);
        assert_eq!(config.field, "date");
        assert_eq!(config.order, "desc");
    }

    #[test]
    fn test_sort_config_field_validation() {
        assert!(SortConfig::is_valid_field("date"));
        assert!(SortConfig::is_valid_field("title"));
        assert!(SortConfig::is_valid_field("filename"));
        assert!(!SortConfig::is_valid_field("invalid"));
        assert!(!SortConfig::is_valid_field("author"));
    }

    #[test]
    fn test_sort_config_order_validation() {
        assert!(SortConfig::is_valid_order("asc"));
        assert!(SortConfig::is_valid_order("desc"));
        assert!(!SortConfig::is_valid_order("ascending"));
        assert!(!SortConfig::is_valid_order("invalid"));
    }

    #[test]
    fn test_date_parsing() {
        let renderer = create_test_html_renderer();

        // Test ISO format
        assert!(renderer.parse_date("2024-01-15").is_some());

        // Test other formats
        assert!(renderer.parse_date("January 15, 2024").is_some());
        assert!(renderer.parse_date("Jan 15, 2024").is_some());
        assert!(renderer.parse_date("15/01/2024").is_some());
        assert!(renderer.parse_date("01/15/2024").is_some());

        // Test invalid format
        assert!(renderer.parse_date("invalid date").is_none());
    }

    #[test]
    fn test_sort_by_date_ascending() {
        let renderer = create_test_html_renderer();

        let file1 = MarkdownFile {
            path: PathBuf::from("file1.md"),
            content: "Content 1".to_string(),
            title: "File 1".to_string(),
            frontmatter: Frontmatter {
                date: Some("2024-01-10".to_string()),
                ..Default::default()
            },
        };

        let file2 = MarkdownFile {
            path: PathBuf::from("file2.md"),
            content: "Content 2".to_string(),
            title: "File 2".to_string(),
            frontmatter: Frontmatter {
                date: Some("2024-01-15".to_string()),
                ..Default::default()
            },
        };

        let mut files = vec![file2, file1];
        let config = SortConfig {
            field: "date".to_string(),
            order: "asc".to_string(),
        };

        renderer.sort_markdown_files(&mut files, &config);

        assert_eq!(files[0].frontmatter.date, Some("2024-01-10".to_string()));
        assert_eq!(files[1].frontmatter.date, Some("2024-01-15".to_string()));
    }

    #[test]
    fn test_sort_by_date_descending() {
        let renderer = create_test_html_renderer();

        let file1 = MarkdownFile {
            path: PathBuf::from("file1.md"),
            content: "Content 1".to_string(),
            title: "File 1".to_string(),
            frontmatter: Frontmatter {
                date: Some("2024-01-10".to_string()),
                ..Default::default()
            },
        };

        let file2 = MarkdownFile {
            path: PathBuf::from("file2.md"),
            content: "Content 2".to_string(),
            title: "File 2".to_string(),
            frontmatter: Frontmatter {
                date: Some("2024-01-15".to_string()),
                ..Default::default()
            },
        };

        let mut files = vec![file1.clone(), file2.clone()];
        let config = SortConfig {
            field: "date".to_string(),
            order: "desc".to_string(),
        };

        renderer.sort_markdown_files(&mut files, &config);

        assert_eq!(files[0].frontmatter.date, Some("2024-01-15".to_string()));
        assert_eq!(files[1].frontmatter.date, Some("2024-01-10".to_string()));
    }

    #[test]
    fn test_sort_by_title() {
        let renderer = create_test_html_renderer();

        let file1 = MarkdownFile {
            path: PathBuf::from("z_file.md"),
            content: "Content 1".to_string(),
            title: "Zebra".to_string(),
            frontmatter: Frontmatter::default(),
        };

        let file2 = MarkdownFile {
            path: PathBuf::from("a_file.md"),
            content: "Content 2".to_string(),
            title: "Apple".to_string(),
            frontmatter: Frontmatter::default(),
        };

        let mut files = vec![file1, file2];
        let config = SortConfig {
            field: "title".to_string(),
            order: "asc".to_string(),
        };

        renderer.sort_markdown_files(&mut files, &config);

        assert_eq!(files[0].title, "Apple");
        assert_eq!(files[1].title, "Zebra");
    }

    #[test]
    fn test_sort_by_filename() {
        let renderer = create_test_html_renderer();

        let file1 = MarkdownFile {
            path: PathBuf::from("z_file.md"),
            content: "Content 1".to_string(),
            title: "Zebra".to_string(),
            frontmatter: Frontmatter::default(),
        };

        let file2 = MarkdownFile {
            path: PathBuf::from("a_file.md"),
            content: "Content 2".to_string(),
            title: "Apple".to_string(),
            frontmatter: Frontmatter::default(),
        };

        let mut files = vec![file1, file2];
        let config = SortConfig {
            field: "filename".to_string(),
            order: "asc".to_string(),
        };

        renderer.sort_markdown_files(&mut files, &config);

        assert_eq!(
            files[0].path.file_name().unwrap().to_str().unwrap(),
            "a_file.md"
        );
        assert_eq!(
            files[1].path.file_name().unwrap().to_str().unwrap(),
            "z_file.md"
        );
    }

    #[test]
    fn test_sort_with_missing_dates() {
        let renderer = create_test_html_renderer();

        let file_with_date = MarkdownFile {
            path: PathBuf::from("with_date.md"),
            content: "Content 1".to_string(),
            title: "With Date".to_string(),
            frontmatter: Frontmatter {
                date: Some("2024-01-15".to_string()),
                ..Default::default()
            },
        };

        let file_without_date = MarkdownFile {
            path: PathBuf::from("without_date.md"),
            content: "Content 2".to_string(),
            title: "Without Date".to_string(),
            frontmatter: Frontmatter::default(),
        };

        let mut files = vec![file_without_date, file_with_date];
        let config = SortConfig {
            field: "date".to_string(),
            order: "asc".to_string(),
        };

        renderer.sort_markdown_files(&mut files, &config);

        // Files with dates should come before files without dates
        assert_eq!(files[0].frontmatter.date, Some("2024-01-15".to_string()));
        assert_eq!(files[1].frontmatter.date, None);
    }

    #[test]
    fn test_sort_with_invalid_dates() {
        let renderer = create_test_html_renderer();

        let file_with_valid_date = MarkdownFile {
            path: PathBuf::from("valid_date.md"),
            content: "Content 1".to_string(),
            title: "Valid Date".to_string(),
            frontmatter: Frontmatter {
                date: Some("2024-01-15".to_string()),
                ..Default::default()
            },
        };

        let file_with_invalid_date = MarkdownFile {
            path: PathBuf::from("invalid_date.md"),
            content: "Content 2".to_string(),
            title: "Invalid Date".to_string(),
            frontmatter: Frontmatter {
                date: Some("not a date".to_string()),
                ..Default::default()
            },
        };

        let mut files = vec![file_with_invalid_date, file_with_valid_date];
        let config = SortConfig {
            field: "date".to_string(),
            order: "asc".to_string(),
        };

        renderer.sort_markdown_files(&mut files, &config);

        // Files with valid dates should come before files with invalid dates
        assert_eq!(files[0].frontmatter.date, Some("2024-01-15".to_string()));
        assert_eq!(files[1].frontmatter.date, Some("not a date".to_string()));
    }

    #[test]
    fn test_compare_by_filename_fallback() {
        let renderer = create_test_html_renderer();

        let file1 = MarkdownFile {
            path: PathBuf::from("z_file.md"),
            content: "Content 1".to_string(),
            title: "Zebra".to_string(),
            frontmatter: Frontmatter::default(),
        };

        let file2 = MarkdownFile {
            path: PathBuf::from("a_file.md"),
            content: "Content 2".to_string(),
            title: "Apple".to_string(),
            frontmatter: Frontmatter::default(),
        };

        let comparison = renderer.compare_by_filename(&file1, &file2);
        assert_eq!(comparison, Ordering::Greater);
    }

    #[test]
    fn test_generate_blog_list_with_sorting() -> Result<()> {
        let temp_dir = tempdir()?;
        let template_manager = TemplateManager::new(temp_dir.path())?;
        let renderer = HtmlRenderer::new(temp_dir.path(), template_manager);

        // Create test files with different dates
        let frontmatter1 = r#"+++
title = "First Post"
date = "2024-01-10"
+++"#;

        let frontmatter2 = r#"+++
title = "Second Post" 
date = "2024-01-15"
+++"#;

        let frontmatter3 = r#"+++
title = "Third Post"
date = "2024-01-05"
+++"#;

        create_test_markdown_file(
            &temp_dir,
            "post1.md",
            frontmatter1,
            "# First Post\nContent here",
        );
        create_test_markdown_file(
            &temp_dir,
            "post2.md",
            frontmatter2,
            "# Second Post\nContent here",
        );
        create_test_markdown_file(
            &temp_dir,
            "post3.md",
            frontmatter3,
            "# Third Post\nContent here",
        );

        // Create list page with sorting configuration
        let list_frontmatter = r#"+++
list = true
title = "Blog"
sort_by = "date"
sort_order = "desc"
+++"#;

        let list_file =
            create_test_markdown_file(&temp_dir, "index.md", list_frontmatter, "# Blog\nWelcome");
        let parsed_list = MarkdownParser::parse_markdown_file(&list_file)?;

        let mut list_pages = HashMap::new();
        list_pages.insert(PathBuf::from(""), &parsed_list);

        // Generate blog list
        let result = renderer.generate_blog_list_content(Path::new(""), &list_pages)?;

        // Verify that posts are in correct order (newest first)
        assert!(result.contains("Second Post"));
        assert!(result.contains("First Post"));
        assert!(result.contains("Third Post"));

        // Check that the order in the result matches expected (newest to oldest)
        let second_index = result.find("Second Post").unwrap_or(0);
        let first_index = result.find("First Post").unwrap_or(0);
        let third_index = result.find("Third Post").unwrap_or(0);

        assert!(second_index < first_index); // Second Post should come before First Post
        assert!(first_index < third_index); // First Post should come before Third Post

        Ok(())
    }
}