Restructure into feature folders with code-behind and scoped CSS

This commit is contained in:
tleininger committed 2026-09-21 22:01:21 +02:00
1 parent 5ba523d34d
commit 9d1f8fe0d4
25 files changed
+250 -203

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
namespace Elternbeirat.Web.Services;
/// <summary>
/// A single calendar entry (parents' evening, meeting, deadline). Read from
/// <c>Content/events.yml</c> at startup. All display text is German because it
/// is visitor-facing content.
/// </summary>
public sealed class Event
{
/// <summary>Short title shown in the list and the calendar.</summary>
public required string Title { get; init; }
/// <summary>
/// When the entry starts. A date-only entry (no time) is treated as an
/// all-day event; see <see cref="HasTime"/>.
/// </summary>
public required DateTime Start { get; init; }
/// <summary>
/// True when <see cref="Start"/> carries a wall-clock time, false for an
/// all-day entry. Drives both the list formatting and the ICS export.
/// </summary>
public required bool HasTime { get; init; }
/// <summary>Optional end, for multi-hour or multi-day entries.</summary>
public DateTime? End { get; init; }
/// <summary>Optional location, e.g. "Aula" or "Mensa".</summary>
public string? Location { get; init; }
/// <summary>Optional free-text note shown below the entry.</summary>
public string? Note { get; init; }
}
@@ -0,0 +1,57 @@
@page "/termine"
@inject EventService EventService
<PageTitle>Termine</PageTitle>
<h1>Termine</h1>
<p class="intro">
Alle Termine des Elternbeirats auf einen Blick. Sie können den Kalender auch
<a href="/termine.ics">abonnieren</a> und in Ihrer Kalender-App automatisch
aktuell halten.
</p>
<h2>Kommende Termine</h2>
@if (EventService.Upcoming.Count == 0)
{
<p>Zurzeit sind keine Termine geplant.</p>
}
else
{
<ul class="event-list">
@foreach (var ev in EventService.Upcoming)
{
<li>
<time datetime="@ev.Start.ToString("s")">@Format(ev)</time>
<span class="event-title">@ev.Title</span>
@if (!string.IsNullOrWhiteSpace(ev.Location))
{
<span class="event-location">@ev.Location</span>
}
@if (!string.IsNullOrWhiteSpace(ev.Note))
{
<p class="event-note">@ev.Note</p>
}
</li>
}
</ul>
}
@if (EventService.Past.Count > 0)
{
<h2>Vergangene Termine</h2>
<ul class="event-list event-list-past">
@foreach (var ev in EventService.Past)
{
<li>
<time datetime="@ev.Start.ToString("s")">@Format(ev)</time>
<span class="event-title">@ev.Title</span>
@if (!string.IsNullOrWhiteSpace(ev.Location))
{
<span class="event-location">@ev.Location</span>
}
</li>
}
</ul>
}
@@ -0,0 +1,37 @@
using System.Globalization;
using Elternbeirat.Web.Services;
namespace Elternbeirat.Web.Features.Events;
public partial class EventList
{
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
// Formats the entry's date range for display: a single day, a date with a
// time, or a span across days.
private static string Format(Event ev)
{
var start = ev.HasTime
? ev.Start.ToString("dddd, d. MMMM yyyy, HH:mm", German) + " Uhr"
: ev.Start.ToString("dddd, d. MMMM yyyy", German);
if (ev.End is not { } end)
{
return start;
}
// Same day: append just the end time. Different days: append the full
// end date.
if (end.Date == ev.Start.Date)
{
return ev.HasTime
? start + "–" + end.ToString("HH:mm", German) + " Uhr"
: start;
}
var endText = ev.HasTime
? end.ToString("d. MMMM yyyy, HH:mm", German) + " Uhr"
: end.ToString("d. MMMM yyyy", German);
return start + " – " + endText;
}
}
@@ -0,0 +1,42 @@
.event-list {
list-style: none;
padding: 0;
}
.event-list li {
padding: 0.75rem 0;
border-bottom: 1px solid #eee;
}
.event-list time {
display: block;
color: #777;
font-size: 0.85rem;
}
.event-title {
font-size: 1.1rem;
font-weight: 600;
}
.event-location::before {
content: " · ";
color: #777;
}
.event-location {
color: #555;
}
.event-note {
margin: 0.25rem 0 0;
color: #444;
}
.event-list-past {
color: #777;
}
.event-list-past .event-title {
font-weight: 400;
}
@@ -0,0 +1,137 @@
using System.Globalization;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
namespace Elternbeirat.Web.Services;
/// <summary>
/// Reads the calendar entries from <c>Content/events.yml</c> 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 EventService
{
private readonly IReadOnlyList<Event> _events;
/// <summary>
/// Reads and parses <c>Content/events.yml</c> below the application root.
/// A missing file yields an empty list rather than an error.
/// </summary>
public EventService(IWebHostEnvironment environment)
{
var path = Path.Combine(environment.ContentRootPath, "Content", "events.yml");
_events = File.Exists(path)
? Parse(File.ReadAllText(path))
: [];
}
/// <summary>
/// Entries that start today or later, earliest first — the upcoming section.
/// "Today" is compared by date, so an entry earlier today still counts as
/// upcoming.
/// </summary>
public IReadOnlyList<Event> Upcoming =>
_events
.Where(e => DateOnly.FromDateTime(e.Start) >= DateOnly.FromDateTime(DateTime.Today))
.OrderBy(e => e.Start)
.ToList();
/// <summary>
/// Entries that already passed, most recent first — the past section shown
/// below the upcoming ones.
/// </summary>
public IReadOnlyList<Event> Past =>
_events
.Where(e => DateOnly.FromDateTime(e.Start) < DateOnly.FromDateTime(DateTime.Today))
.OrderByDescending(e => e.Start)
.ToList();
/// <summary>All entries in chronological order, for the ICS export.</summary>
public IReadOnlyList<Event> All =>
_events.OrderBy(e => e.Start).ToList();
private static List<Event> Parse(string yaml)
{
// Keys are lowercase single words (title, start, ...), which the camel
// case convention maps onto the PascalCase properties.
var deserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.IgnoreUnmatchedProperties()
.Build();
var raw = deserializer.Deserialize<List<EventEntry>?>(yaml) ?? [];
return raw
.Where(entry => entry.Title is not null && entry.Start is not null)
.Select(ToEvent)
.OfType<Event>()
.ToList();
}
private static Event? ToEvent(EventEntry entry)
{
if (!TryParseWhen(entry.Start!, out var start, out var hasTime))
{
// A malformed date drops the entry rather than crashing startup.
return null;
}
DateTime? end = null;
if (entry.End is not null && TryParseWhen(entry.End, out var parsedEnd, out _))
{
end = parsedEnd;
}
return new Event
{
Title = entry.Title!,
Start = start,
HasTime = hasTime,
End = end,
Location = entry.Location,
Note = entry.Note,
};
}
/// <summary>
/// Parses a value that is either a date (<c>2026-03-15</c>) or a date with a
/// time (<c>2026-03-15 19:30</c>). Sets <paramref name="hasTime"/> so the
/// caller knows whether to treat the entry as all-day.
/// </summary>
private static bool TryParseWhen(string value, out DateTime when, out bool hasTime)
{
var trimmed = value.Trim();
if (DateOnly.TryParseExact(trimmed, "yyyy-MM-dd",
CultureInfo.InvariantCulture, DateTimeStyles.None, out var dateOnly))
{
when = dateOnly.ToDateTime(TimeOnly.MinValue);
hasTime = false;
return true;
}
string[] formats = ["yyyy-MM-dd HH:mm", "yyyy-MM-dd'T'HH:mm"];
if (DateTime.TryParseExact(trimmed, formats,
CultureInfo.InvariantCulture, DateTimeStyles.None, out when))
{
hasTime = true;
return true;
}
when = default;
hasTime = false;
return false;
}
/// <summary>
/// Raw shape of one YAML entry, before validation. String-typed on purpose so
/// we control date parsing and can distinguish date-only from date-and-time.
/// </summary>
private sealed class EventEntry
{
public string? Title { get; set; }
public string? Start { get; set; }
public string? End { get; set; }
public string? Location { get; set; }
public string? Note { get; set; }
}
}
@@ -0,0 +1,105 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Elternbeirat.Web.Services;
/// <summary>
/// Builds an iCalendar (RFC 5545) document from the events so visitors can
/// subscribe to the calendar in their own app. Times are written as local
/// wall-clock times without a time zone, which is what a school calendar needs:
/// "19:30" should read as 19:30 everywhere.
/// </summary>
public static class IcsCalendar
{
private const string ProductId = "-//Elternbeirat IGMH//Termine//DE";
/// <summary>
/// Serialises the given entries into a single VCALENDAR document.
/// </summary>
public static string Build(IReadOnlyList<Event> events)
{
var sb = new StringBuilder();
AppendLine(sb, "BEGIN:VCALENDAR");
AppendLine(sb, "VERSION:2.0");
AppendLine(sb, $"PRODID:{ProductId}");
AppendLine(sb, "CALSCALE:GREGORIAN");
AppendLine(sb, "METHOD:PUBLISH");
AppendLine(sb, "X-WR-CALNAME:Elternbeirat IGMH");
foreach (var ev in events)
{
AppendEvent(sb, ev);
}
AppendLine(sb, "END:VCALENDAR");
return sb.ToString();
}
private static void AppendEvent(StringBuilder sb, Event ev)
{
AppendLine(sb, "BEGIN:VEVENT");
AppendLine(sb, $"UID:{Uid(ev)}");
// No live timestamp: a stable DTSTAMP keeps the feed byte-identical
// between requests, so caches and clients do not see spurious changes.
AppendLine(sb, "DTSTAMP:20000101T000000Z");
if (ev.HasTime)
{
AppendLine(sb, $"DTSTART:{Local(ev.Start)}");
if (ev.End is { } end)
{
AppendLine(sb, $"DTEND:{Local(end)}");
}
}
else
{
AppendLine(sb, $"DTSTART;VALUE=DATE:{Date(ev.Start)}");
// For an all-day event DTEND is exclusive: add one day so a single
// day shows as one day, and a range covers its last day.
var end = ev.End ?? ev.Start;
AppendLine(sb, $"DTEND;VALUE=DATE:{Date(end.AddDays(1))}");
}
AppendLine(sb, $"SUMMARY:{Escape(ev.Title)}");
if (!string.IsNullOrWhiteSpace(ev.Location))
{
AppendLine(sb, $"LOCATION:{Escape(ev.Location)}");
}
if (!string.IsNullOrWhiteSpace(ev.Note))
{
AppendLine(sb, $"DESCRIPTION:{Escape(ev.Note)}");
}
AppendLine(sb, "END:VEVENT");
}
/// <summary>
/// A UID that stays the same as long as the entry's title and start do, so a
/// re-subscribe updates the event instead of creating a duplicate.
/// </summary>
private static string Uid(Event ev)
{
var seed = $"{ev.Title}|{ev.Start:O}";
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(seed));
return $"{Convert.ToHexString(hash)[..16].ToLowerInvariant()}@elternbeirat-igmh";
}
private static string Local(DateTime value) =>
value.ToString("yyyyMMdd'T'HHmmss", CultureInfo.InvariantCulture);
private static string Date(DateTime value) =>
value.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
/// <summary>Escapes the characters that are special in an ICS text value.</summary>
private static string Escape(string value) => value
.Replace("\\", "\\\\")
.Replace(";", "\\;")
.Replace(",", "\\,")
.Replace("\r\n", "\\n")
.Replace("\n", "\\n");
// ICS lines are terminated with CRLF regardless of platform.
private static void AppendLine(StringBuilder sb, string line) =>
sb.Append(line).Append("\r\n");
}
+35
View File
@@ -0,0 +1,35 @@
@page "/"
@inject PostService PostService
<PageTitle>Elternbeirat der IGMH</PageTitle>
<h1>Elternbeirat der IGMH</h1>
<p class="intro">
Willkommen beim Elternbeirat der IGMH. Hier finden Sie aktuelle Informationen,
Antworten auf häufige Fragen und Unterlagen rund um die Elternarbeit.
</p>
<section class="home-news">
<h2>Aktuelle Beiträge</h2>
@if (_latest.Count == 0)
{
<p>Zurzeit gibt es keine Beiträge.</p>
}
else
{
<ul class="post-list">
@foreach (var post in _latest)
{
<li>
<a href="@($"/beitraege/{post.Slug}")">@post.Title</a>
<time datetime="@post.Date.ToString("yyyy-MM-dd")">
@post.Date.ToString("d. MMMM yyyy", German)
</time>
</li>
}
</ul>
<p><a href="/beitraege">Alle Beiträge &rarr;</a></p>
}
</section>
@@ -0,0 +1,17 @@
using System.Globalization;
using Elternbeirat.Web.Services;
namespace Elternbeirat.Web.Features.Home;
public partial class Home
{
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
private IReadOnlyList<Post> _latest = [];
protected override void OnInitialized()
{
// Show the three most recent posts as a teaser on the home page.
_latest = [.. PostService.All.Take(3)];
}
}
@@ -0,0 +1,29 @@
.intro {
font-size: 1.1rem;
color: #444;
}
.home-news {
margin-top: 2rem;
}
.post-list {
list-style: none;
padding: 0;
}
.post-list li {
padding: 0.75rem 0;
border-bottom: 1px solid #eee;
}
.post-list a {
font-size: 1.1rem;
text-decoration: none;
}
.post-list time {
display: block;
color: #777;
font-size: 0.85rem;
}
@@ -0,0 +1,14 @@
@page "/{Slug}"
@inject PageService PageService
@if (_page is null)
{
<PageTitle>Nicht gefunden</PageTitle>
}
else
{
<PageTitle>@_page.Title</PageTitle>
<article>
@((MarkupString)_page.ContentHtml)
</article>
}
@@ -0,0 +1,28 @@
using Elternbeirat.Web.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Http;
namespace Elternbeirat.Web.Features.Pages;
public partial class ContentPage
{
[Parameter]
public string Slug { get; set; } = "";
private Page? _page;
protected override void OnParametersSet()
{
_page = PageService.Find(Slug);
// Unknown slug -> 404, so UseStatusCodePagesWithReExecute serves the
// /not-found page instead of an empty 200 response.
if (_page is null && HttpContext is not null)
{
HttpContext.Response.StatusCode = StatusCodes.Status404NotFound;
}
}
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
}
+25
View File
@@ -0,0 +1,25 @@
namespace Elternbeirat.Web.Services;
/// <summary>
/// A static content page, read from a Markdown file in <c>Content/pages/</c>.
/// The file name (without extension) is the slug.
/// </summary>
public sealed class Page
{
/// <summary>
/// URL identifier of the page, taken from the file name without umlauts
/// (e.g. <c>vorstandsteam</c>). It appears in the route <c>/{slug}</c>.
/// </summary>
public required string Slug { get; init; }
/// <summary>
/// Display title from the YAML front matter (<c>titel:</c>). Falls back to
/// the slug when no title is set.
/// </summary>
public required string Title { get; init; }
/// <summary>
/// The page body rendered from Markdown to HTML (front matter excluded).
/// </summary>
public required string ContentHtml { get; init; }
}
@@ -0,0 +1,57 @@
using Markdig;
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 = FrontMatter.Read("title", document, source) ?? slug;
var html = Markdown.ToHtml(source, pipeline);
return new Page { Slug = slug, Title = title, ContentHtml = html };
}
}
+33
View File
@@ -0,0 +1,33 @@
namespace Elternbeirat.Web.Services;
/// <summary>
/// A news post, read from a Markdown file in <c>Content/posts/</c>. Unlike a
/// <see cref="Page"/>, a post has a date and
/// is shown in a chronological list. The file name (without extension) is the
/// slug.
/// </summary>
public sealed class Post
{
/// <summary>
/// URL identifier of the post, taken from the file name without umlauts.
/// It appears in the route <c>/beitraege/{slug}</c>.
/// </summary>
public required string Slug { get; init; }
/// <summary>
/// Display title from the YAML front matter (<c>titel:</c>). Falls back to
/// the slug when no title is set.
/// </summary>
public required string Title { get; init; }
/// <summary>
/// Publication date from the front matter (<c>datum:</c>). Used to sort the
/// list newest first.
/// </summary>
public required DateOnly Date { get; init; }
/// <summary>
/// The post body rendered from Markdown to HTML (front matter excluded).
/// </summary>
public required string ContentHtml { get; init; }
}
@@ -0,0 +1,20 @@
@page "/beitraege/{Slug}"
@inject PostService PostService
@if (_post is null)
{
<PageTitle>Nicht gefunden</PageTitle>
}
else
{
<PageTitle>@_post.Title</PageTitle>
<article>
<p class="post-meta">
<a href="/beitraege">&larr; Alle Beiträge</a>
<time datetime="@_post.Date.ToString("yyyy-MM-dd")">
@_post.Date.ToString("d. MMMM yyyy", German)
</time>
</p>
@((MarkupString)_post.ContentHtml)
</article>
}
@@ -0,0 +1,31 @@
using System.Globalization;
using Elternbeirat.Web.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Http;
namespace Elternbeirat.Web.Features.Posts;
public partial class PostDetail
{
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
[Parameter]
public string Slug { get; set; } = "";
private Post? _post;
protected override void OnParametersSet()
{
_post = PostService.Find(Slug);
// Unknown slug -> 404, so UseStatusCodePagesWithReExecute serves the
// /not-found page instead of an empty 200 response.
if (_post is null && HttpContext is not null)
{
HttpContext.Response.StatusCode = StatusCodes.Status404NotFound;
}
}
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
}
@@ -0,0 +1,13 @@
.post-meta {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 1rem;
margin-bottom: 1rem;
}
.post-meta time {
display: block;
color: #777;
font-size: 0.85rem;
}
@@ -0,0 +1,25 @@
@page "/beitraege"
@inject PostService PostService
<PageTitle>Beiträge</PageTitle>
<h1>Beiträge</h1>
@if (PostService.All.Count == 0)
{
<p>Zurzeit gibt es keine Beiträge.</p>
}
else
{
<ul class="post-list">
@foreach (var post in PostService.All)
{
<li>
<a href="@($"/beitraege/{post.Slug}")">@post.Title</a>
<time datetime="@post.Date.ToString("yyyy-MM-dd")">
@post.Date.ToString("d. MMMM yyyy", German)
</time>
</li>
}
</ul>
}
@@ -0,0 +1,8 @@
using System.Globalization;
namespace Elternbeirat.Web.Features.Posts;
public partial class PostList
{
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
}
@@ -0,0 +1,20 @@
.post-list {
list-style: none;
padding: 0;
}
.post-list li {
padding: 0.75rem 0;
border-bottom: 1px solid #eee;
}
.post-list a {
font-size: 1.1rem;
text-decoration: none;
}
.post-list time {
display: block;
color: #777;
font-size: 0.85rem;
}
@@ -0,0 +1,86 @@
using System.Globalization;
using Markdig;
namespace Elternbeirat.Web.Services;
/// <summary>
/// Reads the news posts from <c>Content/posts/*.md</c>, renders them to HTML
/// once at startup and keeps them in memory, sorted newest first. Registered as
/// a singleton because the content lives in the image and does not change at
/// runtime.
/// </summary>
public sealed class PostService
{
private readonly IReadOnlyList<Post> _posts;
private readonly IReadOnlyDictionary<string, Post> _postsBySlug;
/// <summary>
/// Reads every Markdown post from the <c>Content/posts</c> directory
/// below the application root and caches it.
/// </summary>
public PostService(IWebHostEnvironment environment)
{
var pipeline = new MarkdownPipelineBuilder()
.UseYamlFrontMatter()
.Build();
var directory = Path.Combine(environment.ContentRootPath, "Content", "posts");
var posts = new List<Post>();
if (Directory.Exists(directory))
{
foreach (var path in Directory.EnumerateFiles(directory, "*.md"))
{
posts.Add(Read(path, pipeline));
}
}
// Newest first for the list; a stable slug order breaks date ties.
posts.Sort((a, b) =>
{
var byDate = b.Date.CompareTo(a.Date);
return byDate != 0 ? byDate : string.CompareOrdinal(a.Slug, b.Slug);
});
_posts = posts;
_postsBySlug = posts.ToDictionary(p => p.Slug, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// All posts, newest first. Used for the overview list.
/// </summary>
public IReadOnlyList<Post> All => _posts;
/// <summary>
/// Returns the post for the given slug, or <c>null</c> if there is none.
/// The lookup is case-insensitive.
/// </summary>
public Post? Find(string slug) =>
_postsBySlug.GetValueOrDefault(slug);
private static Post Read(string path, MarkdownPipeline pipeline)
{
var slug = Path.GetFileNameWithoutExtension(path);
var source = File.ReadAllText(path);
var document = Markdown.Parse(source, pipeline);
var title = FrontMatter.Read("title", document, source) ?? slug;
var date = ParseDate(FrontMatter.Read("date", document, source));
var html = Markdown.ToHtml(source, pipeline);
return new Post { Slug = slug, Title = title, Date = date, ContentHtml = html };
}
/// <summary>
/// Parses the <c>datum:</c> value as an ISO date (yyyy-MM-dd). Falls back to
/// <see cref="DateOnly.MinValue"/> when the value is missing or malformed,
/// so a single bad file does not crash startup — it just sorts last.
/// </summary>
private static DateOnly ParseDate(string? value)
{
return DateOnly.TryParse(value, CultureInfo.InvariantCulture,
DateTimeStyles.None, out var date)
? date
: DateOnly.MinValue;
}
}