87 lines
2.9 KiB
C#
87 lines
2.9 KiB
C#
using Markdig;
|
|
using Markdig.Extensions.Yaml;
|
|
using Markdig.Syntax;
|
|
|
|
namespace Elternbeirat.Web.Services;
|
|
|
|
/// <summary>
|
|
/// Reads the static content pages from <c>Content/pages/*.md</c>, renders them
|
|
/// to HTML once at startup and keeps them in memory. Registered as a singleton
|
|
/// because the content lives in the image and does not change at runtime.
|
|
/// </summary>
|
|
public sealed class PageService
|
|
{
|
|
private readonly IReadOnlyDictionary<string, Page> _pagesBySlug;
|
|
|
|
/// <summary>
|
|
/// Reads every Markdown page from the <c>Content/pages</c> directory below
|
|
/// the application root and caches it.
|
|
/// </summary>
|
|
public PageService(IWebHostEnvironment environment)
|
|
{
|
|
var pipeline = new MarkdownPipelineBuilder()
|
|
.UseYamlFrontMatter()
|
|
.Build();
|
|
|
|
var directory = Path.Combine(environment.ContentRootPath, "Content", "pages");
|
|
var pages = new Dictionary<string, Page>(StringComparer.OrdinalIgnoreCase);
|
|
|
|
if (Directory.Exists(directory))
|
|
{
|
|
foreach (var path in Directory.EnumerateFiles(directory, "*.md"))
|
|
{
|
|
var page = Read(path, pipeline);
|
|
pages[page.Slug] = page;
|
|
}
|
|
}
|
|
|
|
_pagesBySlug = pages;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns the page for the given slug, or <c>null</c> if there is none.
|
|
/// The lookup is case-insensitive.
|
|
/// </summary>
|
|
public Page? Find(string slug) =>
|
|
_pagesBySlug.GetValueOrDefault(slug);
|
|
|
|
private static Page Read(string path, MarkdownPipeline pipeline)
|
|
{
|
|
var slug = Path.GetFileNameWithoutExtension(path);
|
|
var source = File.ReadAllText(path);
|
|
|
|
var document = Markdown.Parse(source, pipeline);
|
|
var title = ReadTitle(document, source) ?? slug;
|
|
var html = Markdown.ToHtml(source, pipeline);
|
|
|
|
return new Page { Slug = slug, Title = title, ContentHtml = html };
|
|
}
|
|
|
|
/// <summary>
|
|
/// Pulls the <c>titel:</c> value out of the YAML front matter. Kept
|
|
/// deliberately simple (a single <c>key: value</c> line) — YamlDotNet will
|
|
/// take over once we need structured metadata. The key stays German because
|
|
/// the Markdown files are edited by German-speaking editors.
|
|
/// </summary>
|
|
private static string? ReadTitle(MarkdownDocument document, string source)
|
|
{
|
|
var block = document.Descendants<YamlFrontMatterBlock>().FirstOrDefault();
|
|
if (block is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var frontMatter = source.Substring(block.Span.Start, block.Span.Length);
|
|
foreach (var line in frontMatter.Split('\n'))
|
|
{
|
|
var trimmed = line.Trim();
|
|
if (trimmed.StartsWith("titel:", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return trimmed["titel:".Length..].Trim().Trim('"');
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|