Initial commit
Deploy / validate-dispatch (push) Successful in 43s
Deploy / scheduled-rebuild-dev (push) Skipped
Deploy / scheduled-rebuild-master (push) Skipped
Deploy / rollback-dev (push) Skipped
Deploy / rollback-master (push) Skipped
Deploy / changes (push) Successful in 13s
Deploy / secret-scan (push) Successful in 9s
Deploy / app-quality (push) Successful in 11m21s
Deploy / security-deps (push) Successful in 14s
Deploy / context (push) Failing after 1s
Deploy / app-image (push) Skipped
Deploy / deploy-dev (push) Skipped
Deploy / deploy-master (push) Skipped

This commit is contained in:
Per Hoener
2026-09-18 23:37:19 +02:00
commit 0d45331f5c
135 changed files with 20651 additions and 0 deletions
+82
View File
@@ -0,0 +1,82 @@
import { describe, it, expect } from "vitest";
import { getEffectiveEventEnd, formatEventDateRange } from "../utils/eventFormat";
import type { CalendarEvent } from "../types";
function makeEvent(overrides: Partial<CalendarEvent> = {}): CalendarEvent {
return {
id: "1",
title: "Test Event",
description: null,
location: null,
start: "2025-06-15T14:00:00+02:00",
end: "2025-06-15T18:00:00+02:00",
allDay: false,
timeZone: "Europe/Berlin",
special: false,
...overrides,
};
}
describe("getEffectiveEventEnd", () => {
it("returns end date unchanged for timed events", () => {
const event = makeEvent();
const end = getEffectiveEventEnd(event);
expect(end).toEqual(new Date("2025-06-15T18:00:00+02:00"));
});
it("sets allDay event end to 23:59:59.999", () => {
const event = makeEvent({
allDay: true,
start: "2025-06-15T00:00:00+02:00",
end: "2025-06-16T00:00:00+02:00",
});
const end = getEffectiveEventEnd(event);
expect(end.getHours()).toBe(23);
expect(end.getMinutes()).toBe(59);
expect(end.getSeconds()).toBe(59);
expect(end.getMilliseconds()).toBe(999);
});
});
describe("formatEventDateRange", () => {
it("formats same-day timed event with time range", () => {
const event = makeEvent();
const result = formatEventDateRange(event);
expect(result).toContain("15. Juni 2025");
expect(result).toContain("14:00");
expect(result).toContain("18:00");
});
it("formats single all-day event without time", () => {
const event = makeEvent({
allDay: true,
start: "2025-06-15T00:00:00+02:00",
end: "2025-06-15T00:00:00+02:00",
});
const result = formatEventDateRange(event);
expect(result).toContain("15. Juni 2025");
expect(result).not.toContain(":");
});
it("formats multi-day all-day event as date range", () => {
const event = makeEvent({
allDay: true,
start: "2025-08-01T00:00:00+02:00",
end: "2025-08-08T00:00:00+02:00",
});
const result = formatEventDateRange(event);
expect(result).toContain("1. August 2025");
expect(result).toContain("7. August 2025");
expect(result).toContain("–");
});
it("formats multi-day timed event with both dates and times", () => {
const event = makeEvent({
start: "2025-08-01T10:00:00+02:00",
end: "2025-08-03T16:00:00+02:00",
});
const result = formatEventDateRange(event);
expect(result).toContain("1. August 2025");
expect(result).toContain("3. August 2025");
});
});
+81
View File
@@ -0,0 +1,81 @@
import { describe, expect, it } from "vitest";
import {
getCalendarGroups,
getSpecialEvents,
} from "../utils/eventsRender";
import type { CalendarEvent } from "../types";
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(10, 0, 0, 0);
const tomorrowEnd = new Date(tomorrow);
tomorrowEnd.setHours(12, 0, 0, 0);
const dayAfterTomorrow = new Date(tomorrow);
dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 1);
dayAfterTomorrow.setHours(17, 0, 0, 0);
const dayAfterTomorrowEnd = new Date(dayAfterTomorrow);
dayAfterTomorrowEnd.setHours(19, 0, 0, 0);
const events: CalendarEvent[] = [
{
id: "1",
title: "Regeltermin",
description: null,
location: "Beispielort",
start: dayAfterTomorrow.toISOString(),
end: dayAfterTomorrowEnd.toISOString(),
allDay: false,
timeZone: "Europe/Berlin",
special: false,
},
{
id: "2",
title: "Sondertermin",
description: null,
location: "Beispielstadt",
start: tomorrow.toISOString(),
end: tomorrowEnd.toISOString(),
allDay: false,
timeZone: "Europe/Berlin",
special: true,
},
];
describe("eventsRender helpers", () => {
it("returns only special events in hero mode", () => {
const specialEvents = getSpecialEvents(events);
expect(specialEvents).toHaveLength(1);
expect(specialEvents[0]?.title).toBe("Sondertermin");
});
it("groups upcoming events for the calendar view", () => {
const groups = getCalendarGroups(events);
expect(groups).toHaveLength(1);
expect(groups[0]?.events).toHaveLength(2);
expect(groups[0]?.events[0]?.title).toBe("Sondertermin");
expect(groups[0]?.events[1]?.title).toBe("Regeltermin");
});
it("groups midnight events in their declared time zone", () => {
const event: CalendarEvent = {
id: "midnight",
title: "Mitternachtstermin",
description: null,
location: null,
start: "2026-03-31T22:30:00.000Z",
end: "2026-04-01T00:30:00.000Z",
allDay: false,
timeZone: "Europe/Berlin",
special: true,
};
const groups = getCalendarGroups([event], new Date("2026-03-01T00:00:00.000Z"));
expect(groups[0]?.label).toBe("April 2026");
});
});
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { serializeJsonLd } from "../utils/jsonLd";
describe("serializeJsonLd", () => {
it("escapes characters that can break out of a script context", () => {
const serialized = serializeJsonLd({
text: '</script><script>alert("x")</script>&',
lineSeparator: "\u2028",
paragraphSeparator: "\u2029",
});
expect(serialized).not.toContain("</script>");
expect(serialized).not.toContain("<script>");
expect(serialized).toContain("\\u003C/script\\u003E");
expect(serialized).toContain("\\u0026");
expect(serialized).toContain("\\u2028");
expect(serialized).toContain("\\u2029");
});
});
+96
View File
@@ -0,0 +1,96 @@
import { describe, expect, it } from "vitest";
import {
addImageManifestMetadata,
buildImageManifestEntries,
} from "../../scripts/optimize-images.mjs";
const sizeSuffixes = ["-sm", "-md", ""];
describe("optimize-images manifest helpers", () => {
it("removes existing manifest entries when the tracked source image was deleted", () => {
const manifest = buildImageManifestEntries({
existingManifest: [
{ name: "old-image", ext: ".jpg", alt: "Existing alt", webp: true, avif: true },
],
outputFileNames: [
"old-image.jpg",
"old-image.webp",
"old-image.avif",
"new-image.jpg",
"new-image.webp",
],
sourceRecords: [{ name: "new-image", ext: ".jpg" }],
sizeSuffixes,
sourceIsComplete: true,
});
expect(manifest).toEqual([
{ name: "new-image", ext: ".jpg", alt: undefined, webp: true, avif: false },
]);
});
it("keeps existing public entries only when sources are unavailable", () => {
const manifest = buildImageManifestEntries({
existingManifest: [{ name: "visible", ext: ".jpg" }],
outputFileNames: ["visible.jpg", "hidden.jpg"],
sourceRecords: [],
sizeSuffixes,
sourceIsComplete: false,
});
expect(manifest.map((item) => item.name)).toEqual(["visible"]);
});
it("discovers public images when no manifest exists yet", () => {
const manifest = buildImageManifestEntries({
existingManifest: [],
outputFileNames: ["first.jpg", "first-sm.jpg", "first.webp", "second.png"],
sourceRecords: [],
sizeSuffixes,
});
expect(manifest).toEqual([
{ name: "first", ext: ".jpg", alt: undefined, webp: true, avif: false },
{ name: "second", ext: ".png", alt: undefined, webp: false, avif: false },
]);
});
it("adds intrinsic dimensions and only the generated responsive variants", () => {
const manifest = addImageManifestMetadata({
entries: [{ name: "camp", ext: ".jpg", alt: "Camp" }],
outputMetadata: new Map([
["camp-sm.jpg", { width: 640, height: 427 }],
["camp-md.jpg", { width: 1280, height: 853 }],
["camp.jpg", { width: 1920, height: 1280 }],
["camp-sm.webp", { width: 640, height: 427 }],
["camp.webp", { width: 1920, height: 1280 }],
]),
sizes: [
{ suffix: "-sm", width: 640, height: 480 },
{ suffix: "-md", width: 1280, height: 960 },
{ suffix: "", width: 1920, height: 1440 },
],
});
expect(manifest).toEqual([{
name: "camp",
ext: ".jpg",
alt: "Camp",
width: 1920,
height: 1280,
variants: {
fallback: [
{ file: "camp-sm.jpg", width: 640, height: 427 },
{ file: "camp-md.jpg", width: 1280, height: 853 },
{ file: "camp.jpg", width: 1920, height: 1280 },
],
webp: [
{ file: "camp-sm.webp", width: 640, height: 427 },
{ file: "camp.webp", width: 1920, height: 1280 },
],
avif: [],
},
}]);
});
});
+75
View File
@@ -0,0 +1,75 @@
import { describe, it, expect } from "vitest";
import {
sortPostsByCreatedDate,
extractPlainText,
createExcerpt,
} from "../utils/postUtils";
import type { PostMetadata } from "../types";
function makePost(overrides: Partial<PostMetadata> = {}): PostMetadata {
return {
id: "test",
title: "Test",
author: "Author",
createdAt: new Date("2025-01-01T00:00:00Z"),
updatedAt: new Date("2025-01-02T00:00:00Z"),
published: true,
...overrides,
};
}
describe("sortPostsByCreatedDate", () => {
it("sorts newest first", () => {
const posts = [
makePost({ id: "old", createdAt: new Date("2024-01-01T00:00:00Z") }),
makePost({ id: "new", createdAt: new Date("2025-12-01T00:00:00Z") }),
makePost({ id: "mid", createdAt: new Date("2025-06-01T00:00:00Z") }),
];
const sorted = sortPostsByCreatedDate(posts);
expect(sorted.map((p) => p.id)).toEqual(["new", "mid", "old"]);
});
it("does not mutate the original array", () => {
const posts = [
makePost({ id: "b", createdAt: new Date("2024-01-01T00:00:00Z") }),
makePost({ id: "a", createdAt: new Date("2025-01-01T00:00:00Z") }),
];
const sorted = sortPostsByCreatedDate(posts);
expect(sorted).not.toBe(posts);
expect(posts[0].id).toBe("b");
});
});
describe("extractPlainText", () => {
it("removes HTML tags", () => {
expect(extractPlainText("<p>Hello <b>world</b></p>")).toBe("Hello world");
});
it("removes markdown headings and bold", () => {
expect(extractPlainText("## Heading\n**bold text**")).toBe("Heading bold text");
});
it("extracts link text", () => {
expect(extractPlainText("[click here](https://example.com)")).toBe("click here");
});
it("normalizes whitespace", () => {
expect(extractPlainText(" too much space ")).toBe("too much space");
});
});
describe("createExcerpt", () => {
it("returns full text when shorter than maxLength", () => {
expect(createExcerpt("short", 100)).toBe("short");
});
it("truncates and adds ellipsis", () => {
const result = createExcerpt("This is a longer text that needs truncation", 20);
expect(result.length).toBeLessThanOrEqual(20);
expect(result).toMatch(/\.\.\.$/);
});
it("returns text unchanged at exact maxLength", () => {
expect(createExcerpt("12345", 5)).toBe("12345");
});
});
+69
View File
@@ -0,0 +1,69 @@
import { buildEventsEtag } from "../../../server/calendar/events-transformer";
import { getEventsService } from "../../../server/calendar/events-service";
import { handleRoute } from "../../../server/calendar/http";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
function parseBoolean(value: string | null): boolean | null {
if (value === null) return false;
const normalized = value.toLowerCase();
if (["true", "1", "on", "yes"].includes(normalized)) return true;
if (["false", "0", "off", "no"].includes(normalized)) return false;
return null;
}
function ifNoneMatchMatches(headerValue: string | null, etag: string): boolean {
if (!headerValue) return false;
return headerValue.split(",").some((candidate) => {
let normalized = candidate.trim();
if (normalized === "*") return true;
if (normalized.startsWith("W/")) normalized = normalized.slice(2).trim();
return normalized.replace(/^"|"$/g, "") === etag;
});
}
export async function GET(request: Request): Promise<Response> {
return handleRoute(request, async (config) => {
const specialValues = new URL(request.url).searchParams.getAll("special");
const special = parseBoolean(specialValues.at(-1) ?? null);
if (special === null) {
return Response.json(
{ detail: "Request validation failed", error: "validation_error" },
{ status: 422 },
);
}
const service = getEventsService();
const events = special ? await service.getSpecialEvents() : await service.getEvents();
const etag = special ? buildEventsEtag(events, true) : service.getCachedEtag() ?? buildEventsEtag(events);
const cacheSeconds = Math.floor(config.calendarCacheDurationMs / 1_000);
const headers = new Headers({
"Cache-Control": `public, max-age=${cacheSeconds}, stale-while-revalidate=300`,
ETag: `"${etag}"`,
});
if (ifNoneMatchMatches(request.headers.get("if-none-match"), etag)) {
return new Response(null, { status: 304, headers });
}
return Response.json(events, { headers });
});
}
export async function OPTIONS(request: Request): Promise<Response> {
return handleRoute(request, (config) => {
const origin = request.headers.get("origin");
const requestedMethod = request.headers.get("access-control-request-method");
if (!origin || !requestedMethod) {
return Response.json({ detail: "Method Not Allowed", error: "http_error" }, { status: 405 });
}
const failures: string[] = [];
if (!config.corsOrigins.includes(origin)) failures.push("origin");
if (requestedMethod !== "GET") failures.push("method");
if (failures.length > 0) {
return new Response(`Disallowed CORS ${failures.join(", ")}`, { status: 400 });
}
return new Response("OK", { status: 200 });
});
}
+21
View File
@@ -0,0 +1,21 @@
import type { Metadata } from "next";
import PageEffects from "../../components/PageEffects";
import PhotoSlider from "../../components/PhotoSlider";
import { galleryYears } from "../../data/galleryYears";
import { createPageMetadata } from "../../lib/metadata";
export const metadata: Metadata = createPageMetadata({ title: "Bilder", description: "Neutrale Bildergalerie.", path: "/bilder" });
export default function PicturesPage() {
return (
<div className="about-v2">
<header className="about-header about-header--hero-camp2"><div className="about-header__overlay" /><div className="about-header__content"><h1>Bilder</h1><p>Platzhalter für Bilder und externe Galerien.</p></div></header>
<section className="about-block reveal"><div className="about-block__inner"><PhotoSlider /></div></section>
<section className="about-block about-block--alt reveal"><div className="about-block__inner">
<div className="about-block__head"><span className="about-eyebrow">Galerien</span><h2>Galerieübersicht</h2></div>
{galleryYears.length ? <div className="bilder-grid">{galleryYears.map((year) => <article className="bilder-card" key={year.year}><h2>{year.year}</h2><ul className="bilder-link-list">{year.items.map((item) => <li key={item.label}>{item.link ? <a href={item.link} target="_blank" rel="noopener noreferrer">{item.label}</a> : <span>{item.label}</span>}</li>)}</ul></article>)}</div> : <p className="muted">Noch keine Galerien hinterlegt.</p>}
</div></section>
<PageEffects once={false} />
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
import type { Metadata } from "next";
import { createPageMetadata } from "../../lib/metadata";
import { COMPANY_NAME, CONTACT_ADDRESS, CONTACT_EMAIL, SITE_URL } from "../../lib/site";
export const metadata: Metadata = createPageMetadata({ title: "Datenschutz", description: "Platzhalter für Datenschutzhinweise.", path: "/datenschutz", noindex: true });
export default function PrivacyPage() {
return (
<section className="container legal-page">
<header className="page-header"><h1>Datenschutz</h1><p>Neutrale Vorlage – vor Veröffentlichung rechtlich prüfen und vervollständigen.</p></header>
<div className="legal-content">
<h2>Verantwortliche Stelle</h2>
<p>{COMPANY_NAME}<br />{CONTACT_ADDRESS}<br />E-Mail: <a href={`mailto:${CONTACT_EMAIL}`}>{CONTACT_EMAIL}</a></p>
<h2>Geltungsbereich</h2>
<p>Diese Platzhalterseite bezieht sich auf <a href={SITE_URL}>{SITE_URL}</a>.</p>
<h2>Technischer Betrieb</h2>
<p>Beim Abruf der Website können technisch erforderliche Zugriffsdaten verarbeitet werden. Passen Sie diesen Abschnitt an Hosting, Formulare, Cookies, eingebundene Dienste und tatsächliche Verarbeitungen an.</p>
<h2>Hinweis</h2>
<p>Dieser Text ist keine vollständige Datenschutzerklärung und keine Rechtsberatung.</p>
</div>
</section>
);
}
+22
View File
@@ -0,0 +1,22 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getAllTripReports, getTripReport } from "@/trip-reports";
import JsonLd from "../../../components/JsonLd";
import { createPageMetadata } from "../../../lib/metadata";
import { COMPANY_NAME, SITE_URL } from "../../../lib/site";
import { createExcerpt } from "../../../utils/postUtils";
interface TripPageProps { params: Promise<{ slug: string }>; }
export const dynamicParams = false;
export async function generateStaticParams() { return (await getAllTripReports()).filter((post) => post.metadata.published).map((post) => ({ slug: post.metadata.slug })); }
export async function generateMetadata({ params }: TripPageProps): Promise<Metadata> { const { slug } = await params; const post = await getTripReport(slug); return post?.metadata.published ? createPageMetadata({ title: post.metadata.title, description: createExcerpt(post.metadata.plainText, 160), path: `/fahrten/${post.metadata.slug}`, type: "article" }) : {}; }
export default async function TripPage({ params }: TripPageProps) {
const { slug } = await params;
const post = await getTripReport(slug);
if (!post?.metadata.published) notFound();
const ReportContent = post.Component;
const jsonLd = { "@context": "https://schema.org", "@type": "BlogPosting", headline: post.metadata.title, dateModified: new Date(post.metadata.updatedAt).toISOString(), author: { "@type": "Person", name: post.metadata.author }, publisher: { "@type": "Organization", name: COMPANY_NAME }, mainEntityOfPage: `${SITE_URL}/fahrten/${post.metadata.slug}`, articleBody: post.metadata.plainText };
return <div className="container page-spacing post-detail-page"><JsonLd data={jsonLd} /><Link className="back-link" href="/fahrten">&larr; Zur Beitragsübersicht</Link><article className="post-card post-detail-card"><header><h1>{post.metadata.title}</h1><p className="post-meta">Von {post.metadata.author}</p></header><div className="markdown-content"><ReportContent /></div></article></div>;
}
+25
View File
@@ -0,0 +1,25 @@
import type { Metadata } from "next";
import Link from "next/link";
import { getAllTripReports } from "@/trip-reports";
import JsonLd from "../../components/JsonLd";
import PageEffects from "../../components/PageEffects";
import { createPageMetadata } from "../../lib/metadata";
import { SITE_URL } from "../../lib/site";
import { createExcerpt } from "../../utils/postUtils";
export const metadata: Metadata = createPageMetadata({ title: "Beiträge", description: "Übersicht veröffentlichter Beiträge.", path: "/fahrten" });
export default async function TripsPage() {
const posts = (await getAllTripReports()).filter((post) => post.metadata.published).sort((a, b) => new Date(b.metadata.createdAt).getTime() - new Date(a.metadata.createdAt).getTime());
const collectionJsonLd = { "@context": "https://schema.org", "@type": "CollectionPage", name: "Beiträge", url: `${SITE_URL}/fahrten`, hasPart: posts.slice(0, 20).map((post) => ({ "@type": "BlogPosting", headline: post.metadata.title, url: `${SITE_URL}/fahrten/${post.metadata.slug}`, author: { "@type": "Person", name: post.metadata.author } })) };
return (
<div className="about-v2">
<JsonLd data={collectionJsonLd} />
<header className="about-header about-header--hero-camp1"><div className="about-header__overlay" /><div className="about-header__content"><h1>Beiträge</h1><p>Platzhalter für redaktionelle Inhalte.</p></div></header>
<section className="about-block reveal"><div className="about-block__inner">
{posts.length ? <div className="post-grid post-grid--v2">{posts.map((post) => <Link href={`/fahrten/${post.metadata.slug}`} className="post-card-link" key={post.metadata.slug}><article className="post-card post-preview-card"><header><h3>{post.metadata.title}</h3><p className="post-meta">Von {post.metadata.author}</p></header><p className="post-preview-text">{createExcerpt(post.metadata.plainText, 240)}</p><span className="post-preview-link">Weiterlesen</span></article></Link>)}</div> : <p className="about-block__empty">Noch keine Beiträge veröffentlicht.</p>}
</div></section>
<PageEffects threshold={0} rootMargin="0px" />
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { handleRoute } from "../../../server/calendar/http";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET(request: Request): Promise<Response> {
return handleRoute(request, () => Response.json({ status: "ok" }), {
httpOnlyConfig: true,
});
}
+9
View File
@@ -0,0 +1,9 @@
import { handleRoute } from "../../../server/calendar/http";
import { readinessResponse } from "../../../server/calendar/readiness";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET(request: Request): Promise<Response> {
return handleRoute(request, readinessResponse, { httpOnlyConfig: true });
}
+9
View File
@@ -0,0 +1,9 @@
import { handleRoute } from "../../server/calendar/http";
import { readinessResponse } from "../../server/calendar/readiness";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET(request: Request): Promise<Response> {
return handleRoute(request, readinessResponse, { httpOnlyConfig: true });
}
+21
View File
@@ -0,0 +1,21 @@
import type { Metadata } from "next";
import { createPageMetadata } from "../../lib/metadata";
import { COMPANY_NAME, CONTACT_ADDRESS, CONTACT_EMAIL, CONTACT_PHONE, SITE_URL, toPhoneUrl } from "../../lib/site";
export const metadata: Metadata = createPageMetadata({ title: "Impressum", description: "Platzhalter für rechtliche Anbieterangaben.", path: "/impressum", noindex: true });
export default function LegalNoticePage() {
return (
<section className="container legal-page">
<header className="page-header"><h1>Impressum</h1><p>Neutrale Vorlage – vor Veröffentlichung rechtlich prüfen und vervollständigen.</p></header>
<div className="legal-content">
<h2>Diensteanbieter</h2>
<p><b>{COMPANY_NAME}</b><br />{CONTACT_ADDRESS}</p>
<h2>Kontakt</h2>
<p>Telefon: <a href={toPhoneUrl(CONTACT_PHONE)}>{CONTACT_PHONE}</a><br />E-Mail: <a href={`mailto:${CONTACT_EMAIL}`}>{CONTACT_EMAIL}</a><br />Website: <a href={SITE_URL}>{SITE_URL}</a></p>
<h2>Hinweis</h2>
<p>Dieser Text ist nur ein technischer Platzhalter und keine Rechtsberatung. Ergänzen Sie alle für Ihr Projekt erforderlichen Pflichtangaben.</p>
</div>
</section>
);
}
+67
View File
@@ -0,0 +1,67 @@
import type { Metadata } from "next";
import { Fragment } from "react";
import PacklisteIcon from "../../components/PacklisteIcon";
import PageEffects from "../../components/PageEffects";
import RichTextParagraph from "../../components/RichTextParagraph";
import { downloads } from "../../data/downloads";
import { packlisteBasics, packlisteIntro, packlisteItems, packlisteTips } from "../../data/packliste";
import { createPageMetadata } from "../../lib/metadata";
export const metadata: Metadata = createPageMetadata({
title: "Informationen",
description: "Neutrale Seite für Informationen und Downloads.",
path: "/informationen",
});
function getFileIcon(filename: string): string {
const extension = filename.toLowerCase().split(".").pop() || "";
if (extension === "pdf") return "\u{1F4C4}";
if (["doc", "docx", "txt"].includes(extension)) return "\u{1F4DD}";
return "\u{1F4CE}";
}
export default function InformationPage() {
return (
<div className="about-v2 about-v2--info">
<header className="about-header about-header--hero-camp">
<div className="about-header__overlay" />
<div className="about-header__content"><h1>Informationen</h1><p>Platzhalter für strukturierte Informationen und Dokumente.</p></div>
</header>
<section className="about-block reveal">
<div className="about-block__inner">
<div className="about-block__head"><span className="about-eyebrow">Bausteine</span><h2>Informationsbereiche</h2></div>
<div className="packliste">
<div className="packliste__intro">{packlisteIntro.map((paragraph) => <RichTextParagraph text={paragraph} key={paragraph} />)}</div>
<div className="packliste__callout">
<div className="packliste__callout-icon" aria-hidden="true"><PacklisteIcon name={packlisteBasics.icon} size={20} /></div>
<div className="packliste__callout-body"><h4>{packlisteBasics.title}</h4>{packlisteBasics.paragraphs.map((paragraph) => <RichTextParagraph text={paragraph} key={paragraph} />)}</div>
</div>
<div className="packliste__grid">
{packlisteItems.map((item) => (
<article className="packliste__item" key={item.title}>
<div className="packliste__item-header"><span className="packliste__item-icon" aria-hidden="true"><PacklisteIcon name={item.icon} size={18} /></span><h4>{item.title}</h4></div>
{item.paragraphs.map((paragraph, index) => (
<Fragment key={paragraph}><RichTextParagraph text={paragraph} />{index === 0 && item.bullets?.length ? <ul>{item.bullets.map((bullet) => <li key={bullet}>{bullet}</li>)}</ul> : null}</Fragment>
))}
</article>
))}
</div>
<div className="packliste__tips"><h4>{packlisteTips.title}</h4>{packlisteTips.paragraphs.map((paragraph) => <RichTextParagraph text={paragraph} key={paragraph} />)}</div>
</div>
</div>
</section>
<section className="about-block about-block--alt reveal">
<div className="about-block__inner">
<div className="about-block__head"><span className="about-eyebrow">Dateien</span><h2>Downloads</h2></div>
{downloads.length ? <div className="download-grid">{downloads.map((download) => (
<a href={download.download_url} download className="download-card" title={`Download: ${download.name}`} key={download.download_url}>
<div className="download-header"><span className="download-icon">{getFileIcon(download.name)}</span><h3 className="download-name">{download.name}</h3></div>
<p className="download-description">{download.description}</p>
</a>
))}</div> : <p className="muted">Noch keine Downloads hinterlegt.</p>}
</div>
</section>
<PageEffects threshold={0} rootMargin="0px" />
</div>
);
}
+25
View File
@@ -0,0 +1,25 @@
import type { Metadata } from "next";
import EventsView from "../../components/EventsView";
import PageEffects from "../../components/PageEffects";
import { createPageMetadata } from "../../lib/metadata";
export const metadata: Metadata = createPageMetadata({
title: "Kalender",
description: "Kommende Termine im Kalenderüberblick.",
path: "/kalender",
});
export const dynamic = "force-dynamic";
export default function CalendarPage() {
return (
<div className="about-v2">
<header className="about-header about-header--hero-camp2">
<div className="about-header__overlay" />
<div className="about-header__content"><h1>Kalender</h1><p>Termine aus der konfigurierten Kalenderquelle.</p></div>
</header>
<section className="about-block reveal"><div className="about-block__inner"><EventsView mode="calendar" /></div></section>
<PageEffects once={false} />
</div>
);
}
+52
View File
@@ -0,0 +1,52 @@
import type { Metadata, Viewport } from "next";
import { connection } from "next/server";
import type { ReactNode } from "react";
import Footer from "../components/Footer";
import Header from "../components/Header";
import ScrollToTop from "../components/ScrollToTop";
import { SITE_NAME, SITE_URL } from "../lib/site";
import "../styles/base.css";
import "../styles/layout.css";
import "../styles/components.css";
import "../styles/hero.css";
import "../styles/about.css";
import "../styles/calendar.css";
import "../styles/packliste.css";
import "../styles/post.css";
import "../styles/PhotoSlider.css";
export const metadata: Metadata = {
metadataBase: new URL(SITE_URL),
title: {
default: SITE_NAME,
template: `%s | ${SITE_NAME}`,
},
icons: { icon: "/logo.svg" },
};
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
};
export default async function RootLayout({ children }: Readonly<{ children: ReactNode }>) {
await connection();
return (
<html lang="de">
<head>
<link rel="preload" href="/fonts/Montserrat-Regular.woff2" as="font" type="font/woff2" crossOrigin="anonymous" />
<link rel="preload" href="/fonts/Poppins-Bold.woff2" as="font" type="font/woff2" crossOrigin="anonymous" />
</head>
<body>
<a href="#main-content" className="skip-link">Zum Inhalt springen</a>
<div className="app-shell">
<Header siteName={SITE_NAME} />
<main id="main-content">{children}</main>
<Footer />
</div>
<ScrollToTop />
</body>
</html>
);
}
+20
View File
@@ -0,0 +1,20 @@
import type { Metadata } from "next";
import Link from "next/link";
import { createPageMetadata } from "../lib/metadata";
export const metadata: Metadata = createPageMetadata({
title: "Seite nicht gefunden",
description: "Die angeforderte Seite wurde nicht gefunden.",
path: "/404",
noindex: true,
});
export default function NotFound() {
return (
<section className="container page-spacing">
<h1>Seite nicht gefunden</h1>
<p className="muted">Diese Seite existiert nicht oder wurde verschoben.</p>
<Link className="back-link" href="/">&larr; Zur Startseite</Link>
</section>
);
}
+73
View File
@@ -0,0 +1,73 @@
import type { Metadata } from "next";
import Link from "next/link";
import { getAllTripReports } from "@/trip-reports";
import EventsView from "../components/EventsView";
import JsonLd from "../components/JsonLd";
import { createPageMetadata } from "../lib/metadata";
import { COMPANY_NAME, SITE_NAME, SITE_URL } from "../lib/site";
import { createExcerpt } from "../utils/postUtils";
const homeMetadata = createPageMetadata({
title: "Startseite",
description: "Neutrales Starter-Projekt für eine neue Website.",
path: "/",
});
export const metadata: Metadata = {
...homeMetadata,
title: { absolute: SITE_NAME },
};
export const dynamic = "force-dynamic";
export default async function HomePage() {
const posts = (await getAllTripReports())
.filter((post) => post.metadata.published)
.sort((a, b) => new Date(b.metadata.createdAt).getTime() - new Date(a.metadata.createdAt).getTime())
.slice(0, 3);
const jsonLd = [
{ "@context": "https://schema.org", "@type": "Organization", name: COMPANY_NAME, url: SITE_URL },
{ "@context": "https://schema.org", "@type": "WebSite", name: SITE_NAME, url: SITE_URL },
];
return (
<>
<JsonLd data={jsonLd} />
<section className="hero">
<div className="container hero-content">
<div>
<h1>Bereit für Ihre neue Website</h1>
<p>Diese neutrale Startseite enthält bewusst nur minimale Platzhalter. Inhalte, Navigation und Gestaltung können projektspezifisch ergänzt werden.</p>
<a className="cta" href="#start">Projekt starten</a>
</div>
<div className="hero-card">
<h2>Nächste Termine</h2>
<EventsView mode="special" />
</div>
</div>
</section>
<section id="start" className="container group-info">
<div className="group-info-card">
<h2>Neutraler Ausgangspunkt</h2>
<p>Die technische Infrastruktur ist eingerichtet. Ersetzen Sie diesen Abschnitt durch den Einstieg Ihrer neuen Website.</p>
</div>
</section>
<section className="container">
<h2>Aktuelle Beiträge</h2>
{posts.length ? (
<div className="post-grid">
{posts.map((post) => (
<Link href={`/fahrten/${post.metadata.slug}`} className="post-card-link" key={post.metadata.slug}>
<article className="post-card post-preview-card">
<header><h3>{post.metadata.title}</h3><p className="post-meta">Von {post.metadata.author}</p></header>
<p className="post-preview-text">{createExcerpt(post.metadata.plainText, 220)}</p>
<span className="post-preview-link">Weiterlesen</span>
</article>
</Link>
))}
</div>
) : <p className="muted">Noch keine Beiträge veröffentlicht.</p>}
</section>
</>
);
}
+13
View File
@@ -0,0 +1,13 @@
import type { MetadataRoute } from "next";
import { SITE_URL } from "../lib/site";
export default function robots(): MetadataRoute.Robots {
return {
rules: {
userAgent: "*",
allow: "/",
disallow: ["/api/", "/health", "/downloads/"],
},
sitemap: `${SITE_URL}/sitemap-index.xml`,
};
}
+17
View File
@@ -0,0 +1,17 @@
import { SITE_URL } from "../../lib/site";
export const dynamic = "force-static";
export function GET(): Response {
const body = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
` <sitemap><loc>${SITE_URL}/sitemap.xml</loc></sitemap>`,
"</sitemapindex>",
"",
].join("\n");
return new Response(body, {
headers: { "Content-Type": "application/xml; charset=utf-8" },
});
}
+25
View File
@@ -0,0 +1,25 @@
import type { MetadataRoute } from "next";
import { getAllTripReports } from "@/trip-reports";
import { SITE_URL } from "../lib/site";
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const staticPaths = [
"",
"/ueber-uns",
"/informationen",
"/kalender",
"/fahrten",
"/bilder",
];
const staticEntries: MetadataRoute.Sitemap = staticPaths.map((path) => ({
url: `${SITE_URL}${path}`,
}));
const tripEntries: MetadataRoute.Sitemap = (await getAllTripReports())
.filter((post) => post.metadata.published)
.map((post) => ({
url: `${SITE_URL}/fahrten/${post.metadata.slug}`,
lastModified: new Date(post.metadata.updatedAt),
}));
return [...staticEntries, ...tripEntries];
}
+35
View File
@@ -0,0 +1,35 @@
import type { Metadata } from "next";
import PageEffects from "../../components/PageEffects";
import PhotoSlider from "../../components/PhotoSlider";
import { createPageMetadata } from "../../lib/metadata";
export const metadata: Metadata = createPageMetadata({
title: "Über uns",
description: "Neutrale Inhaltsseite für die Vorstellung einer Organisation.",
path: "/ueber-uns",
});
export default function AboutPage() {
return (
<div className="about-v2">
<header className="about-header about-header--hero-camp1">
<div className="about-header__overlay" />
<div className="about-header__content"><h1>Über uns</h1><p>Platzhalter für eine kurze Vorstellung.</p></div>
</header>
<section className="about-block reveal">
<div className="about-block__inner about-block__inner--narrow">
<span className="about-eyebrow">Organisation</span>
<h2>Ihre Geschichte</h2>
<p>Ergänzen Sie hier die Geschichte, Werte und Ziele Ihres neuen Projekts.</p>
</div>
</section>
<section className="about-block about-block--alt reveal">
<div className="about-block__inner">
<div className="about-block__head"><span className="about-eyebrow">Medien</span><h2>Bilder</h2></div>
<PhotoSlider imageDir="secondary-slider" label="Beispielgalerie" />
</div>
</section>
<PageEffects threshold={0} rootMargin="0px" />
</div>
);
}
+8
View File
@@ -0,0 +1,8 @@
interface ContactLinkProps {
href: string;
children: string;
}
export default function ContactLink({ href, children }: ContactLinkProps) {
return <a href={href}>{children}</a>;
}
+29
View File
@@ -0,0 +1,29 @@
import { getEventsService } from "../server/calendar/events-service";
import type { CalendarEvent } from "../types";
import EventsViewClient from "./EventsViewClient";
interface EventsViewProps {
mode: "special" | "calendar";
}
export default async function EventsView({ mode }: EventsViewProps) {
let initialEvents: CalendarEvent[] | null = null;
try {
const service = getEventsService();
initialEvents = mode === "special"
? await service.getSpecialEvents()
: await service.getEvents();
} catch {
// The page remains available while the calendar source is unavailable.
}
return (
<EventsViewClient
mode={mode}
initialEvents={initialEvents}
referenceDate={new Date().toISOString()}
fixedReferenceDate={false}
/>
);
}
+170
View File
@@ -0,0 +1,170 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import type { CalendarEvent } from "../types";
import { formatEventDateRange } from "../utils/eventFormat";
import { getCalendarGroups, getSpecialEvents } from "../utils/eventsRender";
interface EventsViewClientProps {
mode: "special" | "calendar";
initialEvents: CalendarEvent[] | null;
referenceDate: string;
fixedReferenceDate: boolean;
}
const REQUEST_TIMEOUT_MS = 10_000;
async function fetchEvents(
specialOnly: boolean,
): Promise<CalendarEvent[]> {
const controller = new AbortController();
const timeout = window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
const path = specialOnly ? "/api/events?special=true" : "/api/events";
try {
const response = await fetch(path, { signal: controller.signal });
if (!response.ok) {
const message = await response.text();
throw new Error(message || response.statusText);
}
return (await response.json()) as CalendarEvent[];
} finally {
window.clearTimeout(timeout);
}
}
function SpecialEvents({
events,
now,
}: {
events: CalendarEvent[];
now: Date;
}) {
const specialEvents = getSpecialEvents(events, now);
if (!specialEvents.length) {
return <p className="muted">Aktuell sind keine besonderen Termine geplant.</p>;
}
return (
<div className="hero-special-events">
<ul>
{specialEvents.map((event) => (
<li key={event.id}>
<span className="group-name">{event.title}</span>
<span>{new Intl.DateTimeFormat("de-DE", {
dateStyle: "long",
timeZone: event.timeZone,
}).format(new Date(event.start))}</span>
</li>
))}
</ul>
<p className="calendar-note">
Alle Termine mit weiteren Details findest Du im <Link href="/kalender">Kalender</Link>.
</p>
</div>
);
}
function CalendarEvents({
events,
now,
}: {
events: CalendarEvent[];
now: Date;
}) {
const groups = getCalendarGroups(events, now);
if (!groups.length) {
return (
<p className="muted">
In den nächsten 12 Monaten sind noch keine Termine geplant.
</p>
);
}
return (
<div className="calendar-table">
{groups.map((group) => (
<section className="calendar-table-month" aria-label={group.label} key={group.label}>
<h2 className="calendar-month-heading">{group.label}</h2>
<div className="calendar-table-grid" role="table">
<div className="calendar-table-row calendar-table-row-head" role="row">
<span className="calendar-table-title" role="columnheader">Termin</span>
<span className="calendar-table-date" role="columnheader">Datum &amp; Uhrzeit</span>
</div>
{group.events.map((event) => (
<div className="calendar-table-row" role="row" key={event.id}>
<span className="calendar-table-title" role="cell">
<span className="calendar-event-title">
{event.special ? <span className="calendar-highlight">★</span> : null}
{event.special ? " " : null}
{event.title}
</span>
{event.location ? <span className="calendar-event-location">, {event.location}</span> : null}
</span>
<span className="calendar-table-date" role="cell">{formatEventDateRange(event)}</span>
</div>
))}
</div>
</section>
))}
</div>
);
}
export default function EventsViewClient({
mode,
initialEvents,
referenceDate,
fixedReferenceDate,
}: EventsViewClientProps) {
const [events, setEvents] = useState<CalendarEvent[] | null>(initialEvents);
const [error, setError] = useState<string | null>(null);
const [renderReferenceDate, setRenderReferenceDate] = useState(referenceDate);
const now = new Date(renderReferenceDate);
useEffect(() => {
if (initialEvents !== null) return;
const request = { active: true };
void fetchEvents(mode === "special")
.then((freshEvents) => {
if (!request.active) return;
setEvents(freshEvents);
if (!fixedReferenceDate) setRenderReferenceDate(new Date().toISOString());
setError(null);
})
.catch((cause: unknown) => {
if (!request.active) return;
const message =
cause instanceof Error ? cause.message : "Konnte Termine nicht laden.";
setError(
initialEvents !== null
? "Aktualisierung fehlgeschlagen, zeige letzte bekannte Daten."
: message,
);
});
return () => {
request.active = false;
};
}, [fixedReferenceDate, initialEvents, mode]);
return (
<div className="events-view">
{events === null && !error ? <p role="status">Lade Termine...</p> : null}
{error ? <p className="error" role="alert">{error}</p> : null}
{events !== null ? (
mode === "special" ? <SpecialEvents events={events} now={now} /> : <CalendarEvents events={events} now={now} />
) : null}
<noscript>
<p className="muted">
Die Termine werden serverseitig geladen und können bei Problemen mit der
Kalenderquelle vorübergehend veraltet sein.
</p>
</noscript>
</div>
);
}
+59
View File
@@ -0,0 +1,59 @@
import Link from "next/link";
import {
COMPANY_NAME,
CONTACT_ADDRESS,
CONTACT_EMAIL,
CONTACT_PHONE,
toPhoneUrl,
} from "../lib/site";
import ContactLink from "./ContactLink";
export default function Footer() {
return (
<footer className="app-footer">
<div className="container footer-content">
<div className="footer-top">
<div className="footer-column footer-contact">
<h2 className="footer-heading">Kontakt</h2>
<address>
<div className="footer-contact-item">
<svg className="footer-contact-icon" viewBox="0 0 24 24" role="presentation" aria-hidden="true">
<path fill="currentColor" d="M12 2a7 7 0 0 0-7 7c0 5.25 7 13 7 13s7-7.75 7-13a7 7 0 0 0-7-7Zm0 9.5a2.5 2.5 0 1 1 0-5 2.5 2.5 0 0 1 0 5Z" />
</svg>
<span>{CONTACT_ADDRESS}</span>
</div>
<div className="footer-contact-item">
<svg className="footer-contact-icon" viewBox="0 0 24 24" role="presentation" aria-hidden="true">
<path fill="currentColor" d="M20 4H4a1 1 0 0 0-1 1v1.22l9 5.4 9-5.4V5a1 1 0 0 0-1-1Zm1 5.26-9 5.4-9-5.4V19a1 1 0 0 0 1 1h16a1 1 0 0 0 1-1V9.26Z" />
</svg>
<ContactLink href={`mailto:${CONTACT_EMAIL}`}>{CONTACT_EMAIL}</ContactLink>
</div>
<div className="footer-contact-item">
<svg className="footer-contact-icon" viewBox="0 0 24 24" role="presentation" aria-hidden="true">
<path fill="currentColor" d="M6.62 10.79a15.91 15.91 0 0 0 6.59 6.59l1.89-1.89a1 1 0 0 1 1-.24 12.18 12.18 0 0 0 3.83.61 1 1 0 0 1 1 1v3.18a1 1 0 0 1-1 1A17 17 0 0 1 3 7a1 1 0 0 1 1-1h3.18a1 1 0 0 1 1 1 12.31 12.31 0 0 0 .61 3.83 1 1 0 0 1-.24 1Z" />
</svg>
<ContactLink href={toPhoneUrl(CONTACT_PHONE)}>{CONTACT_PHONE}</ContactLink>
</div>
</address>
</div>
<nav className="footer-column footer-links" aria-label="Seitennavigation">
<h2 className="footer-heading">Links</h2>
<ul>
<li><Link href="/ueber-uns">Über uns</Link></li>
<li><Link href="/informationen">Informationen</Link></li>
<li><Link href="/kalender">Kalender</Link></li>
<li><Link href="/bilder">Bilder</Link></li>
</ul>
</nav>
</div>
<div className="footer-bottom">
<span>&copy; {new Date().getFullYear()} {COMPANY_NAME}</span>
<nav className="footer-legal" aria-label="Rechtliches">
<Link href="/datenschutz">Datenschutz</Link>
<Link href="/impressum">Impressum</Link>
</nav>
</div>
</div>
</footer>
);
}
+81
View File
@@ -0,0 +1,81 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
const navLinks = [
{ href: "/", label: "Start" },
{ href: "/ueber-uns", label: "Über uns" },
{ href: "/informationen", label: "Informationen" },
{ href: "/kalender", label: "Kalender" },
{ href: "/fahrten", label: "Beiträge" },
{ href: "/bilder", label: "Bilder" },
];
export default function Header({ siteName }: { siteName: string }) {
const pathname = usePathname() ?? "/";
const [openPath, setOpenPath] = useState<string | null>(null);
const open = openPath === pathname;
useEffect(() => {
const closeOnEscape = (event: KeyboardEvent) => {
if (event.key === "Escape") setOpenPath(null);
};
document.addEventListener("keydown", closeOnEscape);
return () => document.removeEventListener("keydown", closeOnEscape);
}, []);
const isActive = (href: string) =>
href === "/" ? pathname === "/" : pathname.startsWith(href);
return (
<header className="app-header">
<div className="container header-content">
<Link href="/" className="brand">
<img
src="/logo.svg"
alt={`${siteName} Logo`}
className="brand-logo"
/>
<span>{siteName}</span>
</Link>
<button
className="nav-toggle"
type="button"
aria-expanded={open}
aria-controls="primary-navigation"
aria-label={open ? "Menü schließen" : "Menü öffnen"}
data-open={String(open)}
onClick={() => setOpenPath(open ? null : pathname)}
>
<span className="nav-toggle-bars" aria-hidden="true">
<span />
<span />
<span />
</span>
</button>
<nav
className="nav-links"
id="primary-navigation"
data-open={String(open)}
>
{navLinks.map(({ href, label }) => {
const active = isActive(href);
return (
<Link
key={href}
href={href}
aria-current={active ? "page" : undefined}
className={active ? "active" : undefined}
onClick={() => setOpenPath(null)}
>
{label}
</Link>
);
})}
</nav>
</div>
</header>
);
}
+20
View File
@@ -0,0 +1,20 @@
import { headers } from "next/headers";
import { serializeJsonLd } from "../utils/jsonLd";
interface JsonLdProps {
data: Record<string, unknown> | Record<string, unknown>[];
}
export default async function JsonLd({ data }: JsonLdProps) {
const entries = Array.isArray(data) ? data : [data];
const nonce = (await headers()).get("x-nonce") ?? undefined;
return entries.map((entry, index) => (
<script
key={index}
nonce={nonce}
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: serializeJsonLd(entry) }}
/>
));
}
+34
View File
@@ -0,0 +1,34 @@
import type { PacklisteIconName } from "../data/packliste";
interface PacklisteIconProps {
name: PacklisteIconName;
size?: number;
}
export default function PacklisteIcon({ name, size = 20 }: PacklisteIconProps) {
if (name === "star") {
return (
<svg width={size} height={size} viewBox="0 0 20 20" fill="none" aria-hidden="true">
<path d="M10 2L12.09 7.26L18 8.27L13.82 12.14L14.94 18.02L10 15.27L5.06 18.02L6.18 12.14L2 8.27L7.91 7.26L10 2Z" fill="currentColor" />
</svg>
);
}
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
{name === "document" ? <><path d="M2 4v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8l-6-6H4c-1.1 0-2 .9-2 2z" /><path d="M14 2v6h6" /></> : null}
{name === "mat" ? <><rect x="2" y="6" width="20" height="12" rx="2" /><path d="M2 12h20" /></> : null}
{name === "meal-bag" ? <><path d="M18 8h1a4 4 0 010 8h-1" /><path d="M2 8h16v9a4 4 0 01-4 4H6a4 4 0 01-4-4V8z" /><line x1="6" y1="1" x2="6" y2="4" /><line x1="10" y1="1" x2="10" y2="4" /><line x1="14" y1="1" x2="14" y2="4" /></> : null}
{name === "wash" ? <path d="M12 2.69l5.66 5.66a8 8 0 11-11.31 0z" /> : null}
{name === "clothes" ? <path d="M20.38 3.46L16 2 12 3.46 8 2 3.62 3.46a2 2 0 00-1.34 1.89v13.3a2 2 0 002.68 1.89L8 19.54l4 1.46 4-1.46 3.04 1.1a2 2 0 002.68-1.89V5.35a2 2 0 00-1.34-1.89z" /> : null}
{name === "boots" ? <><path d="M2 22l1-1h18l1 1" /><path d="M6 18V2l4 2 4-2 4 2v16" /></> : null}
{name === "rain" ? <><path d="M16 13v8" /><path d="M12 21h8" /><path d="M20 16.58A5 5 0 0018 7h-1.26A8 8 0 104 15.25" /></> : null}
{name === "flashlight" ? <><line x1="9" y1="18" x2="15" y2="18" /><line x1="10" y1="22" x2="14" y2="22" /><path d="M15.09 14c.18-.98.65-1.74 1.41-2.5A4.65 4.65 0 0018 8 6 6 0 006 8c0 1 .23 2.23 1.5 3.5A4.61 4.61 0 018.91 14" /></> : null}
{name === "hat" ? <><circle cx="12" cy="12" r="5" /><line x1="12" y1="1" x2="12" y2="3" /><line x1="12" y1="21" x2="12" y2="23" /><line x1="4.22" y1="4.22" x2="5.64" y2="5.64" /><line x1="18.36" y1="18.36" x2="19.78" y2="19.78" /><line x1="1" y1="12" x2="3" y2="12" /><line x1="21" y1="12" x2="23" y2="12" /><line x1="4.22" y1="19.78" x2="5.64" y2="18.36" /><line x1="18.36" y1="5.64" x2="19.78" y2="4.22" /></> : null}
{name === "first-aid" ? <path d="M22 12h-4l-3 9L9 3l-3 9H2" /> : null}
{name === "book" ? <><path d="M4 19.5A2.5 2.5 0 016.5 17H20" /><path d="M6.5 2H20v20H6.5A2.5 2.5 0 014 19.5v-15A2.5 2.5 0 016.5 2z" /></> : null}
{name === "laundry" ? <><path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z" /><line x1="3" y1="6" x2="21" y2="6" /><path d="M16 10a4 4 0 01-8 0" /></> : null}
{name === "note" ? <><rect x="2" y="2" width="20" height="20" rx="5" ry="5" /><line x1="16" y1="8" x2="8" y2="8" /><line x1="16" y1="12" x2="8" y2="12" /><line x1="10" y1="16" x2="8" y2="16" /></> : null}
</svg>
);
}
+33
View File
@@ -0,0 +1,33 @@
"use client";
import { useEffect } from "react";
interface PageEffectsProps {
threshold?: number;
rootMargin?: string;
once?: boolean;
}
export default function PageEffects({
threshold = 0.1,
rootMargin = "0px 0px -40px 0px",
once = true,
}: PageEffectsProps) {
useEffect(() => {
const elements = document.querySelectorAll(".reveal");
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) return;
entry.target.classList.add("revealed");
if (once) observer.unobserve(entry.target);
});
},
{ threshold, rootMargin },
);
elements.forEach((element) => observer.observe(element));
return () => observer.disconnect();
}, [once, rootMargin, threshold]);
return null;
}
+26
View File
@@ -0,0 +1,26 @@
import { getSliderImages } from "../lib/photo-slider";
import PhotoSliderCarousel from "./PhotoSliderCarousel";
interface PhotoSliderProps {
imageDir?: string;
label?: string;
autoplayMs?: number;
}
export default async function PhotoSlider({
imageDir = "slider",
label = "Bildergalerie",
autoplayMs = 5000,
}: PhotoSliderProps) {
const images = await getSliderImages(imageDir);
const sliderSlug = imageDir.replace(/[^a-z0-9]+/gi, "-").toLowerCase();
return (
<PhotoSliderCarousel
images={images}
label={label}
autoplayMs={images.length > 1 ? autoplayMs : 0}
sliderId={`photo-slider-${sliderSlug}`}
/>
);
}
+178
View File
@@ -0,0 +1,178 @@
"use client";
import { useEffect, useRef, useState } from "react";
import type { SliderImage } from "../lib/photo-slider";
interface PhotoSliderCarouselProps {
images: SliderImage[];
label: string;
autoplayMs: number;
sliderId: string;
}
function getNearestSlideIndex(
scrollLeft: number,
slideWidth: number,
slideCount: number,
) {
if (slideCount <= 1) return 0;
return Math.max(
0,
Math.min(slideCount - 1, Math.round(scrollLeft / Math.max(slideWidth, 1))),
);
}
export default function PhotoSliderCarousel({
images,
label,
autoplayMs,
sliderId,
}: PhotoSliderCarouselProps) {
const viewportRef = useRef<HTMLDivElement>(null);
const frameRef = useRef<number | null>(null);
const [activeIndex, setActiveIndex] = useState(0);
const [paused, setPaused] = useState(false);
const hasControls = images.length > 1;
const viewportId = `${sliderId}-viewport`;
const goTo = (nextIndex: number, behavior: ScrollBehavior = "smooth") => {
const viewport = viewportRef.current;
if (!viewport || !images.length) return;
const index = (nextIndex + images.length) % images.length;
setActiveIndex(index);
viewport.scrollTo({ left: viewport.clientWidth * index, behavior });
};
const goBy = (offset: number) => {
const viewport = viewportRef.current;
if (!viewport) return;
const current = getNearestSlideIndex(
viewport.scrollLeft,
viewport.clientWidth,
images.length,
);
goTo(current + offset);
};
useEffect(() => {
if (!hasControls || paused || autoplayMs < 1000) return;
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
const timeout = window.setTimeout(() => {
const viewport = viewportRef.current;
if (!viewport) return;
const index = (activeIndex + 1) % images.length;
setActiveIndex(index);
viewport.scrollTo({ left: viewport.clientWidth * index, behavior: "smooth" });
}, autoplayMs);
return () => window.clearTimeout(timeout);
}, [activeIndex, autoplayMs, hasControls, images.length, paused]);
useEffect(() => {
const handleResize = () => {
const viewport = viewportRef.current;
if (!viewport) return;
viewport.scrollTo({ left: viewport.clientWidth * activeIndex, behavior: "auto" });
};
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, [activeIndex]);
useEffect(() => () => {
if (frameRef.current !== null) cancelAnimationFrame(frameRef.current);
}, []);
if (!images.length) {
return <div className="slider-empty">Keine Slider-Bilder gefunden.</div>;
}
return (
<div
className="slider-container"
data-enhanced="true"
aria-label={label}
aria-roledescription="carousel"
onMouseEnter={() => setPaused(true)}
onMouseLeave={() => setPaused(false)}
onFocus={() => setPaused(true)}
onBlur={(event) => {
if (!event.currentTarget.contains(event.relatedTarget)) setPaused(false);
}}
>
<div className="slider-stage">
<div
className="slider-viewport"
id={viewportId}
ref={viewportRef}
tabIndex={0}
onScroll={(event) => {
if (frameRef.current !== null) cancelAnimationFrame(frameRef.current);
const viewport = event.currentTarget;
frameRef.current = requestAnimationFrame(() => {
setActiveIndex(
getNearestSlideIndex(
viewport.scrollLeft,
viewport.clientWidth,
images.length,
),
);
});
}}
onKeyDown={(event) => {
if (event.key === "ArrowLeft") {
event.preventDefault();
goBy(-1);
} else if (event.key === "ArrowRight") {
event.preventDefault();
goBy(1);
} else if (event.key === "Home") {
event.preventDefault();
goTo(0);
} else if (event.key === "End") {
event.preventDefault();
goTo(images.length - 1);
}
}}
>
{images.map((image, index) => (
<figure
className="slider-slide"
aria-hidden={index !== activeIndex}
key={image.id}
>
<picture className="slider-picture">
{image.srcSetAvif ? (
<source srcSet={image.srcSetAvif} sizes="(max-width: 768px) 100vw, min(100vw, 960px)" type="image/avif" />
) : null}
{image.srcSetWebp ? (
<source srcSet={image.srcSetWebp} sizes="(max-width: 768px) 100vw, min(100vw, 960px)" type="image/webp" />
) : null}
<img
src={image.src}
srcSet={image.srcSet}
sizes="(max-width: 768px) 100vw, min(100vw, 960px)"
alt={image.alt}
width={image.width}
height={image.height}
loading={index === 0 ? "eager" : "lazy"}
fetchPriority={index === 0 ? "high" : "auto"}
draggable="false"
/>
</picture>
</figure>
))}
</div>
{hasControls ? (
<>
<button className="slider-nav slider-nav--prev" type="button" aria-controls={viewportId} aria-label="Vorheriges Bild" onClick={() => goBy(-1)}>
<span aria-hidden="true">&#8249;</span>
</button>
<button className="slider-nav slider-nav--next" type="button" aria-controls={viewportId} aria-label="Nächstes Bild" onClick={() => goBy(1)}>
<span aria-hidden="true">&#8250;</span>
</button>
</>
) : null}
</div>
</div>
);
}
+39
View File
@@ -0,0 +1,39 @@
interface RichTextParagraphProps {
text: string;
className?: string;
}
type Segment = { type: "text" | "strong"; value: string };
function parseStrongSegments(value: string): Segment[] {
const segments: Segment[] = [];
const pattern = /<strong>(.*?)<\/strong>/g;
let lastIndex = 0;
for (const match of value.matchAll(pattern)) {
const matchIndex = match.index ?? 0;
if (matchIndex > lastIndex) {
segments.push({ type: "text", value: value.slice(lastIndex, matchIndex) });
}
segments.push({ type: "strong", value: match[1] ?? "" });
lastIndex = matchIndex + match[0].length;
}
if (lastIndex < value.length) {
segments.push({ type: "text", value: value.slice(lastIndex) });
}
return segments;
}
export default function RichTextParagraph({ text, className }: RichTextParagraphProps) {
return (
<p className={className}>
{parseStrongSegments(text).map((segment, index) =>
segment.type === "strong" ? (
<strong key={index}>{segment.value}</strong>
) : (
segment.value
),
)}
</p>
);
}
+19
View File
@@ -0,0 +1,19 @@
"use client";
import { usePathname } from "next/navigation";
import { useLayoutEffect } from "react";
export default function ScrollToTop() {
const pathname = usePathname();
useLayoutEffect(() => {
const root = document.documentElement;
const previousScrollBehavior = root.style.scrollBehavior;
root.style.scrollBehavior = "auto";
window.scrollTo({ top: 0, left: 0 });
root.style.scrollBehavior = previousScrollBehavior;
}, [pathname]);
return null;
}
+88
View File
@@ -0,0 +1,88 @@
import fs from "node:fs";
import path from "node:path";
interface TripImageProps {
src: string;
alt: string;
caption?: string;
}
const RESPONSIVE_SIZES = [
{ suffix: "-sm", width: 800 },
{ suffix: "-md", width: 1000 },
];
const IMAGE_SIZES = "(max-width: 840px) 100vw, 680px";
const directoryEntries = new Map<string, string[]>();
function resolveAssetPath(assetPath: string): string | undefined {
const relativePath = assetPath.replace(/^\/+/, "");
if (!relativePath || relativePath.split("/").includes("..")) return undefined;
const directory = path.dirname(relativePath);
const absoluteDirectory = path.join(process.cwd(), "public", directory);
let entries = directoryEntries.get(absoluteDirectory);
if (!entries) {
try {
entries = fs.readdirSync(absoluteDirectory);
directoryEntries.set(absoluteDirectory, entries);
} catch {
return undefined;
}
}
const requestedName = path.basename(relativePath);
const fileName =
entries.find((entry) => entry === requestedName) ??
entries.find((entry) => entry.toLowerCase() === requestedName.toLowerCase());
if (!fileName) return undefined;
const publicDirectory = directory === "." ? "" : `${directory}/`;
return `/${publicDirectory}${fileName}`;
}
function buildSrcSet(basePath: string, extension: string): string | undefined {
const entries = RESPONSIVE_SIZES.flatMap(({ suffix, width }) => {
const assetPath = `${basePath}${suffix}${extension}`;
const resolvedPath = resolveAssetPath(assetPath);
return resolvedPath ? [`${resolvedPath} ${width}w`] : [];
});
return entries.length ? entries.join(", ") : undefined;
}
export default function TripImage({ src, alt, caption }: TripImageProps) {
const match = src.match(/^(.*?)(\.[a-zA-Z0-9]+)$/);
const basePath = match?.[1];
const extension = match?.[2];
const fallbackSrcSet =
basePath && extension ? buildSrcSet(basePath, extension) : undefined;
const avifSrcSet = basePath ? buildSrcSet(basePath, ".avif") : undefined;
const webpSrcSet = basePath ? buildSrcSet(basePath, ".webp") : undefined;
const fallbackSrc =
basePath && extension
? [...RESPONSIVE_SIZES]
.reverse()
.map(({ suffix }) => `${basePath}${suffix}${extension}`)
.map(resolveAssetPath)
.find((assetPath) => assetPath !== undefined) ?? src
: src;
return (
<figure className="post-figure">
<picture>
{avifSrcSet ? <source type="image/avif" srcSet={avifSrcSet} sizes={IMAGE_SIZES} /> : null}
{webpSrcSet ? <source type="image/webp" srcSet={webpSrcSet} sizes={IMAGE_SIZES} /> : null}
<img
src={fallbackSrc}
srcSet={fallbackSrcSet}
sizes={fallbackSrcSet ? IMAGE_SIZES : undefined}
alt={alt}
className="post-image"
loading="lazy"
decoding="async"
/>
</picture>
{caption ? <figcaption className="post-caption">{caption}</figcaption> : null}
</figure>
);
}
+4
View File
@@ -0,0 +1,4 @@
import type { Download } from "../types";
// Add project-specific files from public/downloads when needed.
export const downloads: Download[] = [];
+7
View File
@@ -0,0 +1,7 @@
export interface GalleryYear {
year: string;
items: Array<{ label: string; link?: string }>;
}
// Add external galleries only after checking access and privacy requirements.
export const galleryYears: GalleryYear[] = [];
+44
View File
@@ -0,0 +1,44 @@
export type PacklisteIconName =
| "star" | "document" | "mat" | "meal-bag" | "wash" | "clothes"
| "boots" | "rain" | "flashlight" | "hat" | "first-aid" | "book"
| "laundry" | "note";
export interface PacklisteSection {
title: string;
icon: PacklisteIconName;
paragraphs: string[];
bullets?: string[];
variant?: "note";
}
export const packlisteIntro = [
"Dieser Bereich demonstriert wiederverwendbare Informationskarten.",
"Ersetzen Sie die Beispiele durch Inhalte des neuen Projekts.",
];
export const packlisteBasics: PacklisteSection = {
title: "Wichtiger Hinweis",
icon: "star",
paragraphs: ["Konfigurieren und prüfen Sie alle Angaben vor der Veröffentlichung."],
};
export const packlisteItems: PacklisteSection[] = [
{
title: "Beispielabschnitt",
icon: "document",
paragraphs: ["Ein kurzer neutraler Platzhalter für strukturierte Inhalte."],
bullets: ["Erster Punkt", "Zweiter Punkt"],
},
];
export const packlisteDigitalPause: PacklisteSection = {
title: "Zusätzlicher Hinweis",
icon: "note",
variant: "note",
paragraphs: ["Optionaler hervorgehobener Inhaltsbereich."],
};
export const packlisteTips = {
title: "Nächste Schritte",
paragraphs: ["Ersetzen Sie Beispieltexte, Dateien und Verweise durch geprüfte Projektinhalte."],
};
+46
View File
@@ -0,0 +1,46 @@
import type { Metadata } from "next";
import { SITE_NAME, toAbsoluteUrl } from "./site";
const DEFAULT_OG_IMAGE = "/logo.svg";
interface PageMetadataOptions {
title: string;
description: string;
path: string;
type?: "website" | "article";
image?: string;
noindex?: boolean;
}
export function createPageMetadata({
title,
description,
path,
type = "website",
image = DEFAULT_OG_IMAGE,
noindex = false,
}: PageMetadataOptions): Metadata {
const canonicalUrl = toAbsoluteUrl(path);
const imageUrl = toAbsoluteUrl(image);
return {
title,
description,
robots: { index: !noindex, follow: true },
alternates: { canonical: canonicalUrl },
openGraph: {
siteName: SITE_NAME,
title,
description,
type,
url: canonicalUrl,
images: [imageUrl],
},
twitter: {
card: "summary",
title,
description,
images: [imageUrl],
},
};
}
+123
View File
@@ -0,0 +1,123 @@
import secondarySliderManifest from "../../public/images/secondary-slider/slider-images.json";
import sliderManifest from "../../public/images/slider/slider-images.json";
interface SliderImageVariant {
file: string;
width: number;
height: number;
}
interface SliderImageMeta {
name: string;
alt?: string;
width: number;
height: number;
variants: {
fallback: SliderImageVariant[];
webp: SliderImageVariant[];
avif: SliderImageVariant[];
};
}
export interface SliderImage {
id: string;
src: string;
alt: string;
srcSet: string;
srcSetWebp?: string;
srcSetAvif?: string;
width?: number;
height?: number;
}
const IMAGE_MANIFESTS: Record<string, unknown> = {
"secondary-slider": secondarySliderManifest,
slider: sliderManifest,
};
function normalizeImageDirectory(imageDir: string): string {
const normalized = imageDir.replace(/^\/+|\/+$/g, "");
if (
!normalized ||
normalized.split("/").some((segment) => !segment || segment === "..")
) {
throw new Error(`Invalid PhotoSlider imageDir: ${imageDir}`);
}
return normalized;
}
function isVariant(value: unknown): value is SliderImageVariant {
if (!value || typeof value !== "object") return false;
const variant = value as Partial<SliderImageVariant>;
return (
typeof variant.file === "string" &&
Number.isInteger(variant.width) &&
Number.isInteger(variant.height)
);
}
function isSliderImageMeta(value: unknown): value is SliderImageMeta {
if (!value || typeof value !== "object") return false;
const item = value as Partial<SliderImageMeta>;
return (
typeof item.name === "string" &&
Number.isInteger(item.width) &&
Number.isInteger(item.height) &&
!!item.variants &&
[item.variants.fallback, item.variants.webp, item.variants.avif].every(
(variants) => Array.isArray(variants) && variants.every(isVariant),
) &&
item.variants.fallback.length > 0
);
}
function defaultAltText(name: string): string {
const normalizedName = name.replace(/[-_]+/g, " ").trim();
return normalizedName
? `Bild: ${normalizedName}`
: "Galeriebild";
}
function buildSrcSet(
imageDir: string,
variants: SliderImageVariant[],
): string | undefined {
if (!variants.length) return undefined;
return variants
.map(({ file, width }) => `/images/${imageDir}/${file} ${width}w`)
.join(", ");
}
export async function getSliderImages(imageDir: string): Promise<SliderImage[]> {
const normalizedImageDir = normalizeImageDirectory(imageDir);
const manifest = IMAGE_MANIFESTS[normalizedImageDir];
if (!Array.isArray(manifest)) return [];
const sliderSlug = normalizedImageDir
.replace(/[^a-z0-9]+/gi, "-")
.toLowerCase();
return manifest.filter(isSliderImageMeta).map((item, index) => {
const fallbackFile = item.variants.fallback.find(
({ width, height }) => width === item.width && height === item.height,
)?.file ?? item.variants.fallback.at(-1)!.file;
const publicImagePath = `/images/${normalizedImageDir}/${fallbackFile}`;
if (!item.alt?.trim()) {
console.warn(
`[PhotoSlider] Missing alt text for ${normalizedImageDir}/${fallbackFile}; using fallback text.`,
);
}
return {
id: `${sliderSlug}-${index + 1}`,
src: publicImagePath,
alt: item.alt?.trim() || defaultAltText(item.name),
srcSet: buildSrcSet(normalizedImageDir, item.variants.fallback) ?? publicImagePath,
srcSetWebp: buildSrcSet(normalizedImageDir, item.variants.webp),
srcSetAvif: buildSrcSet(normalizedImageDir, item.variants.avif),
width: item.width,
height: item.height,
};
});
}
+39
View File
@@ -0,0 +1,39 @@
const DEFAULT_APP_URL = "https://example.com";
function readEnvironment(name: string, fallback: string): string {
return process.env[name]?.trim() || fallback;
}
function normalizeSiteUrl(value: string | undefined): string {
const trimmed = value?.trim();
if (!trimmed) return DEFAULT_APP_URL;
try {
const normalized = new URL(trimmed);
if (!["http:", "https:"].includes(normalized.protocol)) return DEFAULT_APP_URL;
normalized.pathname = normalized.pathname.replace(/\/+$/, "");
return normalized.toString().replace(/\/$/, "");
} catch {
return DEFAULT_APP_URL;
}
}
export const SITE_NAME = readEnvironment("APP_NAME", "Example Website");
export const SITE_URL = normalizeSiteUrl(process.env.APP_URL);
export const COMPANY_NAME = readEnvironment("COMPANY_NAME", "Example Company");
export const CONTACT_EMAIL = readEnvironment("CONTACT_EMAIL", "info@example.com");
export const CONTACT_PHONE = readEnvironment("CONTACT_PHONE", "+49 000 000000");
export const CONTACT_ADDRESS = readEnvironment(
"CONTACT_ADDRESS",
"Example Street 1, 12345 Example City",
);
export function toAbsoluteUrl(pathname: string): string {
if (/^https?:\/\//i.test(pathname)) return pathname;
const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
return `${SITE_URL}${normalized}`;
}
export function toPhoneUrl(phone: string): string {
return `tel:${phone.replace(/[^+\d]/g, "")}`;
}
+39
View File
@@ -0,0 +1,39 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export function proxy(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
const development = process.env.NODE_ENV === "development";
const localRequest = ["localhost", "127.0.0.1", "::1"].includes(request.nextUrl.hostname);
const csp = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${development ? " 'unsafe-eval'" : ""};
style-src 'self' 'nonce-${nonce}';
img-src 'self' data:;
font-src 'self';
connect-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
${development || localRequest ? "" : "upgrade-insecure-requests;"}
`.replace(/\s{2,}/g, " ").trim();
const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-nonce", nonce);
requestHeaders.set("Content-Security-Policy", csp);
const response = NextResponse.next({ request: { headers: requestHeaders } });
response.headers.set("Content-Security-Policy", csp);
return response;
}
export const config = {
matcher: [
{
source: "/((?!api|health|_next/static|_next/image|images|fonts|downloads|favicon.ico|logo.svg).*)",
missing: [
{ type: "header", key: "next-router-prefetch" },
{ type: "header", key: "purpose", value: "prefetch" },
],
},
],
};
+167
View File
@@ -0,0 +1,167 @@
import { describe, expect, it, vi } from "vitest";
import { fetchIcsWithLimit } from "../calendar/calendar-fetcher";
import { loadAppConfig, loadCalendarConfig } from "../calendar/config";
import {
CalendarConfigurationError,
CalendarParseError,
CalendarTooLargeError,
CalendarUpstreamError,
} from "../calendar/errors";
import { resolveClientIp, resolveRequestId } from "../calendar/http";
describe("calendar configuration", () => {
it("does not require CALENDAR_URL while loading build-safe app settings", () => {
expect(loadAppConfig({}).calendarUrl).toBeUndefined();
expect(() => loadCalendarConfig({})).toThrow(CalendarConfigurationError);
});
it("parses lists and validates defensive bounds", () => {
const config = loadCalendarConfig({
CALENDAR_URL: "https://example.com/calendar.ics",
TRUSTED_PROXIES: '["10.0.0.0/8", "fd00::/8"]',
ROUTINE_EVENT_TITLES: "regeltermin, wochentermin",
});
expect(config.trustedProxies).toEqual(["10.0.0.0/8", "fd00::/8"]);
expect(config.routineEventTitles).toEqual(["regeltermin", "wochentermin"]);
expect(() => loadCalendarConfig({
CALENDAR_URL: "https://example.com/calendar.ics",
CALENDAR_CACHE_DURATION_MS: "0",
})).toThrow(CalendarConfigurationError);
});
it("requires HTTPS except for loopback test fixtures", () => {
expect(loadCalendarConfig({
CALENDAR_URL: "https://calendar.example.com/calendar.ics",
}).calendarUrl).toBe("https://calendar.example.com/calendar.ics");
expect(loadCalendarConfig({
CALENDAR_URL: "http://127.0.0.1:3101/calendar.ics",
}).calendarUrl).toBe("http://127.0.0.1:3101/calendar.ics");
expect(loadCalendarConfig({
CALENDAR_URL: "http://localhost:3101/calendar.ics",
}).calendarUrl).toBe("http://localhost:3101/calendar.ics");
expect(() => loadCalendarConfig({
CALENDAR_URL: "http://calendar.example.com/calendar.ics",
})).toThrow(/CALENDAR_URL Expected an HTTPS URL/);
expect(() => loadCalendarConfig({
CALENDAR_URL: "http://10.0.0.10/calendar.ics",
})).toThrow(/CALENDAR_URL Expected an HTTPS URL/);
});
});
describe("streaming calendar fetch", () => {
it("rejects upstream status, oversized data and invalid UTF-8", async () => {
const upstream = vi.fn<typeof fetch>().mockResolvedValue(new Response("no", { status: 503 }));
const oversized = vi.fn<typeof fetch>().mockResolvedValue(new Response("x".repeat(17_000)));
const invalid = vi.fn<typeof fetch>().mockResolvedValue(
new Response(Uint8Array.from([0xff, 0xfe]).buffer),
);
await expect(fetchIcsWithLimit("https://example.com", 1_000, 16_384, upstream))
.rejects.toBeInstanceOf(CalendarUpstreamError);
await expect(fetchIcsWithLimit("https://example.com", 1_000, 16_384, oversized))
.rejects.toBeInstanceOf(CalendarTooLargeError);
await expect(fetchIcsWithLimit("https://example.com", 1_000, 16_384, invalid))
.rejects.toBeInstanceOf(CalendarParseError);
await expect(fetchIcsWithLimit("https://example.com", 1_000, 16_384, upstream))
.rejects.toMatchObject({
message: "Calendar request failed with status 503",
statusCode: 502,
errorCode: "calendar_upstream_error",
});
});
it("accepts the exact byte limit and rejects the first oversized stream chunk", async () => {
const responseFromChunks = (...chunks: number[][]) => new Response(new ReadableStream({
start(controller) {
for (const chunk of chunks) controller.enqueue(Uint8Array.from(chunk));
controller.close();
},
}));
const exact = vi.fn<typeof fetch>().mockResolvedValue(responseFromChunks([97, 98], [99, 100]));
const oversized = vi.fn<typeof fetch>().mockResolvedValue(responseFromChunks([97, 98], [99, 100, 101]));
await expect(fetchIcsWithLimit("https://example.com", 1_000, 4, exact)).resolves.toBe("abcd");
await expect(fetchIcsWithLimit("https://example.com", 1_000, 4, oversized))
.rejects.toMatchObject({
message: "Calendar feed exceeded configured size limit",
statusCode: 413,
errorCode: "calendar_too_large",
});
});
it("rejects a declared oversized payload before reading its body", async () => {
let cancelled = false;
const body = new ReadableStream({
cancel() {
cancelled = true;
},
});
const fetchImplementation = vi.fn<typeof fetch>().mockResolvedValue(new Response(body, {
headers: { "content-length": "5" },
}));
await expect(fetchIcsWithLimit("https://example.com", 1_000, 4, fetchImplementation))
.rejects.toBeInstanceOf(CalendarTooLargeError);
expect(cancelled).toBe(true);
});
it("aborts a timed-out request", async () => {
const pendingFetch = vi.fn<typeof fetch>((_input, init) => new Promise((_resolve, reject) => {
init?.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")));
}));
await expect(fetchIcsWithLimit("https://example.com", 5, 16_384, pendingFetch))
.rejects.toMatchObject({
message: "Calendar request timed out",
statusCode: 504,
errorCode: "calendar_timeout",
});
});
it("does not follow calendar redirects", async () => {
const redirected = vi.fn<typeof fetch>(async (_input, init) => {
expect(init?.redirect).toBe("error");
throw new TypeError("redirect mode is set to error");
});
await expect(fetchIcsWithLimit("https://example.com", 1_000, 16_384, redirected))
.rejects.toBeInstanceOf(CalendarUpstreamError);
});
it("rejects redirect responses and missing response bodies as upstream failures", async () => {
const redirect = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, {
status: 302,
headers: { location: "https://elsewhere.example/calendar.ics" },
}));
const emptyBody = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 200 }));
await expect(fetchIcsWithLimit("https://example.com", 1_000, 16_384, redirect))
.rejects.toMatchObject({ message: "Calendar request failed with status 302" });
await expect(fetchIcsWithLimit("https://example.com", 1_000, 16_384, emptyBody))
.rejects.toMatchObject({ message: "Calendar request failed" });
});
});
describe("request identity", () => {
it("only accepts forwarded addresses from a trusted server-owned peer", () => {
const trusted = new Request("http://localhost/api/events", {
headers: { "x-forwarded-for": "198.51.100.7, 10.0.0.1" },
}) as Request & { ip?: string };
trusted.ip = "10.0.0.1";
const untrusted = new Request("http://localhost/api/events", {
headers: { "x-forwarded-for": "198.51.100.7" },
}) as Request & { ip?: string };
untrusted.ip = "203.0.113.42";
expect(resolveClientIp(trusted, ["10.0.0.0/8"])).toBe("198.51.100.7");
expect(resolveClientIp(untrusted, ["10.0.0.0/8"])).toBe("203.0.113.42");
expect(resolveClientIp(new Request("http://localhost"), ["10.0.0.0/8"])).toBe("127.0.0.1");
});
it("preserves only safe request IDs", () => {
expect(resolveRequestId("req-123")).toBe("req-123");
expect(resolveRequestId("x".repeat(129))).not.toBe("x".repeat(129));
});
});
+140
View File
@@ -0,0 +1,140 @@
import { Temporal } from "@js-temporal/polyfill";
import { describe, expect, it, vi } from "vitest";
import { CalendarParseError, CalendarTooLargeError } from "../calendar/errors";
import { EventsService, setEventsServiceForTests } from "../calendar/events-service";
import { readinessResponse } from "../calendar/readiness";
import { BASE_ICS, calendarResponse, instant, makeConfig } from "./test-helpers";
describe("EventsService", () => {
it("deduplicates inflight fetches and serves the fresh cache", async () => {
const fetchImplementation = vi.fn<typeof fetch>().mockResolvedValue(calendarResponse(BASE_ICS));
const service = new EventsService({ config: makeConfig(), fetchImplementation, now: instant() });
const [first, second] = await Promise.all([service.getEvents(), service.getEvents()]);
const cached = await service.getEvents();
expect(fetchImplementation).toHaveBeenCalledTimes(1);
expect(first).toEqual(second);
expect(cached).toEqual(first);
expect(first).toHaveLength(1);
});
it("serves a non-empty stale cache after an upstream failure", async () => {
const fetchImplementation = vi.fn<typeof fetch>()
.mockResolvedValueOnce(calendarResponse(BASE_ICS))
.mockRejectedValueOnce(new Error("upstream down"));
const service = new EventsService({ config: makeConfig(), fetchImplementation, now: instant() });
await service.getEvents();
service.expireCache();
await expect(service.getEvents()).resolves.toHaveLength(1);
expect(service.lastError).toBe("Calendar request failed");
});
it("serves a successfully synchronized empty stale cache after an upstream failure", async () => {
const emptyCalendar = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nEND:VCALENDAR\r\n";
const fetchImplementation = vi.fn<typeof fetch>()
.mockResolvedValueOnce(calendarResponse(emptyCalendar))
.mockRejectedValueOnce(new Error("upstream down"));
const service = new EventsService({ config: makeConfig(), fetchImplementation, now: instant() });
await expect(service.getEvents()).resolves.toEqual([]);
service.expireCache();
await expect(service.getEvents()).resolves.toEqual([]);
expect(fetchImplementation).toHaveBeenCalledTimes(2);
expect(service.lastError).toBe("Calendar request failed");
});
it("rejects oversized and non-UTF-8 feeds", async () => {
const oversized = new EventsService({
config: makeConfig({ maxIcsBytes: 16_384 }),
fetchImplementation: vi.fn<typeof fetch>().mockResolvedValue(calendarResponse("x".repeat(16_385))),
now: instant(),
});
const invalidUtf8 = new EventsService({
config: makeConfig(),
fetchImplementation: vi.fn<typeof fetch>().mockResolvedValue(calendarResponse(new Uint8Array([0xff, 0xfe]))),
now: instant(),
});
await expect(oversized.getEvents()).rejects.toBeInstanceOf(CalendarTooLargeError);
await expect(invalidUtf8.getEvents()).rejects.toBeInstanceOf(CalendarParseError);
});
it("sanitizes fields and marks routine titles case-insensitively", async () => {
const malicious = BASE_ICS
.replace("SUMMARY:Regeltermin", "SUMMARY:<script>Regeltermin</script>")
.replace("DTSTART", "DESCRIPTION:<b>Text</b>\nLOCATION:<img src=x>\nDTSTART");
const service = new EventsService({
config: makeConfig(),
fetchImplementation: vi.fn<typeof fetch>().mockResolvedValue(calendarResponse(malicious)),
now: instant(),
});
const [event] = await service.getEvents();
expect(event.title).toContain("&lt;script&gt;");
expect(event.description).toContain("&lt;b&gt;");
expect(event.location).toContain("&lt;img");
expect(event.special).toBe(true);
});
it("filters configured routine titles and limits special events to the first three", async () => {
const event = (uid: string, title: string, hour: string) => `BEGIN:VEVENT
UID:${uid}
SUMMARY:${title}
DTSTART;TZID=Europe/Berlin:20991231T${hour}0000
DTEND;TZID=Europe/Berlin:20991231T${hour}3000
END:VEVENT`;
const ics = `BEGIN:VCALENDAR
VERSION:2.0
${event("routine-1", " Regeltermin ", "09")}
${event("routine-2", "WOCHENTERMIN", "10")}
${event("special-1", "Aktion 1", "11")}
${event("special-2", "Aktion 2", "12")}
${event("special-3", "Aktion 3", "13")}
${event("special-4", "Aktion 4", "14")}
END:VCALENDAR`;
const service = new EventsService({
config: makeConfig({ routineEventTitles: ["regeltermin", "wochentermin"] }),
fetchImplementation: vi.fn<typeof fetch>().mockResolvedValue(calendarResponse(ics)),
now: instant(),
});
const allEvents = await service.getEvents();
const specialEvents = await service.getSpecialEvents();
expect(allEvents).toHaveLength(6);
expect(allEvents.filter((item) => !item.special).map((item) => item.id)).toEqual([
"routine-1",
"routine-2",
]);
expect(specialEvents.map((item) => item.id)).toEqual(["special-1", "special-2", "special-3"]);
});
it("reports cache readiness and degrades after 24 hours", async () => {
let current = Temporal.Instant.from("2099-01-01T00:00:00Z");
const service = new EventsService({
config: makeConfig(),
fetchImplementation: vi.fn<typeof fetch>().mockImplementation(async () => calendarResponse(BASE_ICS)),
now: () => current,
});
expect(service.getCacheHealth().statusCode).toBe(503);
await service.getEvents();
expect(service.getCacheHealth()).toEqual({
statusCode: 200,
payload: { status: "ok", reason: null },
});
current = current.add({ hours: 25 });
expect(service.getCacheHealth()).toEqual({
statusCode: 503,
payload: { status: "degraded", reason: "cache older than 24h (age: 25h 0m)" },
});
setEventsServiceForTests(service);
expect(readinessResponse().status).toBe(503);
await vi.waitFor(() => expect(service.getCacheHealth().statusCode).toBe(200));
setEventsServiceForTests(undefined);
});
});
@@ -0,0 +1,124 @@
import { Temporal } from "@js-temporal/polyfill";
import { describe, expect, it } from "vitest";
import {
buildEventsEtag,
buildPublicEvents,
sanitizeIcsText,
} from "../calendar/events-transformer";
import { parseIcsEvents } from "../calendar/ics-parser";
import type { PublicEvent } from "../calendar/types";
function transform(ics: string, now = "2025-03-01T18:00:00+01:00[Europe/Berlin]") {
return buildPublicEvents(
parseIcsEvents(ics, "Europe/Berlin"),
Temporal.ZonedDateTime.from(now),
12,
500,
"Europe/Berlin",
() => true,
);
}
describe("public event transformation", () => {
it("deduplicates title/start/end while retaining distant single events", () => {
const events = transform(`BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:first
SUMMARY:Identisch
DTSTART;TZID=Europe/Berlin:20250302T100000
DTEND;TZID=Europe/Berlin:20250302T110000
END:VEVENT
BEGIN:VEVENT
UID:duplicate
SUMMARY:Identisch
DTSTART;TZID=Europe/Berlin:20250302T100000
DTEND;TZID=Europe/Berlin:20250302T110000
END:VEVENT
BEGIN:VEVENT
UID:distant
SUMMARY:Weit entfernt
DTSTART;TZID=Europe/Berlin:21990101T100000
DTEND;TZID=Europe/Berlin:21990101T110000
END:VEVENT
END:VCALENDAR`);
expect(events.map((event) => event.id)).toEqual(["first", "distant"]);
});
it("retains already-ended events from today but removes older events", () => {
const events = transform(`BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:today
SUMMARY:Heute beendet
DTSTART;TZID=Europe/Berlin:20250301T100000
DTEND;TZID=Europe/Berlin:20250301T110000
END:VEVENT
BEGIN:VEVENT
UID:yesterday
SUMMARY:Gestern beendet
DTSTART;TZID=Europe/Berlin:20250228T100000
DTEND;TZID=Europe/Berlin:20250228T110000
END:VEVENT
END:VCALENDAR`);
expect(events.map((event) => event.id)).toEqual(["today"]);
});
it("escapes HTML and preserves decoded ICS escapes", () => {
const [event] = transform(`BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:escaped
SUMMARY:A & <tag> "quote" 'apostrophe'
DESCRIPTION:Line 1\\nLine 2\\, semicolon\\; slash\\\\ & <b>
LOCATION:<place> & "hut"
DTSTART;TZID=Europe/Berlin:20250302T100000
DTEND;TZID=Europe/Berlin:20250302T110000
END:VEVENT
END:VCALENDAR`);
expect(event).toMatchObject({
title: "A &amp; &lt;tag&gt; &quot;quote&quot; &#x27;apostrophe&#x27;",
description: "Line 1\nLine 2, semicolon; slash\\ &amp; &lt;b&gt;",
location: "&lt;place&gt; &amp; &quot;hut&quot;",
});
expect(sanitizeIcsText(null)).toBeNull();
});
it("serializes UTC timestamps with Z like Pydantic", () => {
const [event] = transform(`BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:utc
SUMMARY:UTC event
DTSTART:20250302T100000Z
DTEND:20250302T110000Z
END:VEVENT
END:VCALENDAR`);
expect(event.start).toBe("2025-03-02T10:00:00Z");
expect(event.end).toBe("2025-03-02T11:00:00Z");
expect(event.timeZone).toBe("UTC");
});
});
describe("event ETags", () => {
it("hashes the exact compact UTF-8 JSON shape and separates special queries", () => {
const events: PublicEvent[] = [{
id: "ä-1",
title: "Termin &amp; Treffen",
description: null,
location: "Beispielort",
start: "2025-03-02T10:00:00+01:00",
end: "2025-03-02T11:00:00+01:00",
allDay: false,
timeZone: "Europe/Berlin",
special: true,
}];
expect(buildEventsEtag(events)).toBe("4c5b6a8244db17058de3fcbd8ed4393931706a1af4eb9159c5554510714d1aa7");
expect(buildEventsEtag(events, true)).toBe("c2440dd450050ba2154eaf56b4aae537d4bb7613ee0cd2d8e80d83de783b0dbe");
});
});
+298
View File
@@ -0,0 +1,298 @@
import { Temporal } from "@js-temporal/polyfill";
import { describe, expect, it, vi } from "vitest";
import { buildPublicEvents } from "../calendar/events-transformer";
import { expandRecurringEvents, parseIcsEvents } from "../calendar/ics-parser";
const SINGLE_EVENT_ICS = `BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:1
SUMMARY:Regeltermin
DTSTART;TZID=Europe/Berlin:20250301T180000
DTEND;TZID=Europe/Berlin:20250301T200000
END:VEVENT
END:VCALENDAR
`;
const DST_ICS = `BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Test//Test//EN
BEGIN:VEVENT
UID:regeltermin-dst
SUMMARY:Regeltermin
DTSTART;TZID=Europe/Berlin:20250307T160000
DTEND;TZID=Europe/Berlin:20250307T190000
RRULE:FREQ=WEEKLY;COUNT=6
END:VEVENT
END:VCALENDAR
`;
const EXDATE_RDATE_ICS = `BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Test//Test//EN
BEGIN:VEVENT
UID:exceptions
SUMMARY:Probe
DTSTART;TZID=Europe/Berlin:20250307T160000
DTEND;TZID=Europe/Berlin:20250307T190000
RRULE:FREQ=WEEKLY;COUNT=4
EXDATE;VALUE=DATE:20250314
EXDATE;TZID=Europe/Berlin:20250321T160000
RDATE;TZID=Europe/Berlin:20250404T160000
END:VEVENT
END:VCALENDAR
`;
function window() {
return {
start: Temporal.ZonedDateTime.from("2025-03-01T00:00:00+01:00[Europe/Berlin]"),
end: Temporal.ZonedDateTime.from("2025-04-30T23:59:59+02:00[Europe/Berlin]"),
};
}
describe("ICS recurrence expansion", () => {
it("parses a single event in its declared timezone", () => {
const [event] = parseIcsEvents(SINGLE_EVENT_ICS, "Europe/Berlin");
expect(event).toMatchObject({
uid: "1",
title: "Regeltermin",
allDay: false,
timeZone: "Europe/Berlin",
});
expect(event.start.toString()).toBe("2025-03-01T18:00:00+01:00[Europe/Berlin]");
expect(event.end.toString()).toBe("2025-03-01T20:00:00+01:00[Europe/Berlin]");
});
it("preserves Europe/Berlin wallclock time across DST", () => {
const parsed = parseIcsEvents(DST_ICS, "Europe/Berlin");
const range = window();
const expanded = expandRecurringEvents(parsed, range.start, range.end, 10, "Europe/Berlin");
expect(expanded).toHaveLength(6);
expect(expanded.map((event) => event.start.hour)).toEqual([16, 16, 16, 16, 16, 16]);
expect(expanded.map((event) => event.end.hour)).toEqual([19, 19, 19, 19, 19, 19]);
expect(expanded.at(-1)?.start.offset).toBe("+02:00");
});
it("applies date-only and datetime EXDATE plus RDATE", () => {
const parsed = parseIcsEvents(EXDATE_RDATE_ICS, "Europe/Berlin");
const range = window();
const expanded = expandRecurringEvents(parsed, range.start, range.end, 10, "Europe/Berlin");
expect(expanded.map((event) => event.start.toPlainDate().toString())).toEqual([
"2025-03-07",
"2025-03-28",
"2025-04-04",
]);
});
it("bounds dense recurrence rules before materializing the full window", () => {
const dense = DST_ICS
.replace("FREQ=WEEKLY;COUNT=6", "FREQ=MINUTELY;COUNT=100000")
.replace("20250307T190000", "20250307T161000");
const parsed = parseIcsEvents(dense, "Europe/Berlin");
const range = window();
const expanded = expandRecurringEvents(parsed, range.start, range.end, 3, "Europe/Berlin");
expect(expanded).toHaveLength(3);
expect(expanded.map((event) => event.start.minute)).toEqual([0, 1, 2]);
});
});
describe("ICS event forms", () => {
it("keeps all-day end dates exclusive, including multi-day events", () => {
const parsed = parseIcsEvents(`BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:one-day
SUMMARY:Aktionstag
DTSTART;VALUE=DATE:20250301
DTEND;VALUE=DATE:20250302
END:VEVENT
BEGIN:VEVENT
UID:multi-day
SUMMARY:Ganztagstermin
DTSTART;VALUE=DATE:20250310
DTEND;VALUE=DATE:20250315
END:VEVENT
END:VCALENDAR`, "Europe/Berlin");
expect(parsed.map((event) => ({
allDay: event.allDay,
start: event.start.toPlainDate().toString(),
end: event.end.toPlainDate().toString(),
}))).toEqual([
{ allDay: true, start: "2025-03-01", end: "2025-03-02" },
{ allDay: true, start: "2025-03-10", end: "2025-03-15" },
]);
});
it("uses UTC for Z timestamps and the default timezone for floating timestamps", () => {
const parsed = parseIcsEvents(`BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:utc
SUMMARY:UTC
DTSTART:20250301T100000Z
DTEND:20250301T110000Z
END:VEVENT
BEGIN:VEVENT
UID:floating
SUMMARY:Floating
DTSTART:20250301T100000
DTEND:20250301T110000
END:VEVENT
END:VCALENDAR`, "Europe/Berlin");
expect(parsed[0]?.timeZone).toBe("UTC");
expect(parsed[0]?.start.toString()).toBe("2025-03-01T10:00:00+00:00[UTC]");
expect(parsed[1]?.timeZone).toBe("Europe/Berlin");
expect(parsed[1]?.start.toString()).toBe("2025-03-01T10:00:00+01:00[Europe/Berlin]");
});
it("defaults a missing DTEND, generates a missing UID and skips a missing SUMMARY", () => {
const parsed = parseIcsEvents(`BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SUMMARY:Ohne Ende
DTSTART;TZID=Europe/Berlin:20250301T100000
END:VEVENT
BEGIN:VEVENT
UID:no-summary
DTSTART;TZID=Europe/Berlin:20250301T120000
END:VEVENT
END:VCALENDAR`, "Europe/Berlin");
expect(parsed).toHaveLength(1);
expect(parsed[0]?.end.equals(parsed[0].start)).toBe(true);
expect(parsed[0]?.uid).toBe("2025-03-01T10:00:00+01:00-Ohne Ende");
});
it("ignores date-only RDATE values", () => {
const parsed = parseIcsEvents(EXDATE_RDATE_ICS.replace(
"RDATE;TZID=Europe/Berlin:20250404T160000",
"RDATE;VALUE=DATE:20250404",
), "Europe/Berlin");
const range = window();
expect(expandRecurringEvents(parsed, range.start, range.end, 10, "Europe/Berlin")
.map((event) => event.start.toPlainDate().toString())).toEqual([
"2025-03-07",
"2025-03-28",
]);
});
it("isolates malformed RRULE and unknown TZID events from valid siblings", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
const parsed = parseIcsEvents(`BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:bad-rule
SUMMARY:Bad rule
DTSTART:20250301T100000Z
RRULE:FREQ=NOPE
END:VEVENT
BEGIN:VEVENT
UID:bad-zone
SUMMARY:Bad zone
DTSTART;TZID=Custom/Camp:20250301T100000
END:VEVENT
BEGIN:VEVENT
UID:valid
SUMMARY:Valid
DTSTART;TZID=Europe/Berlin:20250301T100000
END:VEVENT
END:VCALENDAR`, "Europe/Berlin");
expect(parsed.map((event) => event.uid)).toEqual(["valid"]);
expect(warn).toHaveBeenCalledTimes(2);
warn.mockRestore();
});
});
describe("ICS cancellations and recurrence overrides", () => {
it("removes cancelled series and individual cancelled occurrences", () => {
const parsed = parseIcsEvents(`BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:cancelled-series
SUMMARY:Abgesagt
DTSTART;TZID=Europe/Berlin:20250301T100000
STATUS:CANCELLED
END:VEVENT
BEGIN:VEVENT
UID:series
SUMMARY:Probe
DTSTART;TZID=Europe/Berlin:20250307T160000
DTEND;TZID=Europe/Berlin:20250307T170000
RRULE:FREQ=WEEKLY;COUNT=3
END:VEVENT
BEGIN:VEVENT
UID:series
RECURRENCE-ID;TZID=Europe/Berlin:20250314T160000
STATUS:CANCELLED
END:VEVENT
END:VCALENDAR`, "Europe/Berlin");
const range = window();
expect(parsed.map((event) => event.uid)).toEqual(["series"]);
expect(expandRecurringEvents(parsed, range.start, range.end, 10, "Europe/Berlin")
.map((event) => event.start.toPlainDate().toString())).toEqual([
"2025-03-07",
"2025-03-21",
]);
});
it("replaces one recurrence with its detached override", () => {
const parsed = parseIcsEvents(`BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:series
SUMMARY:Probe
DTSTART;TZID=Europe/Berlin:20250307T160000
DTEND;TZID=Europe/Berlin:20250307T170000
RRULE:FREQ=WEEKLY;COUNT=3
END:VEVENT
BEGIN:VEVENT
UID:series
RECURRENCE-ID;TZID=Europe/Berlin:20250314T160000
SUMMARY:Probe verschoben
DTSTART;TZID=Europe/Berlin:20250315T180000
DTEND;TZID=Europe/Berlin:20250315T190000
END:VEVENT
END:VCALENDAR`, "Europe/Berlin");
const range = window();
const generated = expandRecurringEvents(parsed, range.start, range.end, 10, "Europe/Berlin");
expect(generated.map((event) => event.start.toPlainDate().toString())).toEqual([
"2025-03-07",
"2025-03-21",
]);
expect(parsed.find((event) => event.title === "Probe verschoben")?.recurrenceRule).toBeNull();
expect(buildPublicEvents(
parsed,
range.start,
2,
10,
"Europe/Berlin",
() => true,
).map((event) => [event.title, event.start])).toEqual([
["Probe", "2025-03-07T16:00:00+01:00"],
["Probe verschoben", "2025-03-15T18:00:00+01:00"],
["Probe", "2025-03-21T16:00:00+01:00"],
]);
});
it("rejects unsupported RANGE=THISANDFUTURE instead of applying it incorrectly", () => {
expect(() => parseIcsEvents(`BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:series
RECURRENCE-ID;RANGE=THISANDFUTURE;TZID=Europe/Berlin:20250314T160000
SUMMARY:Neue Zeit
DTSTART;TZID=Europe/Berlin:20250314T180000
END:VEVENT
END:VCALENDAR`, "Europe/Berlin")).toThrow("RANGE=THISANDFUTURE");
});
});
+281
View File
@@ -0,0 +1,281 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { GET as getEvents, OPTIONS as optionsEvents } from "../../app/api/events/route";
import { GET as getLegacyHealth } from "../../app/health/route";
import { GET as getLiveness } from "../../app/health/live/route";
import { GET as getReadiness } from "../../app/health/ready/route";
import { EventsService, setEventsServiceForTests } from "../calendar/events-service";
import { BASE_ICS, calendarResponse, instant, makeConfig } from "./test-helpers";
function request(path: string, headers: HeadersInit = {}): Request {
return new Request(`http://localhost${path}`, { headers: { host: "localhost", ...headers } });
}
afterEach(() => {
setEventsServiceForTests(undefined);
vi.unstubAllEnvs();
});
describe("calendar route handlers", () => {
it("supports strong, weak, multiple and wildcard If-None-Match values", async () => {
vi.stubEnv("CALENDAR_URL", "https://example.com/calendar.ics");
const service = new EventsService({
config: makeConfig(),
fetchImplementation: vi.fn<typeof fetch>().mockResolvedValue(calendarResponse(BASE_ICS)),
now: instant(),
});
setEventsServiceForTests(service);
const initial = await getEvents(request("/api/events"));
const etag = initial.headers.get("etag")!;
const weak = await getEvents(request("/api/events", { "if-none-match": `"other", W/${etag}` }));
const wildcard = await getEvents(request("/api/events", { "if-none-match": "*" }));
expect(initial.status).toBe(200);
expect(initial.headers.get("cache-control")).toContain("stale-while-revalidate=300");
expect(weak.status).toBe(304);
expect(weak.headers.get("etag")).toBe(etag);
expect(await weak.text()).toBe("");
expect(weak.headers.get("cache-control")).toBe(initial.headers.get("cache-control"));
expect(wildcard.status).toBe(304);
});
it("accepts common boolean query forms and uses the final repeated value", async () => {
vi.stubEnv("CALENDAR_URL", "https://example.com/calendar.ics");
const service = new EventsService({
config: makeConfig(),
fetchImplementation: vi.fn<typeof fetch>().mockResolvedValue(calendarResponse(BASE_ICS)),
now: instant(),
});
setEventsServiceForTests(service);
for (const value of ["false", "0", "off", "no"]) {
const response = await getEvents(request(`/api/events?special=${value}`));
expect(await response.json()).toHaveLength(1);
}
for (const value of ["true", "1", "on", "yes"]) {
const response = await getEvents(request(`/api/events?special=${value}`));
expect(await response.json()).toEqual([]);
}
const repeated = await getEvents(request("/api/events?special=true&special=false"));
expect(await repeated.json()).toHaveLength(1);
});
it("returns the exact public JSON shape and distinct all/special ETags", async () => {
vi.stubEnv("CALENDAR_URL", "https://example.com/calendar.ics");
const specialIcs = BASE_ICS
.replace("event-1", "utc-special")
.replace("Regeltermin", "Sondertermin")
.replace("DTSTART;TZID=Europe/Berlin:20991231T180000", "DTSTART:20991231T170000Z")
.replace("DTEND;TZID=Europe/Berlin:20991231T190000", "DTEND:20991231T180000Z");
const service = new EventsService({
config: makeConfig(),
fetchImplementation: vi.fn<typeof fetch>().mockResolvedValue(calendarResponse(specialIcs)),
now: instant(),
});
setEventsServiceForTests(service);
const all = await getEvents(request("/api/events"));
const special = await getEvents(request("/api/events?special=true"));
expect(await all.json()).toEqual([{
id: "utc-special",
title: "Sondertermin",
description: null,
location: null,
start: "2099-12-31T17:00:00Z",
end: "2099-12-31T18:00:00Z",
allDay: false,
timeZone: "UTC",
special: true,
}]);
expect(all.headers.get("content-type")).toContain("application/json");
expect(special.headers.get("etag")).not.toBe(all.headers.get("etag"));
const notModified = await getEvents(request("/api/events?special=true", {
"if-none-match": special.headers.get("etag")!,
}));
expect(notModified.status).toBe(304);
expect(notModified.headers.get("etag")).toBe(special.headers.get("etag"));
});
it("serializes calendar timeout errors with the public status and error code", async () => {
vi.stubEnv("CALENDAR_URL", "https://example.com/calendar.ics");
const pendingFetch = vi.fn<typeof fetch>((_input, init) => new Promise((_resolve, reject) => {
init?.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")));
}));
setEventsServiceForTests(new EventsService({
config: makeConfig({ calendarFetchTimeoutMs: 5 }),
fetchImplementation: pendingFetch,
now: instant(),
}));
const response = await getEvents(request("/api/events"));
expect(response.status).toBe(504);
expect(await response.json()).toEqual({
detail: "Calendar request timed out",
error: "calendar_timeout",
});
});
it("keeps liveness independent and readiness compatible on both paths", async () => {
vi.stubEnv("CALENDAR_URL", "https://example.com/calendar.ics");
const service = new EventsService({
config: makeConfig(),
fetchImplementation: vi.fn<typeof fetch>().mockRejectedValue(new Error("offline")),
now: instant(),
});
setEventsServiceForTests(service);
const live = await getLiveness(request("/health/live"));
const ready = await getReadiness(request("/health/ready"));
const legacy = await getLegacyHealth(request("/health"));
expect(live.status).toBe(200);
expect(await live.json()).toEqual({ status: "ok" });
expect(ready.status).toBe(503);
expect(await ready.json()).toEqual({
status: "starting",
reason: "calendar synchronization in progress",
});
expect(legacy.status).toBe(503);
});
it("reports ready after a successful synchronization", async () => {
vi.stubEnv("CALENDAR_URL", "https://example.com/calendar.ics");
const service = new EventsService({
config: makeConfig(),
fetchImplementation: vi.fn<typeof fetch>().mockResolvedValue(calendarResponse(BASE_ICS)),
now: instant(),
});
await service.getEvents();
setEventsServiceForTests(service);
const response = await getReadiness(request("/health/ready"));
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ status: "ok", reason: null });
});
it("rejects invalid query booleans and unknown hosts with JSON errors", async () => {
vi.stubEnv("CALENDAR_URL", "https://example.com/calendar.ics");
const invalidQuery = await getEvents(request("/api/events?special=not-a-bool"));
const invalidHost = await getLiveness(new Request("http://evil.example/health/live", {
headers: { host: "evil.example" },
}));
expect(invalidQuery.status).toBe(422);
expect(await invalidQuery.json()).toEqual({
detail: "Request validation failed",
error: "validation_error",
});
expect(invalidHost.status).toBe(400);
expect(await invalidHost.json()).toEqual({ detail: "Invalid host header", error: "invalid_host" });
});
it("allows loopback hosts and applies the complete security-header contract", async () => {
vi.stubEnv("CALENDAR_URL", "https://example.com/calendar.ics");
const response = await getLiveness(new Request("http://127.0.0.1/health/live", {
headers: { host: "127.0.0.1", "x-request-id": "req-123" },
}));
expect(response.status).toBe(200);
expect(Object.fromEntries([
"content-security-policy",
"strict-transport-security",
"cross-origin-resource-policy",
"x-content-type-options",
"x-frame-options",
"referrer-policy",
"permissions-policy",
"cross-origin-opener-policy",
"x-robots-tag",
"x-request-id",
].map((name) => [name, response.headers.get(name)]))).toEqual({
"content-security-policy": "default-src 'self'",
"strict-transport-security": "max-age=31536000; includeSubDomains; preload",
"cross-origin-resource-policy": "same-site",
"x-content-type-options": "nosniff",
"x-frame-options": "DENY",
"referrer-policy": "no-referrer",
"permissions-policy": "geolocation=()",
"cross-origin-opener-policy": "same-origin",
"x-robots-tag": "noindex, noarchive",
"x-request-id": "req-123",
});
});
it("answers CORS preflights for configured origins", async () => {
vi.stubEnv("CALENDAR_URL", "https://example.com/calendar.ics");
vi.stubEnv("CORS_ORIGIN", "https://www.example.com");
const response = await optionsEvents(new Request("http://localhost/api/events", {
method: "OPTIONS",
headers: {
host: "localhost",
origin: "https://www.example.com",
"access-control-request-method": "GET",
"access-control-request-headers": "if-none-match",
},
}));
expect(response.status).toBe(200);
expect(await response.text()).toBe("OK");
expect(response.headers.get("access-control-allow-origin")).toBe("https://www.example.com");
expect(response.headers.get("access-control-allow-methods")).toBe("GET");
expect(response.headers.get("access-control-allow-headers")).toBe("if-none-match");
expect(response.headers.has("access-control-allow-credentials")).toBe(false);
setEventsServiceForTests(new EventsService({
config: makeConfig(),
fetchImplementation: vi.fn<typeof fetch>().mockResolvedValue(calendarResponse(BASE_ICS)),
now: instant(),
}));
const getResponse = await getEvents(request("/api/events", { origin: "https://www.example.com" }));
expect(getResponse.headers.get("access-control-allow-origin")).toBe("https://www.example.com");
expect(getResponse.headers.get("vary")).toContain("Origin");
});
it("does not grant CORS access to an unconfigured origin", async () => {
vi.stubEnv("CALENDAR_URL", "https://example.com/calendar.ics");
vi.stubEnv("CORS_ORIGIN", "https://www.example.com");
const response = await optionsEvents(new Request("http://localhost/api/events", {
method: "OPTIONS",
headers: {
host: "localhost",
origin: "https://evil.example.com",
"access-control-request-method": "GET",
},
}));
expect(response.status).toBe(400);
expect(await response.text()).toBe("Disallowed CORS origin");
expect(response.headers.has("access-control-allow-origin")).toBe(false);
});
it("rejects methods outside the configured CORS contract", async () => {
vi.stubEnv("CALENDAR_URL", "https://example.com/calendar.ics");
vi.stubEnv("CORS_ORIGIN", "https://www.example.com");
const response = await optionsEvents(new Request("http://localhost/api/events", {
method: "OPTIONS",
headers: {
host: "localhost",
origin: "https://www.example.com",
"access-control-request-method": "POST",
},
}));
expect(response.status).toBe(400);
expect(await response.text()).toBe("Disallowed CORS method");
expect(response.headers.get("access-control-allow-methods")).toBe("GET");
});
it("keeps liveness healthy and exposes invalid calendar config as not ready", async () => {
vi.stubEnv("CALENDAR_URL", "ftp://invalid.example/calendar.ics");
const live = await getLiveness(request("/health/live"));
const ready = await getReadiness(request("/health/ready"));
expect(live.status).toBe(200);
expect(await live.json()).toEqual({ status: "ok" });
expect(ready.status).toBe(503);
expect(await ready.json()).toMatchObject({ status: "starting" });
});
});
+32
View File
@@ -0,0 +1,32 @@
import { Temporal } from "@js-temporal/polyfill";
import { loadCalendarConfig } from "../calendar/config";
import type { CalendarRuntimeConfig } from "../calendar/events-service";
export const BASE_ICS = `BEGIN:VCALENDAR\r
VERSION:2.0\r
PRODID:-//Test//Test//EN\r
BEGIN:VEVENT\r
UID:event-1\r
SUMMARY:Regeltermin\r
DTSTART;TZID=Europe/Berlin:20991231T180000\r
DTEND;TZID=Europe/Berlin:20991231T190000\r
END:VEVENT\r
END:VCALENDAR\r
`;
export function makeConfig(overrides: Partial<CalendarRuntimeConfig> = {}): CalendarRuntimeConfig {
return {
...loadCalendarConfig({ CALENDAR_URL: "https://example.com/calendar.ics" }),
...overrides,
};
}
export function instant(value = "2099-01-01T00:00:00Z"): () => Temporal.Instant {
const fixed = Temporal.Instant.from(value);
return () => fixed;
}
export function calendarResponse(body: string | Uint8Array, status = 200): Response {
const responseBody = typeof body === "string" ? body : Uint8Array.from(body).buffer;
return new Response(responseBody, { status });
}
+22
View File
@@ -0,0 +1,22 @@
# Calendar runtime notes
The Next.js hosting model has these operational characteristics:
- Cache and inflight fetches are process-local `globalThis` singletons. They are not shared between
Next.js workers or instances and disappear on process restart.
- There is no periodic background refresh. Route handlers have no reliable application lifespan for
long-running timers, so refreshes happen lazily after the configured TTL. Readiness starts a
non-blocking initial warmup, and stale data is still served after refresh errors.
- Current Next.js route-handler requests do not expose the Node socket peer address. The public API
rate limit is therefore enforced by the trusted Traefik entrypoint instead of trusting spoofable
forwarded headers in application code.
- Trusted-host checks, request IDs, CORS response headers and security headers are implemented in the
calendar and health handlers. They are not global middleware for unrelated Next.js routes.
- Readiness reports missing or invalid runtime calendar configuration as `503 starting`. Runtime
validation keeps `CALENDAR_URL` out of the build and image layers.
- Calendar feeds require HTTPS. Plain HTTP is accepted only for loopback addresses so the local
production-mode E2E fixture can run without weakening external calendar transport security.
- The Compose runtime uses a read-only root filesystem, drops all Linux capabilities, forbids
privilege escalation and exposes only a size-limited `/tmp` filesystem for temporary writes.
- IANA zones such as `Europe/Berlin` use Temporal's runtime time-zone data. Arbitrary custom
`VTIMEZONE` definitions whose TZID is not recognized by Temporal are rejected as parse failures.
+71
View File
@@ -0,0 +1,71 @@
import {
CalendarError,
CalendarParseError,
CalendarTimeoutError,
CalendarTooLargeError,
CalendarUpstreamError,
} from "./errors";
export async function fetchIcsWithLimit(
calendarUrl: string,
timeoutMs: number,
maxIcsBytes: number,
fetchImplementation: typeof fetch = fetch,
): Promise<string> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetchImplementation(calendarUrl, {
method: "GET",
cache: "no-store",
redirect: "error",
signal: controller.signal,
});
if (response.status !== 200) {
throw new CalendarUpstreamError(`Calendar request failed with status ${response.status}`);
}
const declaredSize = Number(response.headers.get("content-length"));
if (Number.isFinite(declaredSize) && declaredSize > maxIcsBytes) {
await response.body?.cancel();
throw new CalendarTooLargeError("Calendar feed exceeded configured size limit");
}
if (!response.body) throw new CalendarUpstreamError("Calendar request failed");
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let size = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > maxIcsBytes) {
await reader.cancel();
throw new CalendarTooLargeError("Calendar feed exceeded configured size limit");
}
chunks.push(value);
}
const payload = new Uint8Array(size);
let offset = 0;
for (const chunk of chunks) {
payload.set(chunk, offset);
offset += chunk.byteLength;
}
try {
return new TextDecoder("utf-8", { fatal: true }).decode(payload);
} catch (error) {
throw new CalendarParseError("Calendar feed was not valid UTF-8", { cause: error });
}
} catch (error) {
if (error instanceof CalendarError) throw error;
if (controller.signal.aborted || (error instanceof Error && error.name === "AbortError")) {
throw new CalendarTimeoutError("Calendar request timed out", { cause: error });
}
throw new CalendarUpstreamError("Calendar request failed", { cause: error });
} finally {
clearTimeout(timeout);
}
}
+148
View File
@@ -0,0 +1,148 @@
import { z } from "zod";
import { CalendarConfigurationError } from "./errors";
const integerFromEnvironment = (minimum: number, maximum: number, fallback: number) =>
z.preprocess(
(value) => (value === undefined || value === "" ? fallback : Number(value)),
z.number().int().min(minimum).max(maximum),
);
function stringList(value: unknown, fallback: string[]): string[] {
if (Array.isArray(value)) {
return value.map(String).map((item) => item.trim()).filter(Boolean);
}
if (value === undefined || value === null || value === "") return fallback;
const raw = String(value);
if (raw.trim().startsWith("[")) {
try {
const parsed: unknown = JSON.parse(raw);
if (Array.isArray(parsed)) {
return parsed.map(String).map((item) => item.trim()).filter(Boolean);
}
} catch {
// CSV parsing below produces a useful, deterministic result for malformed JSON.
}
}
return raw.split(",").map((item) => item.trim()).filter(Boolean);
}
const httpUrl = z.string().trim().url().refine((value) => {
const protocol = new URL(value).protocol;
return protocol === "http:" || protocol === "https:";
}, "Expected an HTTP(S) URL");
const calendarUrl = httpUrl.refine((value) => {
const url = new URL(value);
return url.protocol === "https:" ||
["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
}, "Expected an HTTPS URL (HTTP is allowed only for loopback test fixtures)");
const environmentSchema = z.object({
CORS_ORIGIN: z.string().default(""),
TRUSTED_PROXIES: z.preprocess((value) => stringList(value, []), z.array(z.string())),
APP_URL: httpUrl.default("https://example.com"),
CALENDAR_URL: calendarUrl.optional(),
CALENDAR_CACHE_DURATION_MS: integerFromEnvironment(1_000, 60 * 60 * 1_000, 10 * 60 * 1_000),
CALENDAR_FETCH_TIMEOUT_MS: integerFromEnvironment(1_000, 60 * 60 * 1_000, 10 * 1_000),
DEFAULT_CALENDAR_TIMEZONE: z.string().default("Europe/Berlin").refine((value) => {
try {
new Intl.DateTimeFormat("de-DE", { timeZone: value }).format();
return true;
} catch {
return false;
}
}, "Expected a supported IANA time zone"),
MAX_RECURRENCE_WINDOW_MONTHS: integerFromEnvironment(1, 24, 12),
MAX_ICS_BYTES: integerFromEnvironment(16 * 1_024, 5 * 1_024 * 1_024, 512 * 1_024),
MAX_OCCURRENCES_PER_EVENT: integerFromEnvironment(1, 2_000, 500),
ROUTINE_EVENT_TITLES: z.preprocess(
(value) => stringList(value, ["regeltermin"]),
z.array(z.string()),
),
});
type EnvironmentSettings = z.infer<typeof environmentSchema>;
export interface AppConfig {
corsOrigins: string[];
trustedProxies: string[];
publicSiteUrl: string;
calendarUrl?: string;
calendarCacheDurationMs: number;
calendarFetchTimeoutMs: number;
defaultCalendarTimeZone: string;
maxRecurrenceWindowMonths: number;
maxIcsBytes: number;
maxOccurrencesPerEvent: number;
routineEventTitles: string[];
}
function mapSettings(settings: EnvironmentSettings): AppConfig {
const corsOrigins = settings.CORS_ORIGIN
? settings.CORS_ORIGIN.split(",").map((origin) => origin.trim()).filter(Boolean)
: [settings.APP_URL];
return {
corsOrigins,
trustedProxies: settings.TRUSTED_PROXIES,
publicSiteUrl: settings.APP_URL,
calendarUrl: settings.CALENDAR_URL,
calendarCacheDurationMs: settings.CALENDAR_CACHE_DURATION_MS,
calendarFetchTimeoutMs: settings.CALENDAR_FETCH_TIMEOUT_MS,
defaultCalendarTimeZone: settings.DEFAULT_CALENDAR_TIMEZONE,
maxRecurrenceWindowMonths: settings.MAX_RECURRENCE_WINDOW_MONTHS,
maxIcsBytes: settings.MAX_ICS_BYTES,
maxOccurrencesPerEvent: settings.MAX_OCCURRENCES_PER_EVENT,
routineEventTitles: settings.ROUTINE_EVENT_TITLES,
};
}
type Environment = Record<string, string | undefined>;
export function loadAppConfig(environment: Environment = process.env): AppConfig {
const result = environmentSchema.safeParse(environment);
if (!result.success) {
const issue = result.error.issues[0];
const setting = issue?.path.join(".") || "environment";
const detail = issue?.message ?? "invalid value";
throw new CalendarConfigurationError(`Application configuration is invalid: ${setting} ${detail}`, {
cause: result.error,
});
}
return mapSettings(result.data);
}
export function loadHttpConfig(environment: Environment = process.env): AppConfig {
return loadAppConfig({
...environment,
CALENDAR_URL: undefined,
CALENDAR_CACHE_DURATION_MS: undefined,
CALENDAR_FETCH_TIMEOUT_MS: undefined,
DEFAULT_CALENDAR_TIMEZONE: undefined,
MAX_RECURRENCE_WINDOW_MONTHS: undefined,
MAX_ICS_BYTES: undefined,
MAX_OCCURRENCES_PER_EVENT: undefined,
ROUTINE_EVENT_TITLES: undefined,
});
}
export function loadCalendarConfig(environment: Environment = process.env): AppConfig & {
calendarUrl: string;
} {
const config = loadAppConfig(environment);
if (!config.calendarUrl) throw new CalendarConfigurationError();
return config as AppConfig & { calendarUrl: string };
}
export function getAllowedHosts(config: AppConfig): string[] {
const hosts = new Set(["localhost", "127.0.0.1"]);
for (const origin of [...config.corsOrigins, config.publicSiteUrl]) {
try {
hosts.add(new URL(origin).hostname);
} catch {
// Invalid origins are rejected by URL validation where applicable.
}
}
return [...hosts].sort();
}
+41
View File
@@ -0,0 +1,41 @@
export class CalendarError extends Error {
constructor(
message: string,
readonly statusCode = 502,
readonly errorCode = "calendar_error",
options?: ErrorOptions,
) {
super(message, options);
this.name = new.target.name;
}
}
export class CalendarUpstreamError extends CalendarError {
constructor(message: string, options?: ErrorOptions) {
super(message, 502, "calendar_upstream_error", options);
}
}
export class CalendarTimeoutError extends CalendarError {
constructor(message: string, options?: ErrorOptions) {
super(message, 504, "calendar_timeout", options);
}
}
export class CalendarTooLargeError extends CalendarError {
constructor(message: string, options?: ErrorOptions) {
super(message, 413, "calendar_too_large", options);
}
}
export class CalendarParseError extends CalendarError {
constructor(message: string, options?: ErrorOptions) {
super(message, 502, "calendar_parse_error", options);
}
}
export class CalendarConfigurationError extends CalendarError {
constructor(message = "Calendar configuration is invalid", options?: ErrorOptions) {
super(message, 500, "configuration_error", options);
}
}
+176
View File
@@ -0,0 +1,176 @@
import { Temporal } from "@js-temporal/polyfill";
import { fetchIcsWithLimit } from "./calendar-fetcher";
import type { AppConfig } from "./config";
import { loadCalendarConfig } from "./config";
import { CalendarError, CalendarParseError } from "./errors";
import { buildEventsEtag, buildPublicEvents, normalizeEventTitle } from "./events-transformer";
import { parseIcsEvents } from "./ics-parser";
import type { CacheHealth, PublicEvent } from "./types";
export type CalendarRuntimeConfig = AppConfig & { calendarUrl: string };
interface EventsCache {
events: PublicEvent[];
fetchedAtMs: number;
etag: string | null;
}
interface EventsServiceOptions {
config?: CalendarRuntimeConfig;
fetchImplementation?: typeof fetch;
now?: () => Temporal.Instant;
}
export class EventsService {
private cache: EventsCache = { events: [], fetchedAtMs: 0, etag: null };
private inflightFetch: Promise<PublicEvent[]> | null = null;
private readonly config: CalendarRuntimeConfig;
private readonly fetchImplementation: typeof fetch;
private readonly now: () => Temporal.Instant;
private readonly routineEventTitles: Set<string>;
lastSuccessAt: Temporal.ZonedDateTime | null = null;
lastRefreshStartedAt: Temporal.ZonedDateTime | null = null;
lastError: string | null = null;
constructor(options: EventsServiceOptions = {}) {
this.config = options.config ?? loadCalendarConfig();
this.fetchImplementation = options.fetchImplementation ?? fetch;
this.now = options.now ?? (() => Temporal.Now.instant());
this.routineEventTitles = new Set(
this.config.routineEventTitles.map((title) => normalizeEventTitle(title)),
);
}
private isCacheFresh(nowMs = this.now().epochMilliseconds): boolean {
return this.cache.fetchedAtMs !== 0 &&
nowMs - this.cache.fetchedAtMs < this.config.calendarCacheDurationMs;
}
isSpecialEvent(event: PublicEvent): boolean {
return !this.routineEventTitles.has(normalizeEventTitle(event.title));
}
async getEvents(): Promise<PublicEvent[]> {
if (this.isCacheFresh()) return this.cache.events;
if (!this.inflightFetch) {
const refresh = this.refreshCache();
this.inflightFetch = refresh;
void refresh.finally(() => {
if (this.inflightFetch === refresh) this.inflightFetch = null;
}).catch(() => undefined);
}
try {
return await this.inflightFetch;
} catch (error) {
if (this.lastSuccessAt !== null) return this.cache.events;
throw error;
}
}
async getSpecialEvents(): Promise<PublicEvent[]> {
return (await this.getEvents()).filter((event) => event.special).slice(0, 3);
}
scheduleWarmup(): void {
void this.getEvents().catch(() => undefined);
}
getCachedEtag(): string | null {
return this.cache.etag;
}
getCacheHealth(): { statusCode: number; payload: CacheHealth } {
if (!this.cache.fetchedAtMs) {
return {
statusCode: 503,
payload: {
status: "starting",
reason: this.lastError ?? "calendar synchronization in progress",
},
};
}
const ageMs = this.now().epochMilliseconds - this.cache.fetchedAtMs;
if (ageMs > 24 * 60 * 60 * 1_000) {
const hours = Math.floor(ageMs / 3_600_000);
const minutes = Math.floor((ageMs % 3_600_000) / 60_000);
return {
statusCode: 503,
payload: {
status: "degraded",
reason: `cache older than 24h (age: ${hours}h ${minutes}m)`,
},
};
}
return { statusCode: 200, payload: { status: "ok", reason: null } };
}
private async refreshCache(): Promise<PublicEvent[]> {
const refreshStarted = this.now();
const fetchedAtMs = refreshStarted.epochMilliseconds;
this.lastRefreshStartedAt = refreshStarted.toZonedDateTimeISO(this.config.defaultCalendarTimeZone);
let icsText: string;
try {
icsText = await fetchIcsWithLimit(
this.config.calendarUrl,
this.config.calendarFetchTimeoutMs,
this.config.maxIcsBytes,
this.fetchImplementation,
);
} catch (error) {
if (error instanceof CalendarError) this.lastError = error.message;
throw error;
}
let events: PublicEvent[];
try {
const parsed = parseIcsEvents(icsText, this.config.defaultCalendarTimeZone);
const nowInZone = this.now().toZonedDateTimeISO(this.config.defaultCalendarTimeZone);
events = buildPublicEvents(
parsed,
nowInZone,
this.config.maxRecurrenceWindowMonths,
this.config.maxOccurrencesPerEvent,
this.config.defaultCalendarTimeZone,
(event) => this.isSpecialEvent(event),
);
} catch (error) {
this.lastError = "calendar data could not be parsed";
throw new CalendarParseError("Calendar data could not be parsed", { cause: error });
}
this.cache = {
events,
fetchedAtMs,
etag: buildEventsEtag(events),
};
this.lastSuccessAt = this.now().toZonedDateTimeISO(this.config.defaultCalendarTimeZone);
this.lastError = null;
return events;
}
/** Test seam for forced cache expiry. */
expireCache(): void {
this.cache.fetchedAtMs = 0;
}
}
type CalendarGlobal = typeof globalThis & {
__starterEventsService?: EventsService;
};
const calendarGlobal = globalThis as CalendarGlobal;
export function getEventsService(): EventsService {
calendarGlobal.__starterEventsService ??= new EventsService();
return calendarGlobal.__starterEventsService;
}
export function setEventsServiceForTests(service: EventsService | undefined): void {
calendarGlobal.__starterEventsService = service;
}
+82
View File
@@ -0,0 +1,82 @@
import { createHash } from "node:crypto";
import { Temporal } from "@js-temporal/polyfill";
import { expandRecurringEvents } from "./ics-parser";
import type { ParsedEvent, PublicEvent } from "./types";
export function normalizeEventTitle(title: string): string {
return title.trim().toLocaleLowerCase("und").replace(/\s+/g, " ");
}
export function sanitizeIcsText(text: string | null): string | null {
if (text === null) return null;
return text
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#x27;");
}
function publicTimestamp(value: Temporal.ZonedDateTime): string {
const timestamp = value.toString({
timeZoneName: "never",
fractionalSecondDigits: value.millisecond || value.microsecond || value.nanosecond ? "auto" : 0,
});
return value.offsetNanoseconds === 0 ? timestamp.replace(/\+00:00$/, "Z") : timestamp;
}
export function buildEventsEtag(events: PublicEvent[], special = false): string {
return createHash("sha256").update(JSON.stringify({ special, events }), "utf8").digest("hex");
}
export function buildPublicEvents(
parsedEvents: ParsedEvent[],
nowInZone: Temporal.ZonedDateTime,
maxRecurrenceWindowMonths: number,
maxOccurrencesPerEvent: number,
defaultTimeZone: string,
isSpecialEvent: (event: PublicEvent) => boolean,
): PublicEvent[] {
const windowStart = nowInZone.subtract({ days: 1 });
const windowEnd = nowInZone.add({ days: 30 * maxRecurrenceWindowMonths });
const recurring = expandRecurringEvents(
parsedEvents,
windowStart,
windowEnd,
maxOccurrencesPerEvent,
defaultTimeZone,
);
const combined = parsedEvents.filter((event) => !event.recurrenceRule).concat(recurring);
const today = nowInZone.toPlainDate();
combined.sort((left, right) => Temporal.ZonedDateTime.compare(left.start, right.start));
const seen = new Set<string>();
const result: PublicEvent[] = [];
for (const event of combined) {
const isCurrentOrFuture = Temporal.ZonedDateTime.compare(event.end, nowInZone) >= 0 ||
Temporal.ZonedDateTime.compare(event.start, nowInZone) >= 0 ||
Temporal.PlainDate.compare(event.start.toPlainDate(), today) === 0;
if (!isCurrentOrFuture) continue;
const key = `${event.title}::${publicTimestamp(event.start)}::${publicTimestamp(event.end)}`;
if (seen.has(key)) continue;
seen.add(key);
const publicEvent: PublicEvent = {
id: event.uid,
title: sanitizeIcsText(event.title) ?? "",
description: sanitizeIcsText(event.description),
location: sanitizeIcsText(event.location),
start: publicTimestamp(event.start),
end: publicTimestamp(event.end),
allDay: event.allDay,
timeZone: event.timeZone ?? defaultTimeZone,
special: false,
};
publicEvent.special = isSpecialEvent(publicEvent);
result.push(publicEvent);
}
return result;
}
+155
View File
@@ -0,0 +1,155 @@
import { randomUUID } from "node:crypto";
import { isIP } from "node:net";
import type { AppConfig } from "./config";
import { getAllowedHosts, loadAppConfig, loadHttpConfig } from "./config";
import { CalendarError } from "./errors";
const REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
export function resolveRequestId(value: string | null): string {
return value && REQUEST_ID_PATTERN.test(value) ? value : randomUUID();
}
function parseIp(value: string): bigint | null {
const input = value.trim().replace(/^\[|\]$/g, "");
const version = isIP(input);
if (version === 4) {
return input.split(".").reduce((result, part) => (result << 8n) + BigInt(part), 0n);
}
if (version !== 6) return null;
const [left = "", right = ""] = input.toLowerCase().split("::");
const leftParts = left ? left.split(":") : [];
const rightParts = right ? right.split(":") : [];
const missing = 8 - leftParts.length - rightParts.length;
if (missing < 0 || (!input.includes("::") && missing !== 0)) return null;
const parts = [...leftParts, ...Array(missing).fill("0"), ...rightParts];
if (parts.length !== 8) return null;
return parts.reduce((result, part) => (result << 16n) + BigInt(`0x${part || "0"}`), 0n);
}
function isInCidr(address: string, cidr: string): boolean {
const [networkAddress, prefixText] = cidr.split("/");
const addressVersion = isIP(address);
const networkVersion = isIP(networkAddress ?? "");
if (!addressVersion || addressVersion !== networkVersion) return false;
const bitCount = addressVersion === 4 ? 32 : 128;
const prefix = prefixText === undefined ? bitCount : Number(prefixText);
if (!Number.isInteger(prefix) || prefix < 0 || prefix > bitCount) return false;
const parsedAddress = parseIp(address);
const parsedNetwork = parseIp(networkAddress ?? "");
if (parsedAddress === null || parsedNetwork === null) return false;
const shift = BigInt(bitCount - prefix);
return (parsedAddress >> shift) === (parsedNetwork >> shift);
}
function getServerPeerAddress(request: Request): string | null {
const peer = (request as Request & { ip?: unknown }).ip;
return typeof peer === "string" && isIP(peer) ? peer : null;
}
export function resolveClientIp(request: Request, trustedProxies: string[]): string {
const peerAddress = getServerPeerAddress(request);
if (!peerAddress) return "127.0.0.1";
if (!trustedProxies.some((network) => isInCidr(peerAddress, network))) return peerAddress;
const forwarded = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
const realIp = request.headers.get("x-real-ip")?.trim();
for (const candidate of [forwarded, realIp]) {
if (candidate && isIP(candidate)) return candidate;
}
return peerAddress;
}
function anonymizeIp(address: string): string {
if (isIP(address) === 4) return `${address.split(".").slice(0, 3).join(".")}.0/24`;
if (isIP(address) === 6) {
const parsed = parseIp(address);
if (parsed !== null) return `${(parsed >> 80n).toString(16).match(/.{1,4}/g)?.join(":") ?? "::"}::/48`;
}
return "unknown";
}
function isHostAllowed(request: Request, config: AppConfig): boolean {
const hostHeader = request.headers.get("host") ?? "";
let hostname = hostHeader;
try {
hostname = new URL(`http://${hostHeader}`).hostname;
} catch {
return false;
}
return getAllowedHosts(config).some((allowed) =>
allowed === "*" || hostname === allowed || (allowed.startsWith("*.") && hostname.endsWith(allowed.slice(1)))
);
}
function applyHeaders(response: Response, request: Request, requestId: string, config?: AppConfig): Response {
response.headers.set("x-request-id", requestId);
response.headers.set("content-security-policy", "default-src 'self'");
response.headers.set("strict-transport-security", "max-age=31536000; includeSubDomains; preload");
response.headers.set("cross-origin-resource-policy", "same-site");
response.headers.set("x-content-type-options", "nosniff");
response.headers.set("x-frame-options", "DENY");
response.headers.set("referrer-policy", "no-referrer");
response.headers.set("permissions-policy", "geolocation=()");
response.headers.set("cross-origin-opener-policy", "same-origin");
response.headers.set("x-robots-tag", "noindex, noarchive");
const origin = request.headers.get("origin");
if (origin && config?.corsOrigins.includes(origin)) {
response.headers.set("access-control-allow-origin", origin);
response.headers.append("vary", "Origin");
if (request.method === "OPTIONS") {
response.headers.set("access-control-allow-methods", "GET");
response.headers.set(
"access-control-allow-headers",
request.headers.get("access-control-request-headers") ?? "*",
);
response.headers.set("access-control-max-age", "600");
}
}
return response;
}
export async function handleRoute(
request: Request,
handler: (config: AppConfig) => Promise<Response> | Response,
options: { httpOnlyConfig?: boolean } = {},
): Promise<Response> {
const startedAt = performance.now();
const requestId = resolveRequestId(request.headers.get("x-request-id"));
let config: AppConfig | undefined;
let response: Response;
try {
config = options.httpOnlyConfig ? loadHttpConfig() : loadAppConfig();
if (!isHostAllowed(request, config)) {
response = Response.json({ detail: "Invalid host header", error: "invalid_host" }, { status: 400 });
} else {
response = await handler(config);
}
} catch (error) {
if (error instanceof CalendarError) {
response = Response.json(
{ detail: error.message, error: error.errorCode },
{ status: error.statusCode },
);
} else {
console.error("request_error", { requestId, errorType: error instanceof Error ? error.name : "unknown" });
response = Response.json(
{ detail: "Internal server error", error: "internal_server_error" },
{ status: 500 },
);
}
}
const clientIp = config ? resolveClientIp(request, config.trustedProxies) : "127.0.0.1";
console.info("request_completed", {
requestId,
method: request.method,
path: new URL(request.url).pathname,
statusCode: response.status,
durationMs: Math.round(performance.now() - startedAt),
clientIpPrefix: anonymizeIp(clientIp),
});
return applyHeaders(response, request, requestId, config);
}
+340
View File
@@ -0,0 +1,340 @@
import { Temporal } from "@js-temporal/polyfill";
import ICAL from "ical.js";
import { RRule, RRuleSet } from "rrule";
import type { ParsedEvent, ParsedTimestamp } from "./types";
interface IcalTimeLike {
year: number;
month: number;
day: number;
hour: number;
minute: number;
second: number;
isDate: boolean;
zone?: { tzid?: string };
}
interface ParsedComponentEvent extends ParsedEvent {
recurrenceId: ParsedTimestamp | null;
cancelled: boolean;
}
function isIcalTime(value: unknown): value is IcalTimeLike {
return typeof value === "object" && value !== null &&
"year" in value && "month" in value && "day" in value && "isDate" in value;
}
function resolveTimeZone(
value: IcalTimeLike,
defaultTimeZone: string,
propertyTimeZone?: string,
): string {
if (propertyTimeZone) return propertyTimeZone;
const timeZone = value.zone?.tzid;
if (!timeZone || timeZone === "floating" || timeZone === "local") return defaultTimeZone;
if (timeZone === "Z") return "UTC";
return timeZone;
}
function toTimestamp(
value: IcalTimeLike,
defaultTimeZone: string,
propertyTimeZone?: string,
): ParsedTimestamp {
const plainDateTime = new Temporal.PlainDateTime(
value.year,
value.month,
value.day,
value.isDate ? 0 : value.hour,
value.isDate ? 0 : value.minute,
value.isDate ? 0 : value.second,
);
return {
dateTime: plainDateTime.toZonedDateTime(resolveTimeZone(value, defaultTimeZone, propertyTimeZone)),
isDateOnly: value.isDate,
};
}
type IcalComponent = InstanceType<typeof ICAL.Component>;
function readText(component: IcalComponent, name: string): string | null {
const value = component.getFirstPropertyValue(name);
return value === null || value === undefined || value === "" ? null : String(value);
}
function readTimestamps(
component: IcalComponent,
propertyName: "exdate" | "rdate",
defaultTimeZone: string,
): ParsedTimestamp[] {
const timestamps: ParsedTimestamp[] = [];
for (const property of component.getAllProperties(propertyName)) {
const propertyTimeZone = property.getFirstParameter("tzid");
for (const value of property.getValues() as unknown[]) {
if (!isIcalTime(value)) continue;
const timestamp = toTimestamp(value, defaultTimeZone, propertyTimeZone);
// Date-only RDATE values are intentionally ignored.
if (propertyName === "rdate" && timestamp.isDateOnly) continue;
timestamps.push(timestamp);
}
}
return timestamps;
}
function omitEventsWithInvalidRecurrenceRules(icsText: string): string {
const unfolded = icsText.replace(/\r?\n[ \t]/g, "");
const newline = icsText.includes("\r\n") ? "\r\n" : "\n";
const lines = unfolded.split(/\r?\n/);
const output: string[] = [];
let eventLines: string[] | null = null;
for (const line of lines) {
if (/^BEGIN:VEVENT$/i.test(line)) {
eventLines = [line];
continue;
}
if (!eventLines) {
output.push(line);
continue;
}
eventLines.push(line);
if (!/^END:VEVENT$/i.test(line)) continue;
const recurrenceRules = eventLines.flatMap((eventLine) => {
const match = /^RRULE(?:;[^:]*)?:(.*)$/i.exec(eventLine);
return match?.[1] ? [match[1]] : [];
});
const isValid = recurrenceRules.every((rule) => {
try {
const options = RRule.parseString(rule);
if (options.freq === undefined || options.freq === null) return false;
new RRule({ ...options, dtstart: new Date(Date.UTC(2000, 0, 1)) });
return true;
} catch {
return false;
}
});
if (isValid) output.push(...eventLines);
else console.warn("calendar_rrule_parse_failed", { action: "event_skipped" });
eventLines = null;
}
if (eventLines) output.push(...eventLines);
return output.join(newline);
}
export function parseIcsEvents(icsText: string, defaultTimeZone: string): ParsedEvent[] {
const calendar = new ICAL.Component(ICAL.parse(omitEventsWithInvalidRecurrenceRules(icsText)));
if (calendar.name !== "vcalendar") throw new Error("Expected a VCALENDAR component");
const events: ParsedComponentEvent[] = [];
for (const component of calendar.getAllSubcomponents("vevent")) {
const recurrenceIdProperty = component.getFirstProperty("recurrence-id");
const recurrenceRange = recurrenceIdProperty?.getFirstParameter("range")?.toUpperCase();
if (recurrenceRange === "THISANDFUTURE") {
throw new Error("RECURRENCE-ID;RANGE=THISANDFUTURE is not supported");
}
try {
const title = readText(component, "summary");
const startProperty = component.getFirstProperty("dtstart");
const startValue = startProperty?.getFirstValue() as unknown;
const recurrenceIdValue = recurrenceIdProperty?.getFirstValue() as unknown;
const recurrenceId = isIcalTime(recurrenceIdValue)
? toTimestamp(
recurrenceIdValue,
defaultTimeZone,
recurrenceIdProperty?.getFirstParameter("tzid"),
)
: null;
const cancelled = readText(component, "status")?.toUpperCase() === "CANCELLED";
const uidValue = readText(component, "uid");
if (cancelled && recurrenceId && uidValue) {
events.push({
uid: uidValue,
title: title ?? "",
description: null,
location: null,
start: recurrenceId.dateTime,
end: recurrenceId.dateTime,
allDay: recurrenceId.isDateOnly,
timeZone: recurrenceId.dateTime.timeZoneId,
recurrenceRule: null,
exDates: [],
rDates: [],
recurrenceId,
cancelled: true,
});
continue;
}
if (!title || !isIcalTime(startValue)) continue;
const start = toTimestamp(startValue, defaultTimeZone, startProperty?.getFirstParameter("tzid"));
const endProperty = component.getFirstProperty("dtend");
const endValue = endProperty?.getFirstValue() as unknown;
const end = isIcalTime(endValue)
? toTimestamp(endValue, defaultTimeZone, endProperty?.getFirstParameter("tzid"))
: start;
const recurrence = component.getFirstPropertyValue("rrule") as { toString?: () => string } | null;
const uid = uidValue ?? `${start.dateTime.toString({ timeZoneName: "never" })}-${title}`;
events.push({
uid,
title,
description: readText(component, "description"),
location: readText(component, "location"),
start: start.dateTime,
end: end.dateTime,
allDay: start.isDateOnly,
timeZone: start.dateTime.timeZoneId,
recurrenceRule: recurrence?.toString?.() ?? null,
exDates: readTimestamps(component, "exdate", defaultTimeZone),
rDates: readTimestamps(component, "rdate", defaultTimeZone),
recurrenceId,
cancelled,
});
} catch (error) {
console.warn("calendar_event_parse_failed", {
uid: readText(component, "uid"),
errorType: error instanceof Error ? error.name : "unknown",
});
}
}
const cancelledSeries = new Set(
events.filter((event) => event.cancelled && !event.recurrenceId).map((event) => event.uid),
);
const masters = new Map(
events
.filter((event) => !event.recurrenceId && !event.cancelled)
.map((event) => [event.uid, event]),
);
for (const exception of events.filter((event) => event.recurrenceId)) {
const master = masters.get(exception.uid);
if (master && exception.recurrenceId) master.exDates.push(exception.recurrenceId);
}
return events
.filter((event) => !event.cancelled && !cancelledSeries.has(event.uid))
.map((event) => ({
uid: event.uid,
title: event.title,
description: event.description,
location: event.location,
start: event.start,
end: event.end,
allDay: event.allDay,
timeZone: event.timeZone,
recurrenceRule: event.recurrenceId ? null : event.recurrenceRule,
exDates: event.exDates,
rDates: event.rDates,
}));
}
function plainDateTimeToFakeUtc(value: Temporal.PlainDateTime): Date {
const date = new Date(0);
date.setUTCFullYear(value.year, value.month - 1, value.day);
date.setUTCHours(value.hour, value.minute, value.second, value.millisecond);
return date;
}
function fakeUtcToPlainDateTime(value: Date): Temporal.PlainDateTime {
return new Temporal.PlainDateTime(
value.getUTCFullYear(),
value.getUTCMonth() + 1,
value.getUTCDate(),
value.getUTCHours(),
value.getUTCMinutes(),
value.getUTCSeconds(),
value.getUTCMilliseconds(),
);
}
function localDateKey(value: Temporal.PlainDate | Temporal.PlainDateTime): string {
return `${value.year.toString().padStart(4, "0")}-${value.month.toString().padStart(2, "0")}-${value.day.toString().padStart(2, "0")}`;
}
function copyOccurrence(event: ParsedEvent, occurrence: Temporal.ZonedDateTime): ParsedEvent {
const eventEndInStartZone = event.end.withTimeZone(event.start.timeZoneId);
const wallClockDuration = event.start.toPlainDateTime().until(eventEndInStartZone.toPlainDateTime());
return {
...event,
uid: `${event.uid}-${occurrence.toString({ timeZoneName: "never" })}`,
start: occurrence,
end: occurrence.add(wallClockDuration),
recurrenceRule: null,
exDates: [],
rDates: [],
};
}
export function expandRecurringEvents(
events: ParsedEvent[],
windowStart: Temporal.ZonedDateTime,
windowEnd: Temporal.ZonedDateTime,
maxOccurrencesPerEvent: number,
defaultTimeZone: string,
): ParsedEvent[] {
const expanded: ParsedEvent[] = [];
for (const event of events) {
if (!event.recurrenceRule) continue;
const eventTimeZone = event.timeZone ?? defaultTimeZone;
const recurrenceStart = plainDateTimeToFakeUtc(event.start.toPlainDateTime());
let recurrenceSet: RRuleSet;
try {
recurrenceSet = new RRuleSet();
recurrenceSet.rrule(new RRule({
...RRule.parseString(event.recurrenceRule),
dtstart: recurrenceStart,
}));
} catch (error) {
console.warn("calendar_rrule_parse_failed", { uid: event.uid, errorType: error instanceof Error ? error.name : "unknown" });
continue;
}
const excludedDates = new Set<string>();
for (const excluded of event.exDates) {
if (excluded.isDateOnly) {
excludedDates.add(localDateKey(excluded.dateTime.toPlainDate()));
} else {
const local = excluded.dateTime.withTimeZone(eventTimeZone).toPlainDateTime();
recurrenceSet.exdate(plainDateTimeToFakeUtc(local));
}
}
for (const additional of event.rDates) {
const local = additional.dateTime.withTimeZone(eventTimeZone).toPlainDateTime();
recurrenceSet.rdate(plainDateTimeToFakeUtc(local));
}
const localWindowStart = windowStart.withTimeZone(eventTimeZone).toPlainDateTime();
const localWindowEnd = windowEnd.withTimeZone(eventTimeZone).toPlainDateTime();
const startBoundary = plainDateTimeToFakeUtc(localWindowStart);
const endBoundary = plainDateTimeToFakeUtc(localWindowEnd);
const seen = new Set<number>();
let examined = 0;
let occurrence = recurrenceSet.after(startBoundary, true);
while (
occurrence &&
occurrence.getTime() <= endBoundary.getTime() &&
examined < maxOccurrencesPerEvent + excludedDates.size
) {
examined += 1;
const next = recurrenceSet.after(occurrence, false);
const local = fakeUtcToPlainDateTime(occurrence);
if (!excludedDates.has(localDateKey(local)) && !seen.has(occurrence.getTime())) {
seen.add(occurrence.getTime());
const zoned = local.toZonedDateTime(eventTimeZone);
expanded.push(copyOccurrence(event, zoned));
if (seen.size >= maxOccurrencesPerEvent) break;
}
occurrence = next;
}
}
return expanded;
}
+19
View File
@@ -0,0 +1,19 @@
import { CalendarConfigurationError } from "./errors";
import { getEventsService } from "./events-service";
export function readinessResponse(): Response {
try {
const service = getEventsService();
const { statusCode, payload } = service.getCacheHealth();
if (payload.status !== "ok") service.scheduleWarmup();
return Response.json(payload, { status: statusCode });
} catch (error) {
if (error instanceof CalendarConfigurationError) {
return Response.json(
{ status: "starting", reason: error.message },
{ status: 503 },
);
}
throw error;
}
}
+37
View File
@@ -0,0 +1,37 @@
import type { Temporal } from "@js-temporal/polyfill";
export interface PublicEvent {
id: string;
title: string;
description: string | null;
location: string | null;
start: string;
end: string;
allDay: boolean;
timeZone: string;
special: boolean;
}
export interface ParsedTimestamp {
dateTime: Temporal.ZonedDateTime;
isDateOnly: boolean;
}
export interface ParsedEvent {
uid: string;
title: string;
description: string | null;
location: string | null;
start: Temporal.ZonedDateTime;
end: Temporal.ZonedDateTime;
allDay: boolean;
timeZone: string | null;
recurrenceRule: string | null;
exDates: ParsedTimestamp[];
rDates: ParsedTimestamp[];
}
export interface CacheHealth {
status: "ok" | "starting" | "degraded";
reason: string | null;
}
+163
View File
@@ -0,0 +1,163 @@
.slider-container {
width: 100%;
margin: 0 0 1.75rem 0;
}
.slider-stage {
position: relative;
border-radius: 18px;
overflow: hidden;
box-shadow: var(--shadow-lg);
background:
linear-gradient(135deg, rgba(15, 23, 42, 0.95), rgba(71, 85, 105, 0.72));
}
.slider-viewport {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
scroll-behavior: smooth;
scrollbar-width: none;
-ms-overflow-style: none;
aspect-ratio: 3 / 2;
overscroll-behavior-x: contain;
touch-action: pan-y pinch-zoom;
}
.slider-viewport::-webkit-scrollbar {
display: none;
}
.slider-slide {
min-width: 100%;
margin: 0;
scroll-snap-align: start;
scroll-snap-stop: always;
}
.slider-picture {
display: block;
width: 100%;
height: 100%;
background:
linear-gradient(135deg, rgba(226, 232, 240, 0.55), rgba(248, 250, 252, 0.8));
}
.slider-slide img {
display: block;
width: 100%;
height: 100%;
aspect-ratio: 3 / 2;
object-fit: cover;
object-position: center;
user-select: none;
-webkit-user-drag: none;
}
.slider-nav {
position: absolute;
top: 50%;
z-index: 2;
display: inline-flex;
align-items: center;
justify-content: center;
width: 48px;
height: 48px;
padding: 0;
border-radius: 999px;
appearance: none;
-webkit-appearance: none;
border: 1px solid rgba(248, 250, 252, 0.35);
background: rgba(15, 23, 42, 0.4);
color: var(--color-text-on-dark);
box-shadow: none;
backdrop-filter: blur(8px);
transform: translateY(-50%);
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
transition:
background-color var(--transition-fast),
border-color var(--transition-fast),
transform var(--transition-fast);
}
.slider-nav--prev {
left: 0.85rem;
}
.slider-nav--next {
right: 0.85rem;
}
.slider-nav span {
font-size: 2rem;
line-height: 1;
}
.slider-nav:focus-visible {
outline: 2px solid rgba(37, 99, 235, 0.65);
outline-offset: 2px;
}
.slider-nav:hover,
.slider-nav:active {
transform: translateY(-50%);
box-shadow: none;
}
.slider-empty {
width: 100%;
padding: 3rem;
background: var(--color-card-bg);
border: var(--border-subtle);
border-radius: 18px;
text-align: center;
color: var(--color-text-muted);
font-style: italic;
}
.slider-container[data-enhanced="true"] .slider-viewport {
cursor: grab;
}
.slider-container[data-enhanced="true"] .slider-viewport:active {
cursor: grabbing;
}
@media (hover: hover) {
.slider-nav:hover {
background: rgba(37, 99, 235, 0.88);
border-color: rgba(255, 255, 255, 0.55);
transform: translateY(-50%) scale(1.04);
}
}
@media (max-width: 768px) {
.slider-nav {
width: 42px;
height: 42px;
}
}
@media (max-width: 480px) {
.slider-container {
margin-bottom: 1.5rem;
}
.slider-stage {
border-radius: 0;
}
.slider-nav {
width: 38px;
height: 38px;
}
.slider-nav--prev {
left: 0.6rem;
}
.slider-nav--next {
right: 0.6rem;
}
}
+893
View File
@@ -0,0 +1,893 @@
/* ============================================
BILDER PAGE - Gallery Styles
============================================ */
.bilder-page {
display: grid;
gap: 3rem;
}
.bilder-grid {
display: grid;
gap: 1.75rem;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
}
.bilder-card {
background: var(--color-card-bg);
border-radius: 8px;
box-shadow: var(--shadow-md);
padding: 2rem 1.75rem;
text-align: center;
display: grid;
gap: 1.25rem;
position: relative;
border-top: 3px solid var(--color-neutral-700);
transition: transform var(--transition-fast), box-shadow var(--transition-fast);
}
.bilder-card:hover {
transform: translateY(-4px);
box-shadow: var(--shadow-lg);
}
.bilder-card h2 {
margin: 0;
font-family: var(--font-heading);
font-size: 1.5rem;
color: var(--color-neutral-950);
}
.bilder-link-list {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.75rem;
}
.bilder-link-list a {
font-weight: 600;
color: var(--color-accent-600);
text-decoration: none;
border-bottom: 2px solid rgba(37, 99, 235, 0.3);
padding-bottom: 0.15rem;
transition: color var(--transition-fast), border-color var(--transition-fast);
}
.bilder-link-list a:hover {
color: var(--color-accent-500);
border-color: var(--color-accent-500);
}
.bilder-link-list span {
font-weight: 600;
color: var(--color-text-muted);
}
.bilder-hints {
background: var(--color-card-bg);
border-radius: 8px;
padding: 2rem;
box-shadow: var(--shadow-md);
border-left: 4px solid var(--color-neutral-500);
}
.bilder-hints h2 {
margin-top: 0;
font-family: var(--font-heading);
color: var(--color-neutral-950);
}
.bilder-hints ul {
margin: 1rem 0 1.5rem;
padding-left: 1.25rem;
display: grid;
gap: 0.6rem;
}
.bilder-hints li {
color: var(--color-text-secondary);
}
.bilder-contact {
margin: 0;
font-weight: 500;
color: var(--color-text-secondary);
}
/* ============================================
ABOUT PAGE
============================================ */
.about-page {
display: grid;
gap: 2.5rem;
padding-bottom: 4rem;
}
.about-intro {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
gap: 1.5rem;
}
.about-card {
background: var(--color-card-bg);
border-radius: 10px;
padding: 2rem;
box-shadow: var(--shadow-md);
border-left: 4px solid rgba(51, 65, 85, 0.18);
}
.about-card-highlight {
border-left-color: var(--color-accent-600);
box-shadow: 0 16px 30px rgba(51, 65, 85, 0.12);
}
.about-card h2 {
margin: 0 0 0.75rem;
font-family: var(--font-heading);
font-size: 1.5rem;
color: var(--color-neutral-950);
}
.about-card p {
margin: 0;
color: var(--color-text-secondary);
line-height: 1.7;
}
.about-callout {
background: linear-gradient(
135deg,
rgba(51, 65, 85, 0.08),
rgba(37, 99, 235, 0.08)
);
border-radius: 12px;
padding: 2.5rem;
display: grid;
gap: 1.5rem;
box-shadow: var(--shadow-sm);
}
.about-callout h2 {
margin: 0 0 0.6rem;
font-family: var(--font-heading);
color: var(--color-neutral-950);
font-size: 1.6rem;
}
.about-callout p {
margin: 0;
color: var(--color-text-secondary);
line-height: 1.7;
}
.about-callout-note {
font-weight: 600;
color: var(--color-neutral-700);
}
/* Reusable about-page sections */
.about-section {
padding: 2.5rem 0;
}
.about-section + .about-section {
border-top: 1px solid rgba(51, 65, 85, 0.1);
}
.about-section__header {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1.75rem;
}
.about-section__header h2 {
margin: 0;
font-family: var(--font-heading);
font-size: 1.6rem;
color: var(--color-neutral-950);
position: relative;
}
.about-section__header h2::after {
content: "";
display: block;
width: 40px;
height: 3px;
background: var(--color-accent-600);
border-radius: 2px;
margin-top: 0.5rem;
}
/* Two-column media + text layout */
.about-section__content--media {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2rem;
align-items: start;
}
.about-section__media {
border-radius: 12px;
overflow: hidden;
}
.about-section__media .slider-container {
margin: 0;
box-shadow: var(--shadow-md);
}
.about-section__text {
color: var(--color-text-secondary);
line-height: 1.7;
}
.about-section__text p {
margin: 0 0 1rem;
}
.about-section__text p:last-child {
margin-bottom: 0;
}
.about-section__content > p {
margin: 0;
color: var(--color-text-secondary);
line-height: 1.7;
}
/* Timeline for schedules */
.about-timeline {
display: grid;
gap: 0;
}
.about-timeline__item {
display: grid;
grid-template-columns: 1fr;
padding: 1.25rem 0 1.25rem 1.5rem;
border-left: 2px solid rgba(51, 65, 85, 0.15);
margin-left: 3.5rem;
position: relative;
}
.about-timeline__item::before {
content: "";
position: absolute;
left: -6px;
top: 1.65rem;
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--color-neutral-700);
border: 2px solid var(--color-card-bg);
box-shadow: 0 0 0 2px rgba(51, 65, 85, 0.15);
}
.about-timeline__item--highlight::before {
background: var(--color-accent-600);
box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.2);
}
.about-timeline__time {
font-family: var(--font-heading);
font-weight: 700;
font-size: 0.95rem;
color: var(--color-accent-600);
white-space: nowrap;
position: absolute;
left: -5rem;
top: 1.25rem;
text-align: right;
width: 3rem;
}
.about-timeline__body p {
margin: 0;
color: var(--color-text-secondary);
line-height: 1.7;
font-size: 0.95rem;
}
/* Featured section with subtle gradient */
.about-section--feature {
background: linear-gradient(
135deg,
rgba(51, 65, 85, 0.05),
rgba(37, 99, 235, 0.04)
);
border-radius: 12px;
padding: 2.5rem;
border: 1px solid rgba(51, 65, 85, 0.08);
}
.about-section--feature + .about-section {
border-top: none;
}
.about-section--schedule + .about-section--feature {
border-top: none;
}
/* Two-column text + aside layout */
.about-section__content--aside {
display: grid;
grid-template-columns: 1fr 300px;
gap: 2rem;
align-items: start;
}
/* Tuch system cards */
.tuch-system {
background: var(--color-card-bg);
border-radius: 10px;
padding: 1.5rem;
box-shadow: var(--shadow-md);
display: grid;
gap: 0.75rem;
}
.tuch-system__title {
margin: 0 0 0.25rem;
font-family: var(--font-heading);
font-size: 1.1rem;
color: var(--color-neutral-950);
}
.tuch-card {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem 1rem;
border-radius: 8px;
background: rgba(51, 65, 85, 0.04);
border-left: 3px solid var(--color-neutral-700);
transition: background var(--transition-fast);
}
.tuch-card:hover {
background: rgba(51, 65, 85, 0.07);
}
.tuch-card strong {
display: block;
font-size: 0.9rem;
color: var(--color-neutral-950);
margin-bottom: 0.15rem;
}
.tuch-card p {
margin: 0;
font-size: 0.825rem;
color: var(--color-text-muted);
line-height: 1.45;
}
.tuch-card__badge {
width: 22px;
height: 22px;
border-radius: 50%;
flex-shrink: 0;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);
}
.tuch-card--gelb-rot .tuch-card__badge {
background: linear-gradient(135deg, #60a5fa 50%, #64748b 50%);
}
.tuch-card--rot .tuch-card__badge {
background: #64748b;
}
.tuch-card--rot-schwarz .tuch-card__badge {
background: linear-gradient(135deg, #64748b 50%, var(--color-neutral-950) 50%);
}
.tuch-card--gelb-rot {
border-left-color: #60a5fa;
}
.tuch-card--rot {
border-left-color: #64748b;
}
.tuch-card--rot-schwarz {
border-left-color: var(--color-neutral-950);
}
/* ============================================
ABOUT PAGE V2
============================================ */
.about-v2 {
--about-accent: #475569;
--about-accent-warm: #2563eb;
--about-bg-alt: #f1f5f9;
--about-pad: clamp(2.5rem, 5vw, 4.5rem);
}
.about-v2--info {
--about-pad: clamp(1.75rem, 3vw, 2.75rem);
}
/* Scroll reveal */
.about-v2 .reveal {
opacity: 0;
transform: translateY(24px);
transition: opacity 0.7s cubic-bezier(0.16, 1, 0.3, 1),
transform 0.7s cubic-bezier(0.16, 1, 0.3, 1);
}
.about-v2 .revealed {
opacity: 1;
transform: none;
}
/* Eyebrow */
.about-eyebrow {
display: block;
font-family: var(--font-body);
font-size: 0.78rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.16em;
color: var(--about-accent);
margin-bottom: 0.5rem;
}
/* ── Page Header (compact banner) ── */
.about-header {
position: relative;
min-height: 35vh;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
padding: 4rem 2rem;
background-image: var(--about-header-bg, linear-gradient(135deg, #1e293b, #475569));
background-size: cover;
background-position: center;
color: var(--color-surface-light);
overflow: hidden;
}
.about-header--hero-camp1 {
background-image: linear-gradient(135deg, #172554, #2563eb);
}
.about-header--hero-camp2 {
background-image: linear-gradient(135deg, #1e293b, #64748b);
}
@media (max-width: 768px) {
.about-header--hero-camp {
background-image: linear-gradient(135deg, #1e293b, #475569);
}
.about-header--hero-camp1 {
background-image: linear-gradient(135deg, #172554, #2563eb);
}
.about-header--hero-camp2 {
background-image: linear-gradient(135deg, #1e293b, #64748b);
}
}
.about-header__overlay {
position: absolute;
inset: 0;
background: linear-gradient(
180deg,
rgba(15, 23, 42, 0.45) 0%,
rgba(15, 23, 42, 0.62) 100%
);
z-index: 1;
}
.about-header__content {
position: relative;
z-index: 2;
max-width: 600px;
animation: about-header-in 0.7s cubic-bezier(0.16, 1, 0.3, 1) 0.1s both;
}
.about-header h1 {
font-family: var(--font-heading);
font-size: clamp(2rem, 5vw, 3rem);
margin: 0 0 0.75rem;
color: var(--color-surface-light);
letter-spacing: -0.02em;
}
.about-header p {
font-size: clamp(0.95rem, 2vw, 1.1rem);
line-height: 1.7;
color: rgba(248, 250, 252, 0.8);
margin: 0;
}
@keyframes about-header-in {
from {
opacity: 0;
transform: translateY(16px);
}
to {
opacity: 1;
transform: none;
}
}
/* ── Content Blocks ── */
.about-block {
padding: var(--about-pad) 0;
}
.about-block--alt {
background: var(--about-bg-alt);
}
.about-block__inner {
max-width: 1100px;
margin: 0 auto;
padding: 0 clamp(1.5rem, 4vw, 3rem);
}
.about-block__inner--narrow {
max-width: 720px;
}
.about-block__head {
margin-bottom: 2rem;
}
.about-v2--info .about-block__head {
margin-bottom: 1.25rem;
}
.about-block__head h2,
.about-block__inner--narrow h2 {
font-family: var(--font-heading);
font-size: clamp(1.5rem, 3vw, 2rem);
color: var(--color-neutral-950);
margin: 0 0 0.75rem;
letter-spacing: -0.015em;
}
.about-block__head p,
.about-block__inner--narrow > p {
font-size: 1rem;
line-height: 1.75;
color: var(--color-text-secondary);
margin: 0 0 0.75rem;
}
.about-block__inner--narrow > p:last-child {
margin-bottom: 0;
}
.about-inline-link {
font-weight: 700;
color: #1d4ed8;
text-decoration: underline;
text-decoration-thickness: 0.16em;
text-underline-offset: 0.18em;
transition:
color 160ms ease,
text-decoration-color 160ms ease;
}
.about-inline-link:hover,
.about-inline-link:focus-visible {
color: #1e40af;
text-decoration-color: #3b82f6;
}
/* ── Split Layouts ── */
.about-split {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2rem;
align-items: start;
}
.about-split__media {
border-radius: 10px;
overflow: hidden;
box-shadow: var(--shadow-md);
}
.about-split__media .slider-container {
margin: 0;
}
.about-split__text p {
font-size: 1rem;
line-height: 1.75;
color: var(--color-text-secondary);
margin: 0 0 0.75rem;
}
.about-split__text p:last-child {
margin-bottom: 0;
}
/* ── Schedule Cards ── */
.about-split__aside {
display: grid;
gap: 0.6rem;
}
.sched-card {
display: flex;
gap: 1rem;
padding: 1rem 1.15rem;
border-radius: 8px;
background: rgba(71, 85, 105, 0.04);
border-left: 3px solid rgba(71, 85, 105, 0.2);
transition: background var(--transition-fast),
border-color var(--transition-fast);
}
.sched-card:hover {
background: rgba(71, 85, 105, 0.08);
border-left-color: var(--about-accent);
}
.sched-card--accent {
border-left-color: var(--about-accent-warm);
background: rgba(193, 127, 62, 0.05);
}
.sched-card--accent:hover {
background: rgba(193, 127, 62, 0.09);
border-left-color: var(--about-accent-warm);
}
.sched-card__time {
font-family: var(--font-heading);
font-size: 0.82rem;
font-weight: 700;
color: var(--about-accent);
min-width: 3.8rem;
padding-top: 0.05rem;
}
.sched-card--accent .sched-card__time {
color: var(--about-accent-warm);
}
.sched-card h3 {
font-family: var(--font-heading);
font-size: 0.92rem;
margin: 0 0 0.2rem;
color: var(--color-neutral-950);
}
.sched-card p {
margin: 0;
font-size: 0.85rem;
line-height: 1.6;
color: var(--color-text-secondary);
}
/* ── Scarf / Tuch Box ── */
.scarf-box {
background: #fff;
border-radius: 10px;
padding: 1.25rem;
box-shadow: var(--shadow-sm);
border: 1px solid rgba(71, 85, 105, 0.1);
display: grid;
gap: 0.5rem;
}
.scarf-box__title {
font-family: var(--font-heading);
font-size: 0.95rem;
margin: 0 0 0.25rem;
color: var(--color-neutral-950);
}
.scarf-row {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.6rem 0.75rem;
border-radius: 6px;
background: rgba(71, 85, 105, 0.04);
border-left: 3px solid var(--about-accent);
transition: background var(--transition-fast);
}
.scarf-row:hover {
background: rgba(71, 85, 105, 0.07);
}
.scarf-row__dot {
width: 20px;
height: 20px;
border-radius: 50%;
flex-shrink: 0;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.scarf-row--yellow .scarf-row__dot {
background: #60a5fa;
}
.scarf-row--yellow {
border-left-color: #60a5fa;
}
.scarf-row--yellow-green .scarf-row__dot {
background: linear-gradient(135deg, #60a5fa 50%, #3b82f6 50%);
}
.scarf-row--yellow-green {
border-left-color: #3b82f6;
}
.scarf-row--yellow-red .scarf-row__dot {
background: linear-gradient(135deg, #60a5fa 50%, #64748b 50%);
}
.scarf-row--yellow-red {
border-left-color: #2563eb;
}
.scarf-row--red .scarf-row__dot {
background: #64748b;
}
.scarf-row--red {
border-left-color: #64748b;
}
.scarf-row--red-black .scarf-row__dot {
background: linear-gradient(
135deg,
#64748b 50%,
var(--color-neutral-950) 50%
);
}
.scarf-row--red-black {
border-left-color: var(--color-neutral-950);
}
.scarf-row strong {
display: block;
font-size: 0.85rem;
color: var(--color-neutral-950);
margin-bottom: 0.05rem;
}
.scarf-row p {
margin: 0;
font-size: 0.78rem;
line-height: 1.4;
color: var(--color-text-muted);
}
/* ── Join (subtle) ── */
.about-join {
border-top: 1px solid rgba(71, 85, 105, 0.12);
}
.about-join__content {
text-align: center;
}
.about-join__content h2 {
color: var(--about-accent);
}
.about-join__content p {
color: var(--color-text-secondary);
}
/* ── Responsive ── */
@media (max-width: 960px) {
.about-split {
grid-template-columns: 1fr;
}
}
@media (max-width: 640px) {
.about-header {
min-height: 28vh;
padding: 3rem 1.5rem;
}
.sched-card {
flex-direction: column;
gap: 0.4rem;
}
}
@media (max-width: 768px) {
.about-section__content--media,
.about-section__content--aside {
grid-template-columns: 1fr;
}
.about-timeline__item {
margin-left: 2rem;
padding-left: 1.25rem;
}
.about-timeline__time {
left: -3.5rem;
font-size: 0.85rem;
width: 2.25rem;
}
.about-section--feature {
padding: 2rem 1.5rem;
}
.bilder-hints {
padding: 1.5rem;
}
.bilder-card {
padding: 1.5rem;
}
}
@media (max-width: 480px) {
.about-section {
padding: 1.5rem 0;
}
.about-section__header h2 {
font-size: 1.35rem;
}
.about-timeline__item {
margin-left: 0;
padding: 0 0 1.25rem;
border-left: none;
}
.about-timeline__item::before {
display: none;
}
.about-timeline__time {
position: static;
display: block;
width: auto;
margin-bottom: 0.35rem;
text-align: left;
}
.about-section--feature {
border-radius: 8px;
padding: 1.5rem 1rem;
}
.tuch-system {
padding: 1rem;
}
}
@media (prefers-reduced-motion: reduce) {
.about-v2 .reveal {
opacity: 1;
transform: none;
transition: none;
}
.about-header__content {
animation: none;
opacity: 1;
transform: none;
}
}
.about-block__empty {
font-size: 1rem;
color: var(--color-text-muted);
text-align: center;
padding: 2rem 0;
}
+265
View File
@@ -0,0 +1,265 @@
/* ============================================
LOCAL FONTS - DSGVO/DSG-EKD Compliant
Self-hosted fonts, no external requests
============================================ */
/* Poppins - Heading Text */
@font-face {
font-family: 'Poppins';
src: url('/fonts/Poppins-Regular.woff2') format('woff2');
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Poppins';
src: url('/fonts/Poppins-Medium.woff2') format('woff2');
font-weight: 500;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Poppins';
src: url('/fonts/Poppins-SemiBold.woff2') format('woff2');
font-weight: 600;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Poppins';
src: url('/fonts/Poppins-Bold.woff2') format('woff2');
font-weight: 700;
font-style: normal;
font-display: swap;
}
/* Montserrat - Body Text */
@font-face {
font-family: 'Montserrat';
src: url('/fonts/Montserrat-Regular.woff2') format('woff2');
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Montserrat';
src: url('/fonts/Montserrat-SemiBold.woff2') format('woff2');
font-weight: 600;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Montserrat';
src: url('/fonts/Montserrat-Bold.woff2') format('woff2');
font-weight: 700;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Montserrat';
src: url('/fonts/Montserrat-Italic.woff2') format('woff2');
font-weight: 400;
font-style: italic;
font-display: swap;
}
:root {
/* Typography - Modern sans serif pairing */
--font-heading: 'Poppins', 'Trebuchet MS', 'Segoe UI', sans-serif;
--font-body: 'Montserrat', 'Helvetica Neue', 'Arial Nova', Arial, sans-serif;
/* Neutral starter palette */
--color-neutral-950: #0f172a;
--color-neutral-800: #1e293b;
--color-accent-600: #2563eb;
--color-accent-500: #3b82f6;
--color-accent-400: #60a5fa;
--color-neutral-700: #334155;
--color-neutral-600: #475569;
--color-neutral-500: #64748b;
--color-neutral-200: #e2e8f0;
--color-surface-light: #f8fafc;
/* Semantic Colors */
--color-primary: var(--color-neutral-700);
--color-primary-dark: var(--color-neutral-950);
--color-accent: var(--color-accent-600);
--color-accent-light: var(--color-accent-500);
--color-highlight: var(--color-accent-400);
/* Surface Colors */
--color-page-bg: var(--color-surface-light);
--color-card-bg: #ffffff;
--color-footer-bg: var(--color-neutral-950);
--color-header-bg: #ffffff;
/* Text Colors */
--color-text-primary: var(--color-neutral-950);
--color-text-secondary: #475569;
--color-text-muted: #64748b;
--color-text-on-dark: #f8fafc;
/* Shadows - Neutral */
--shadow-sm: 0 2px 8px rgba(15, 23, 42, 0.08);
--shadow-md: 0 8px 24px rgba(15, 23, 42, 0.12);
--shadow-lg: 0 16px 48px rgba(15, 23, 42, 0.16);
--shadow-glow: 0 0 20px rgba(37, 99, 235, 0.3);
/* Borders */
--border-subtle: 1px solid rgba(51, 65, 85, 0.12);
--border-accent: 3px solid var(--color-accent-600);
/* Transitions */
--transition-fast: 150ms ease;
--transition-base: 250ms ease;
--transition-slow: 400ms ease;
/* Spacing rhythm */
--space-xs: 0.25rem;
--space-sm: 0.5rem;
--space-md: 1rem;
--space-lg: 2rem;
--space-xl: 4rem;
font-family: var(--font-body);
line-height: 1.65;
font-weight: 400;
background-color: var(--color-page-bg);
color: var(--color-text-primary);
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
* {
box-sizing: border-box;
}
.skip-link {
position: absolute;
top: -100%;
left: 1rem;
background: var(--color-accent);
color: #fff;
padding: 0.5rem 1.25rem;
border-radius: 0 0 var(--radius-sm) var(--radius-sm);
text-decoration: none;
font-weight: 600;
z-index: 200;
transition: top var(--transition-fast);
}
.skip-link:focus {
top: 0;
}
body {
margin: 0;
min-height: 100vh;
background-color: var(--color-page-bg);
color: var(--color-text-primary);
/* Subtle paper texture feel */
background-image:
radial-gradient(ellipse at 20% 30%, rgba(226, 232, 240, 0.3) 0%, transparent 50%),
radial-gradient(ellipse at 80% 70%, rgba(100, 116, 139, 0.08) 0%, transparent 40%);
}
h1, h2, h3, h4, h5, h6 {
font-family: var(--font-heading);
font-weight: 700;
line-height: 1.25;
color: var(--color-text-primary);
}
a {
color: inherit;
text-decoration: none;
transition: color var(--transition-fast);
}
p {
margin-top: 0;
}
main {
min-height: 60vh;
}
.container {
max-width: 1100px;
margin: 0 auto;
padding-left: clamp(1.5rem, 4vw, 3rem);
padding-right: clamp(1.5rem, 4vw, 3rem);
}
/* Focus styles for accessibility */
a:focus-visible,
button:focus-visible,
.nav-links a:focus-visible {
outline: 2px solid var(--color-accent-600);
outline-offset: 2px;
}
/* Selection color */
::selection {
background: rgba(37, 99, 235, 0.2);
color: var(--color-neutral-950);
}
/* Smooth scroll behavior */
html {
scroll-behavior: smooth;
}
/* Reduced motion preference */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
html {
scroll-behavior: auto;
}
}
/* Print styles */
@media print {
.app-header,
.app-footer,
.cta,
.back-link {
display: none;
}
body {
background: white;
color: black;
}
.hero {
min-height: auto;
padding: 2rem 0;
}
.hero::before,
.hero::after {
display: none;
}
.post-card,
.event-card,
.group-info-card {
box-shadow: none;
border: 1px solid #ddd;
}
}
+129
View File
@@ -0,0 +1,129 @@
/* ============================================
CALENDAR TABLE
============================================ */
.calendar-table {
display: flex;
flex-direction: column;
gap: 2.5rem;
margin-top: 2.5rem;
}
.calendar-table-month {
display: flex;
flex-direction: column;
gap: 1rem;
}
.calendar-month-heading {
margin: 0;
font-family: var(--font-heading);
font-size: clamp(1.3rem, 3vw, 1.6rem);
font-weight: 700;
color: var(--color-neutral-950);
text-transform: capitalize;
display: flex;
align-items: center;
gap: 0.75rem;
}
.calendar-month-heading::before {
content: '';
width: 4px;
height: 1.2em;
background: var(--color-accent-600);
border-radius: 2px;
}
.calendar-table-grid {
background: var(--color-card-bg);
border-radius: 8px;
box-shadow: var(--shadow-md);
overflow: hidden;
}
.calendar-table-row {
display: grid;
grid-template-columns: minmax(0, 1.7fr) minmax(0, 1.1fr);
gap: 1.5rem;
padding: 1rem 1.5rem;
align-items: center;
border-top: 1px solid rgba(51, 65, 85, 0.08);
transition: background-color var(--transition-fast);
}
.calendar-table-row:hover:not(.calendar-table-row-head) {
background-color: rgba(51, 65, 85, 0.03);
}
.calendar-table-row:first-child {
border-top: none;
}
.calendar-table-row-head {
background: linear-gradient(135deg, var(--color-neutral-700) 0%, var(--color-neutral-800) 100%);
color: var(--color-surface-light);
font-weight: 600;
border-top: none;
}
.calendar-table-row-head .calendar-table-title,
.calendar-table-row-head .calendar-table-date {
font-size: 0.9rem;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.calendar-table-row-head .calendar-table-title,
.calendar-table-row-head .calendar-table-date {
color: var(--color-surface-light);
}
.calendar-event-title {
font-weight: inherit;
}
.calendar-highlight {
color: var(--color-accent-400);
margin-right: 0.35rem;
}
.calendar-event-location {
font-weight: 400;
color: var(--color-text-muted);
font-size: 0.9rem;
}
.calendar-table-date {
color: var(--color-text-muted);
font-weight: 500;
}
@media (max-width: 640px) {
.calendar-table-grid {
box-shadow: none;
background: none;
}
.calendar-table-row {
grid-template-columns: 1fr;
gap: 0.35rem;
padding: 0.75rem 0;
border-top: 1px solid rgba(51, 65, 85, 0.12);
}
.calendar-table-row-head {
display: none;
}
.calendar-table-month {
padding: 1.25rem 1.5rem;
border-radius: 8px;
background: var(--color-card-bg);
box-shadow: var(--shadow-md);
}
.calendar-month-heading::before {
display: none;
}
}
+271
View File
@@ -0,0 +1,271 @@
/* ============================================
PAGE LAYOUTS
============================================ */
.page-spacing {
padding-top: 2.5rem;
}
.info-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 1.5rem;
margin: 2rem 0 0;
}
.info-grid > div {
background: var(--color-card-bg);
border-radius: 8px;
padding: 1.5rem;
box-shadow: var(--shadow-md);
}
.calendar-page {
padding-top: 3rem;
padding-bottom: 4rem;
}
.page-header {
text-align: center;
max-width: 640px;
margin: 0 auto;
position: relative;
}
.page-header h1 {
margin-bottom: 0.75rem;
font-family: var(--font-heading);
font-size: clamp(2rem, 5vw, 2.75rem);
color: var(--color-neutral-950);
}
.page-header h1::after {
content: '';
display: block;
width: 60px;
height: 3px;
background: linear-gradient(to right, var(--color-accent-600), var(--color-accent-500));
margin: 1rem auto 0;
border-radius: 2px;
}
.page-header p {
margin: 0;
color: var(--color-text-secondary);
font-size: 1.05rem;
}
/* ============================================
LEGAL PAGES
============================================ */
.legal-page {
padding: 3rem 0 4rem;
}
.legal-content {
background: var(--color-card-bg);
border-radius: 8px;
padding: 2rem;
box-shadow: var(--shadow-md);
color: var(--color-text-secondary);
}
.legal-content h2 {
font-family: var(--font-heading);
color: var(--color-neutral-950);
margin-top: 2rem;
}
.legal-content h2:first-child {
margin-top: 0;
}
.legal-content p {
margin-bottom: 1rem;
line-height: 1.7;
}
.legal-content p:last-child {
margin-bottom: 0;
}
/* ============================================
EVENT CARDS
============================================ */
.event-grid {
display: grid;
gap: 1.5rem;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
margin-top: 1.5rem;
}
.event-card {
background: var(--color-card-bg);
border-radius: 8px;
padding: 1.5rem;
box-shadow: var(--shadow-md);
display: flex;
flex-direction: column;
gap: 0.75rem;
border-top: 3px solid var(--color-neutral-700);
transition: transform var(--transition-fast), box-shadow var(--transition-fast);
}
.event-card:hover {
transform: translateY(-3px);
box-shadow: var(--shadow-lg);
}
.event-meta {
margin: 0.4rem 0 0;
color: var(--color-accent-600);
font-weight: 600;
}
.event-location {
margin: 0.25rem 0 0;
color: var(--color-text-muted);
}
.event-description {
margin: 0.75rem 0 0;
color: var(--color-text-secondary);
line-height: 1.7;
}
.post-meta {
margin: 0.4rem 0 0;
color: var(--color-text-muted);
font-size: 0.9rem;
}
.muted {
color: var(--color-text-muted);
}
.error {
color: #b91c1c;
margin-top: 0.75rem;
padding: 0.75rem 1rem;
background: rgba(185, 28, 28, 0.08);
border-radius: 6px;
border-left: 3px solid #b91c1c;
}
/* Error styling specifically for hero card context */
.hero-card .error {
color: #991b1b;
background: rgba(185, 28, 28, 0.12);
border-left-color: #dc2626;
font-weight: 500;
}
.card {
background: var(--color-card-bg);
border-radius: 8px;
padding: 1.75rem;
box-shadow: var(--shadow-md);
margin-top: 2rem;
}
/* ============================================
BUTTONS
============================================ */
button {
border-radius: 6px;
border: none;
padding: 0.75rem 1.5rem;
font-size: 1rem;
font-weight: 700;
font-family: inherit;
background: linear-gradient(135deg, var(--color-neutral-700) 0%, var(--color-neutral-800) 100%);
color: white;
cursor: pointer;
transition: transform var(--transition-fast), box-shadow var(--transition-fast);
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(51, 65, 85, 0.3);
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
box-shadow: none;
}
/* ============================================
DOWNLOAD CARDS
============================================ */
.download-grid {
display: grid;
gap: 1.5rem;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
margin-top: 1.5rem;
}
.download-card {
background: var(--color-card-bg);
border-radius: 8px;
padding: 1.5rem;
box-shadow: var(--shadow-md);
display: flex;
flex-direction: column;
gap: 1rem;
border-top: 3px solid var(--color-neutral-700);
transition: transform var(--transition-fast), box-shadow var(--transition-fast);
text-decoration: none;
color: inherit;
}
.download-card:hover {
transform: translateY(-3px);
box-shadow: var(--shadow-lg);
}
.download-header {
display: flex;
align-items: flex-start;
gap: 0.75rem;
}
.download-icon {
font-size: 2rem;
flex-shrink: 0;
line-height: 1;
}
.download-name {
margin: 0;
font-family: var(--font-heading);
font-size: 1.1rem;
color: var(--color-neutral-950);
word-break: break-word;
overflow-wrap: break-word;
}
.download-description {
margin: 0;
font-size: 0.9rem;
color: var(--color-text-muted);
line-height: 1.45;
}
@media (max-width: 768px) {
.info-grid,
.event-grid {
grid-template-columns: 1fr;
}
.page-header h1::after {
margin-top: 0.75rem;
}
}
@media (max-width: 480px) {
.event-card {
padding: 1.25rem;
}
}
+504
View File
@@ -0,0 +1,504 @@
/* ============================================
HERO
============================================ */
.hero {
background-image: var(--hero-background-image, linear-gradient(135deg, #0f172a, #334155));
background-size: cover;
background-position: center;
background-repeat: no-repeat;
color: var(--color-surface-light);
padding: 5rem 0;
min-height: calc(100vh - 80px);
display: flex;
align-items: center;
position: relative;
}
/* Readability overlay */
.hero::before {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(
135deg,
rgba(15, 23, 42, 0.7) 0%,
rgba(30, 41, 59, 0.5) 50%,
rgba(51, 65, 85, 0.35) 100%
);
z-index: 1;
}
/* Subtle accent at bottom */
.hero::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 200px;
background: linear-gradient(
to top,
rgba(37, 99, 235, 0.15) 0%,
transparent 100%
);
z-index: 1;
pointer-events: none;
}
.hero-content {
display: grid;
grid-template-columns: 1.2fr 0.8fr;
gap: 3rem;
align-items: center;
position: relative;
z-index: 2;
}
.hero h1 {
font-family: var(--font-heading);
font-size: clamp(2.4rem, 5vw, 3.5rem);
margin-bottom: 1.25rem;
color: var(--color-surface-light);
text-shadow: 0 2px 20px rgba(0, 0, 0, 0.3);
line-height: 1.15;
}
.hero p {
max-width: 520px;
font-size: 1.1rem;
line-height: 1.7;
color: rgba(248, 250, 252, 0.92);
text-shadow: 0 1px 8px rgba(0, 0, 0, 0.2);
}
.hero-card {
background: var(--color-card-bg);
color: var(--color-text-primary);
align-self: start;
padding: 1.75rem;
border-radius: 8px;
box-shadow: var(--shadow-lg);
text-align: left;
position: relative;
overflow: hidden;
/* Geometric accent */
border-left: 4px solid var(--color-accent-600);
}
.hero-card::before {
content: '';
position: absolute;
top: 0;
right: 0;
width: 80px;
height: 80px;
background: linear-gradient(
135deg,
transparent 50%,
rgba(37, 99, 235, 0.08) 50%
);
}
.hero-card .hero-special-events {
display: grid;
gap: 0.75rem;
width: 100%;
}
.hero-card .hero-special-events > * {
min-width: 0;
width: 100%;
}
.hero-card h2 {
margin-top: 0;
font-family: var(--font-heading);
font-size: 1.25rem;
color: var(--color-neutral-950);
}
.hero-card ul {
list-style: none;
padding-left: 0;
margin: 0;
display: grid;
gap: 0.25rem;
}
.hero-card li {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1.5rem;
font-weight: 500;
padding: 0.75rem 0.5rem;
border-bottom: 1px solid rgba(51, 65, 85, 0.1);
transition: background-color var(--transition-fast);
margin: 0 -0.5rem;
}
.hero-card li:hover {
background-color: rgba(51, 65, 85, 0.03);
}
.hero-card .hero-special-events li {
flex-direction: column;
align-items: flex-start;
justify-content: flex-start;
gap: 0.15rem;
margin-inline: 0;
min-width: 0;
}
.hero-card .hero-special-events li span:last-child {
color: var(--color-text-muted);
font-size: 0.9rem;
}
.hero-card li:last-child {
border-bottom: none;
}
.hero-card li:first-child {
padding-top: 0.5rem;
}
.hero-card .group-name {
font-weight: 700;
color: var(--color-neutral-700);
min-width: 0;
overflow-wrap: anywhere;
}
.hero-card .calendar-note {
max-width: none;
margin: 0;
padding-top: 0.75rem;
border-top: 1px solid rgba(51, 65, 85, 0.1);
font-size: 0.9rem;
color: var(--color-text-muted);
}
.hero-card .calendar-note a {
color: var(--color-accent-600);
font-weight: 600;
text-decoration: none;
transition: color var(--transition-fast);
}
.hero-card .calendar-note a:hover {
color: var(--color-accent-500);
text-decoration: underline;
}
.brand span {
color: inherit;
}
/* ============================================
CTA BUTTON
============================================ */
.cta {
display: inline-flex;
align-items: center;
gap: 0.5rem;
margin-top: 2rem;
padding: 0.9rem 2rem;
background: linear-gradient(
135deg,
var(--color-accent-600) 0%,
var(--color-accent-500) 100%
);
color: #fff;
font-weight: 700;
font-size: 1rem;
letter-spacing: 0.03em;
text-transform: uppercase;
border-radius: 4px;
box-shadow: 0 4px 20px rgba(37, 99, 235, 0.4);
transition: transform var(--transition-fast), box-shadow var(--transition-fast),
filter var(--transition-fast);
transform: translateZ(0);
position: relative;
overflow: hidden;
}
.cta::before {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(
135deg,
rgba(255, 255, 255, 0.2) 0%,
transparent 50%
);
opacity: 0;
transition: opacity var(--transition-fast);
}
.cta:hover {
box-shadow: 0 8px 30px rgba(37, 99, 235, 0.5), var(--shadow-glow);
filter: brightness(1.03);
}
.cta:hover::before {
opacity: 1;
}
.cta:active {
transform: translateY(1px);
}
/* ============================================
GROUP INFO - Featured Section
============================================ */
.group-info {
margin: 4rem auto 0;
}
.group-info-card {
background: var(--color-card-bg);
border-radius: 8px;
padding: 2.5rem;
box-shadow: var(--shadow-md);
display: grid;
gap: 1.5rem;
position: relative;
overflow: hidden;
/* Top accent bar */
border-top: 4px solid var(--color-neutral-700);
}
.group-info-card::before {
content: '';
position: absolute;
bottom: 0;
right: 0;
width: 150px;
height: 150px;
background: radial-gradient(
circle at bottom right,
rgba(51, 65, 85, 0.06) 0%,
transparent 70%
);
}
.group-info-card h2 {
margin: 0;
font-family: var(--font-heading);
color: var(--color-neutral-950);
font-size: 1.5rem;
}
.group-info-card > p {
color: var(--color-text-secondary);
font-size: 1.05rem;
line-height: 1.7;
margin: 0;
}
.group-schedule {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1.5rem;
margin-top: 0.5rem;
}
.group-schedule > div {
background: rgba(51, 65, 85, 0.04);
padding: 1.25rem 1.5rem;
border-radius: 6px;
border-left: 3px solid var(--color-accent-600);
transition: transform var(--transition-fast), box-shadow var(--transition-fast);
}
.group-schedule > div:hover {
transform: translateY(-2px);
box-shadow: var(--shadow-sm);
}
.group-schedule h3 {
margin: 0 0 0.5rem;
font-family: var(--font-heading);
font-size: 1rem;
color: var(--color-neutral-950);
}
.group-time {
font-weight: 700;
font-size: 1.15rem;
color: var(--color-accent-600);
margin: 0;
}
.group-note {
margin: 0 0 0.25rem;
color: var(--color-text-muted);
font-weight: 500;
font-size: 0.9rem;
}
/* Section intro text for content sections */
.section-intro {
color: var(--color-text-secondary);
font-size: 1.05rem;
margin-bottom: 0.5rem;
}
@media (max-width: 960px) {
.container {
padding-left: 1.25rem;
padding-right: 1.25rem;
}
.hero-content {
grid-template-columns: 1fr;
gap: 2.5rem;
}
}
@media (max-width: 768px) {
.hero {
background-image: linear-gradient(135deg, #0f172a, #334155);
padding: 3rem 0;
text-align: center;
}
.hero-content {
justify-items: center;
grid-template-columns: 1fr;
}
.hero h1 {
font-size: clamp(1.8rem, 6vw, 2.5rem);
}
.hero p {
margin: 0 auto;
font-size: 1rem;
}
.hero-card {
width: 100%;
max-width: 400px;
margin: 0 auto;
text-align: left;
}
.cta {
width: 100%;
text-align: center;
justify-content: center;
}
.group-info {
margin-top: 2.5rem;
}
.group-info-card {
padding: 1.5rem;
}
.group-schedule {
gap: 1rem;
}
.group-schedule > div {
padding: 1rem 1.25rem;
}
}
@media (max-width: 480px) {
.hero {
padding: 2.5rem 0;
min-height: auto;
}
.hero::after {
height: 100px;
}
.hero-card {
padding: 1.25rem;
}
.group-info-card h2 {
font-size: 1.25rem;
}
}
/* ============================================
ANIMATIONS & MICRO-INTERACTIONS
============================================ */
/* Fade in animation for page elements */
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/* Subtle glow pulse for CTA */
@keyframes glowPulse {
0%, 100% {
box-shadow: 0 4px 20px rgba(37, 99, 235, 0.4);
}
50% {
box-shadow: 0 4px 30px rgba(37, 99, 235, 0.6);
}
}
/* Hero section entrance */
.hero h1 {
animation: fadeInUp 0.6s ease-out;
}
.hero p {
animation: fadeInUp 0.6s ease-out 0.1s both;
}
.hero .cta {
animation: fadeInUp 0.6s ease-out 0.2s both;
}
.hero-card {
animation: fadeInUp 0.6s ease-out 0.3s both;
}
/* CTA glow effect on idle */
.cta {
animation: glowPulse 3s ease-in-out infinite;
}
/* Section headings with accent */
.group-info-card h2 {
position: relative;
display: inline-block;
}
.group-info-card h2::after {
content: '';
position: absolute;
bottom: -4px;
left: 0;
width: 40px;
height: 3px;
background: var(--color-accent-600);
border-radius: 2px;
}
+476
View File
@@ -0,0 +1,476 @@
/* ============================================
HEADER - Modern Scout Navigation
============================================ */
.app-header {
background: var(--color-header-bg);
color: var(--color-text-primary);
position: sticky;
top: 0;
z-index: 100;
border-bottom: none;
box-shadow: var(--shadow-sm);
}
.app-header::after {
content: '';
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 4px;
background: linear-gradient(
to right,
var(--color-neutral-950) 0%,
var(--color-neutral-700) 40%,
var(--color-accent-600) 70%,
var(--color-accent-500) 100%
);
pointer-events: none;
}
.header-content {
display: flex;
align-items: center;
justify-content: space-between;
gap: 2rem;
padding-top: 1.25rem;
padding-bottom: 1.25rem;
}
.brand {
display: inline-flex;
align-items: center;
gap: 0.85rem;
font-family: var(--font-heading);
font-size: 1.05rem;
font-weight: 700;
letter-spacing: 0.01em;
color: var(--color-text-primary);
transition: opacity var(--transition-fast);
}
.brand:hover {
opacity: 0.85;
}
.brand-logo {
height: 46px;
width: auto;
display: block;
filter: drop-shadow(0 2px 4px rgba(15, 23, 42, 0.1));
}
.nav-links {
display: flex;
align-items: center;
gap: 0.5rem;
}
.nav-links a {
color: var(--color-text-secondary);
font-weight: 600;
font-size: 0.95rem;
letter-spacing: 0.02em;
text-transform: uppercase;
padding: 0.5rem 0.9rem;
border-radius: 4px;
position: relative;
white-space: nowrap;
transition: color var(--transition-fast), background-color var(--transition-fast);
}
.nav-links a::after {
content: '';
position: absolute;
bottom: 0;
left: 50%;
width: 0;
height: 2px;
background: var(--color-accent-600);
transition: width var(--transition-base), left var(--transition-base);
}
.nav-links a:hover {
color: var(--color-text-primary);
background-color: rgba(51, 65, 85, 0.06);
}
.nav-links a:hover::after {
width: 60%;
left: 20%;
}
.nav-links a.active {
color: var(--color-neutral-700);
background-color: rgba(51, 65, 85, 0.1);
}
.nav-links a.active::after {
width: 80%;
left: 10%;
background: var(--color-neutral-700);
}
.nav-toggle {
display: none;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
padding: 0;
border-radius: 10px;
border: 1px solid rgba(51, 65, 85, 0.2);
background: rgba(255, 255, 255, 0.85);
cursor: pointer;
transition: background-color var(--transition-fast),
border-color var(--transition-fast);
transform: none;
}
.nav-toggle[data-open="true"] {
border-color: rgba(51, 65, 85, 0.35);
background: rgba(255, 255, 255, 1);
}
.nav-toggle:hover {
background: rgba(255, 255, 255, 1);
border-color: rgba(51, 65, 85, 0.3);
box-shadow: var(--shadow-sm);
transform: none;
}
.nav-toggle-bars {
display: grid;
gap: 5px;
}
.nav-toggle-bars span {
width: 22px;
height: 2px;
border-radius: 999px;
background: var(--color-neutral-950);
transition: background-color var(--transition-fast);
}
.link-button {
background: none;
border: none;
color: var(--color-text-secondary);
font: inherit;
cursor: pointer;
border-radius: 4px;
padding: 0.5rem 0.9rem;
font-weight: 600;
font-size: 0.95rem;
letter-spacing: 0.02em;
text-transform: uppercase;
transition: color var(--transition-fast), background-color var(--transition-fast);
}
.link-button:hover {
color: var(--color-text-primary);
background-color: rgba(51, 65, 85, 0.08);
}
/* ============================================
FOOTER - Footer
============================================ */
.app-footer {
background: var(--color-footer-bg);
color: var(--color-text-on-dark);
padding: 3rem 0 2rem;
margin-top: 5rem;
position: relative;
/* Neutral gradient overlay */
background-image:
linear-gradient(to bottom, var(--color-neutral-950) 0%, var(--color-neutral-800) 100%);
}
.app-footer::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: linear-gradient(
to right,
var(--color-accent-600) 0%,
var(--color-accent-500) 30%,
var(--color-accent-400) 50%,
var(--color-accent-500) 70%,
var(--color-accent-600) 100%
);
}
.footer-content {
display: flex;
flex-direction: column;
gap: 2rem;
}
.footer-top {
display: flex;
flex-wrap: wrap;
gap: 2.5rem;
justify-content: space-between;
}
.footer-column {
flex: 1 1 240px;
min-width: 220px;
align-self: stretch;
}
.footer-links {
text-align: right;
}
.footer-heading {
margin: 0 0 1rem;
font-family: var(--font-heading);
font-size: 1.1rem;
font-weight: 700;
color: var(--color-surface-light);
letter-spacing: 0.02em;
position: relative;
padding-bottom: 0.5rem;
}
.footer-heading::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 2rem;
height: 2px;
background: var(--color-accent-600);
}
.footer-links .footer-heading::after {
left: auto;
right: 0;
}
.footer-contact address {
display: grid;
gap: 0.6rem;
margin: 0;
font-style: normal;
}
.footer-contact-item {
display: flex;
align-items: center;
gap: 0.75rem;
line-height: 1.4;
font-size: 0.95rem;
}
.footer-contact-icon {
width: 1.2rem;
height: 1.2rem;
flex-shrink: 0;
color: var(--color-accent-500);
opacity: 0.9;
}
.footer-links ul {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.5rem;
justify-items: end;
}
.footer-contact a,
.footer-links a,
.footer-legal a {
color: rgba(248, 250, 252, 0.85);
transition: color var(--transition-fast);
text-decoration: none;
font-size: 0.95rem;
}
.footer-contact a:hover,
.footer-links a:hover,
.footer-legal a:hover {
color: var(--color-accent-400);
}
.footer-bottom {
display: flex;
flex-wrap: wrap;
gap: 1rem 2rem;
justify-content: space-between;
align-items: center;
border-top: 1px solid rgba(248, 250, 252, 0.12);
padding-top: 1.25rem;
font-size: 0.9rem;
color: rgba(248, 250, 252, 0.7);
}
.footer-legal {
display: flex;
gap: 1.5rem;
}
@media (max-width: 720px) {
.app-footer {
padding: 1rem 0 1.25rem;
}
.footer-content {
gap: 1rem;
}
.footer-top {
flex-direction: column;
gap: 1rem;
align-items: center;
text-align: center;
}
.footer-heading {
margin-bottom: 0.5rem;
}
.footer-links {
text-align: center;
}
.footer-links ul {
justify-items: center;
gap: 0.2rem;
}
.footer-contact address {
gap: 0.18rem;
justify-items: center;
text-align: center;
}
.footer-contact-item {
justify-content: center;
}
.footer-bottom {
flex-direction: column;
align-items: center;
gap: 0.45rem;
padding-top: 0.6rem;
text-align: center;
}
.footer-legal {
order: -1;
justify-content: center;
}
.footer-column {
flex: none;
min-width: 0;
width: 100%;
align-self: auto;
}
}
@media (max-width: 1100px) {
.container {
padding-left: clamp(1rem, 3vw, 1.5rem);
padding-right: clamp(1rem, 3vw, 1.5rem);
}
}
@media (max-width: 1080px) {
.header-content {
flex-wrap: wrap;
gap: 1rem;
padding-top: 1.1rem;
padding-bottom: 1.1rem;
}
.brand {
font-size: 1rem;
}
.brand span {
max-width: 260px;
}
.brand-logo {
height: 42px;
}
.nav-toggle {
display: inline-flex;
}
.nav-links {
display: none;
width: 100%;
flex-basis: 100%;
flex-direction: column;
align-items: stretch;
gap: 0.35rem;
padding-bottom: 0.75rem;
}
.nav-links[data-open="true"] {
display: flex;
}
.nav-links a {
text-align: left;
font-size: 0.9rem;
padding: 0.55rem 0.9rem;
}
}
@media (max-width: 768px) {
.header-content {
gap: 0.75rem;
padding-top: 1rem;
padding-bottom: 1rem;
}
.nav-links a {
font-size: 0.85rem;
padding: 0.4rem 0.7rem;
}
.app-footer {
margin-top: 3rem;
}
}
@media (max-width: 480px) {
.container {
padding-left: 1rem;
padding-right: 1rem;
}
.brand {
font-size: 0.95rem;
gap: 0.6rem;
}
.brand span {
max-width: 180px;
line-height: 1.2;
}
.brand-logo {
height: 38px;
}
.header-content {
padding-top: 0.9rem;
padding-bottom: 0.9rem;
}
.footer-heading::after {
display: none;
}
}
+302
View File
@@ -0,0 +1,302 @@
/* ── V2 Info Cards (Informationen page) ── */
.info-grid--v2 {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
margin: 0;
}
.info-card-v2 {
background: #fff;
border-radius: 10px;
padding: 1.5rem 1.5rem 1.75rem;
box-shadow: var(--shadow-sm);
border: 1px solid rgba(71, 85, 105, 0.1);
border-left: 3px solid rgba(71, 85, 105, 0.2);
}
.info-card-v2 h3 {
font-family: var(--font-heading);
font-size: 1.05rem;
margin: 0 0 0.5rem;
color: var(--color-neutral-950);
}
.info-card-v2 p {
margin: 0 0 0.5rem;
font-size: 0.92rem;
line-height: 1.7;
color: var(--color-text-secondary);
}
.info-card-v2 p:last-child {
margin-bottom: 0;
}
.price-table {
margin: 1rem 0 1.1rem;
border-radius: 10px;
overflow: hidden;
border: 1px solid rgba(71, 85, 105, 0.12);
background: linear-gradient(
180deg,
rgba(250, 251, 248, 0.96),
rgba(244, 247, 243, 0.98)
);
}
.price-table__row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.8rem 1rem;
border-bottom: 1px solid rgba(71, 85, 105, 0.1);
}
.price-table__row:last-child {
border-bottom: 0;
}
.price-table__item,
.price-table__value {
font-size: 0.94rem;
line-height: 1.4;
}
.price-table__item {
color: var(--color-neutral-950);
font-weight: 600;
}
.price-table__value {
color: var(--color-text-primary);
font-weight: 700;
white-space: nowrap;
}
/* ── Optional media section ── */
.hemd-figure {
margin: 0;
display: flex;
justify-content: center;
padding: 0.5rem;
border-radius: 16px;
background: linear-gradient(
180deg,
rgba(255, 255, 255, 0.96),
rgba(247, 244, 236, 0.92)
);
box-shadow: var(--shadow-sm);
border: 1px solid rgba(71, 85, 105, 0.1);
}
.about-v2--info .hemd-figure {
padding: 0.5rem;
}
.hemd-figure picture {
display: block;
width: min(100%, 560px);
margin-inline: auto;
}
.hemd-figure img {
display: block;
width: 100%;
height: auto;
}
/* ── Packliste Section ── */
.packliste__intro {
max-width: 720px;
margin-bottom: 2rem;
}
.packliste__intro p {
font-size: 1rem;
line-height: 1.75;
color: var(--color-text-secondary);
margin: 0 0 0.75rem;
}
.packliste__intro p:last-child {
margin-bottom: 0;
}
/* Callout boxes (Grundsätzlich wichtig, Handyfreie Zeit) */
.packliste__callout {
display: flex;
gap: 1rem;
background: #fff;
border-radius: 10px;
padding: 1.25rem 1.5rem;
margin-bottom: 2rem;
box-shadow: var(--shadow-sm);
border: 1px solid rgba(71, 85, 105, 0.1);
border-left: 3px solid var(--color-neutral-500);
}
.packliste__callout-icon {
flex-shrink: 0;
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 8px;
background: rgba(51, 65, 85, 0.08);
color: var(--color-neutral-500);
margin-top: 0.1rem;
}
.packliste__callout-body h4 {
font-family: var(--font-heading);
font-size: 1rem;
color: var(--color-neutral-950);
margin: 0 0 0.5rem;
}
.packliste__callout-body p {
font-size: 0.92rem;
line-height: 1.7;
color: var(--color-text-secondary);
margin: 0 0 0.5rem;
}
.packliste__callout-body p:last-child {
margin-bottom: 0;
}
.packliste__callout--note {
border-left-color: var(--color-accent-600);
}
.packliste__callout--note .packliste__callout-icon {
background: rgba(37, 99, 235, 0.08);
color: var(--color-accent-600);
}
/* Equipment items grid */
.packliste__grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1.25rem;
margin-bottom: 2rem;
}
.packliste__item {
background: #fff;
border-radius: 10px;
padding: 1.25rem 1.5rem 1.5rem;
box-shadow: var(--shadow-sm);
border: 1px solid rgba(71, 85, 105, 0.08);
border-top: 2px solid rgba(71, 85, 105, 0.18);
transition: box-shadow var(--transition-base), transform var(--transition-base);
}
.packliste__item:hover {
box-shadow: var(--shadow-md);
transform: translateY(-2px);
}
.packliste__item-header {
display: flex;
align-items: center;
gap: 0.6rem;
margin-bottom: 0.65rem;
}
.packliste__item-icon {
flex-shrink: 0;
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 7px;
background: rgba(51, 65, 85, 0.07);
color: var(--color-neutral-500);
}
.packliste__item-header h4 {
font-family: var(--font-heading);
font-size: 0.98rem;
color: var(--color-neutral-950);
margin: 0;
}
.packliste__item p {
font-size: 0.9rem;
line-height: 1.7;
color: var(--color-text-secondary);
margin: 0 0 0.5rem;
}
.packliste__item p:last-child {
margin-bottom: 0;
}
.packliste__item ul {
margin: 0.25rem 0 0.6rem 1.1rem;
padding: 0;
color: var(--color-text-secondary);
}
.packliste__item li {
margin-bottom: 0.15rem;
font-size: 0.9rem;
line-height: 1.65;
}
/* Tips footer */
.packliste__tips {
background: #fff;
border-radius: 10px;
padding: 1.25rem 1.5rem;
box-shadow: var(--shadow-sm);
border: 1px solid rgba(71, 85, 105, 0.08);
border-left: 3px solid var(--color-neutral-200);
}
.packliste__tips h4 {
font-family: var(--font-heading);
font-size: 1rem;
color: var(--color-neutral-950);
margin: 0 0 0.5rem;
}
.packliste__tips p {
font-size: 0.92rem;
line-height: 1.7;
color: var(--color-text-secondary);
margin: 0 0 0.5rem;
}
.packliste__tips p:last-child {
margin-bottom: 0;
}
/* Responsive: stack on small screens */
@media (max-width: 640px) {
.hemd-figure {
padding: 0.35rem;
}
.about-v2--info .hemd-figure {
padding: 0.35rem;
}
.price-table__row {
padding: 0.75rem 0.9rem;
}
.packliste__grid {
grid-template-columns: 1fr;
}
.packliste__callout {
flex-direction: column;
gap: 0.75rem;
}
}
+321
View File
@@ -0,0 +1,321 @@
/* ============================================
POST CARDS - Trip Reports
============================================ */
.post-grid {
display: grid;
gap: 1.75rem;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
margin-top: 2rem;
}
.post-grid--v2 {
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}
.page-spacing .post-grid {
grid-template-columns: 1fr;
}
.post-card {
background: var(--color-card-bg);
border-radius: 8px;
padding: 1.75rem;
box-shadow: var(--shadow-md);
display: flex;
flex-direction: column;
gap: 1rem;
position: relative;
border-left: 4px solid var(--color-neutral-700);
transition: transform var(--transition-fast), box-shadow var(--transition-fast), border-color var(--transition-fast);
}
.post-card:hover:not(.post-card-link .post-card) {
transform: translateY(-4px);
box-shadow: var(--shadow-lg);
border-color: var(--color-accent-600);
}
.post-detail-page {
display: grid;
gap: 1.5rem;
}
.back-link {
color: var(--color-accent-600);
font-weight: 600;
text-decoration: none;
display: inline-flex;
align-items: center;
gap: 0.5rem;
transition: color var(--transition-fast), gap var(--transition-fast);
}
.back-link:hover {
color: var(--color-accent-500);
gap: 0.75rem;
}
.post-detail-page .back-link {
margin-top: 0.5rem;
}
.post-detail-card {
gap: 1.5rem;
border-left: none;
border-top: 4px solid var(--color-neutral-700);
}
.post-detail-card:hover {
transform: none;
border-color: var(--color-neutral-700);
}
.post-detail-card header h1 {
margin: 0 0 0.75rem;
font-family: var(--font-heading);
font-size: clamp(2rem, 5vw, 2.75rem);
color: var(--color-neutral-950);
overflow-wrap: anywhere;
word-break: break-word;
hyphens: auto;
}
.post-detail-card .post-meta {
margin: 0;
color: var(--color-text-muted);
font-weight: 500;
}
.post-card-link {
text-decoration: none;
color: inherit;
display: flex;
flex-direction: column;
height: 100%;
}
.post-card-link:hover .post-preview-card {
transform: translateY(-4px);
box-shadow: var(--shadow-lg);
border-color: var(--color-accent-600);
}
.post-card-link:hover .post-preview-link {
color: var(--color-accent-500);
}
.post-card-link:hover .post-preview-link::after {
transform: translateX(4px);
}
.post-preview-card {
gap: 1rem;
flex: 1;
}
.post-preview-card h3 {
margin: 0;
font-family: var(--font-heading);
font-size: 1.2rem;
color: var(--color-neutral-950);
overflow-wrap: anywhere;
word-break: break-word;
hyphens: auto;
}
.post-preview-text {
margin: 0;
color: var(--color-text-secondary);
line-height: 1.7;
}
.post-preview-link {
margin-top: auto;
align-self: flex-start;
font-weight: 700;
color: var(--color-accent-600);
text-decoration: none;
display: inline-flex;
align-items: center;
gap: 0.35rem;
transition: color var(--transition-fast), gap var(--transition-fast);
}
.post-preview-link::after {
content: '\2192';
transition: transform var(--transition-fast);
}
.post-preview-link:hover {
color: var(--color-accent-500);
}
.post-preview-link:hover::after {
transform: translateX(4px);
}
.post-meta {
margin: 0.4rem 0 0;
color: var(--color-text-muted);
font-size: 0.9rem;
}
.muted {
color: var(--color-text-muted);
}
.error {
color: #b91c1c;
margin-top: 0.75rem;
padding: 0.75rem 1rem;
background: rgba(185, 28, 28, 0.08);
border-radius: 6px;
border-left: 3px solid #b91c1c;
}
/* Error styling specifically for hero card context */
.hero-card .error {
color: #991b1b;
background: rgba(185, 28, 28, 0.12);
border-left-color: #dc2626;
font-weight: 500;
}
.card {
background: var(--color-card-bg);
border-radius: 8px;
padding: 1.75rem;
box-shadow: var(--shadow-md);
margin-top: 2rem;
}
/* ============================================
MARKDOWN CONTENT
============================================ */
.markdown-content,
.markdown-preview {
line-height: 1.75;
color: var(--color-text-secondary);
}
.markdown-content p {
margin: 1rem 0;
}
.markdown-content figure {
margin: 2rem auto;
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem;
}
.markdown-content img {
max-width: 100%;
height: auto;
}
.markdown-content .post-image {
width: min(680px, 100%);
border-radius: 8px;
box-shadow: var(--shadow-lg);
}
.markdown-content .post-caption {
width: min(640px, 100%);
text-align: center;
font-size: 0.9rem;
color: var(--color-text-muted);
font-style: italic;
}
.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-preview h1,
.markdown-preview h2,
.markdown-preview h3,
.markdown-preview h4 {
font-family: var(--font-heading);
color: var(--color-neutral-950);
margin-top: 2rem;
margin-bottom: 0.75rem;
}
.markdown-content p,
.markdown-preview p {
margin: 1rem 0;
text-align: justify;
}
.markdown-content ul,
.markdown-content ol,
.markdown-preview ul,
.markdown-preview ol {
padding-left: 1.5rem;
margin: 1rem 0;
}
.markdown-content li,
.markdown-preview li {
margin: 0.5rem 0;
}
.markdown-content code,
.markdown-preview code {
background: rgba(51, 65, 85, 0.1);
color: var(--color-neutral-950);
padding: 0.15rem 0.4rem;
border-radius: 4px;
font-size: 0.9em;
}
.markdown-content pre,
.markdown-preview pre {
background: var(--color-neutral-950);
color: var(--color-surface-light);
padding: 1rem 1.25rem;
border-radius: 8px;
overflow-x: auto;
margin: 1.5rem 0;
}
.markdown-content pre code,
.markdown-preview pre code {
background: transparent;
padding: 0;
color: inherit;
}
.markdown-content {
margin-top: 1rem;
}
.markdown-content > :first-child,
.markdown-preview > :first-child {
margin-top: 0;
}
.markdown-content > :last-child,
.markdown-preview > :last-child {
margin-bottom: 0;
}
@media (max-width: 768px) {
.post-grid {
grid-template-columns: 1fr;
}
.post-detail-page .back-link {
margin-top: 1.25rem;
}
}
@media (max-width: 480px) {
.post-card {
padding: 1.25rem;
border-left-width: 3px;
}
}
+19
View File
@@ -0,0 +1,19 @@
import type { TripReportModule } from "./types";
// Register project-specific report modules here. The starter is intentionally empty.
const tripReports: readonly TripReportModule[] = [
];
const tripReportsBySlug = new Map(
tripReports.map((tripReport) => [tripReport.metadata.slug, tripReport] as const),
);
export function getAllTripReports(): readonly TripReportModule[] {
return tripReports;
}
export function getTripReport(slug: string): TripReportModule | undefined {
return tripReportsBySlug.get(slug);
}
export type { TripReportModule } from "./types";
+17
View File
@@ -0,0 +1,17 @@
import type { ComponentType } from "react";
export interface TripReportMetadata {
slug: string;
title: string;
author: string;
createdAt: string;
updatedAt: string;
published: boolean;
excerpt: string;
plainText: string;
}
export interface TripReportModule {
metadata: TripReportMetadata;
Component: ComponentType;
}
+66
View File
@@ -0,0 +1,66 @@
/**
* @fileoverview Zentrale TypeScript-Definitionen der Website
*
* Diese Datei enthält die zentralen TypeScript-Schnittstellen für alle Datenstrukturen
* der Anwendung, einschließlich Beiträge, Kalenderereignisse und Downloads.
*/
/**
* Metadaten eines Beitrags
* @interface PostMetadata
* @property {string} id - Eindeutige ID des Beitrags
* @property {string} title - Titel des Beitrags
* @property {string} author - Name des Autors
* @property {Date} createdAt - Erstellungsdatum
* @property {Date} updatedAt - Letztes Änderungsdatum
* @property {boolean} published - Gibt an, ob der Beitrag veröffentlicht ist
* @property {string} [excerpt] - Kurzbeschreibung des Beitrags
* @property {string} [plainText] - Reiner Textinhalt (ohne Markdown)
*/
export interface PostMetadata {
id: string;
title: string;
author: string;
createdAt: Date;
updatedAt: Date;
published: boolean;
excerpt?: string;
plainText?: string;
}
/**
* Ein Kalenderereignis
* @interface CalendarEvent
* @property {string} id - Eindeutige ID des Ereignisses
* @property {string} title - Titel des Ereignisses
* @property {string|null} description - Detailierte Beschreibung des Ereignisses
* @property {string|null} location - Ort des Ereignisses
* @property {string} start - Startzeitpunkt (ISO-Format)
* @property {string} end - Endzeitpunkt (ISO-Format)
* @property {boolean} allDay - Gibt an, ob das Ereignis den ganzen Tag dauert
* @property {string} timeZone - Zeitzone des Ereignisses (z.B. "Europe/Berlin")
*/
export interface CalendarEvent {
id: string;
title: string;
description: string | null;
location: string | null;
start: string;
end: string;
allDay: boolean;
timeZone: string;
special: boolean;
}
/**
* Ein Download-Objekt für Dokumente und Dateien
* @interface Download
* @property {string} name - Dateiname
* @property {string} description - Kurzbeschreibung der Datei
* @property {string} download_url - URL zum Herunterladen der Datei
*/
export interface Download {
name: string;
description: string;
download_url: string;
}
+108
View File
@@ -0,0 +1,108 @@
/**
* @fileoverview Hilfsfunktionen zum Formatieren von Kalender-Events
*
* Diese Module bietet Funktionen zur Formatierung von Event-Start- und Endzeiten
* in deutsches Format, Handling von ganztägigen Events und Berechnung der
* effektiven Endzeit eines Events.
*
* @module utils/eventFormat
*/
import type { CalendarEvent } from "../types";
// Dauer eines Tages in Millisekunden
const DAY_IN_MS = 24 * 60 * 60 * 1000;
/**
* Formatiert ein Datum für den Vergleich
*
* Wandelt ein Date-Objekt in ein formatiertes String um (JJJJ-MM-TT) unter
* Berücksichtigung der angegebenen Zeitzone.
*
* @param date - Das zu formatierende Datum
* @param timeZone - Die Zeitzone (z.B. "Europe/Berlin")
* @returns Formattierte Datums-ID für Vergleichszwecke
*/
function formatDateKey(date: Date, timeZone: string) {
return new Intl.DateTimeFormat("en-CA", {
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(date);
}
/**
* Berechnet die effektive Endzeit eines Events
*
* Für ganztägige Events wird die Endzeit auf 23:59:59.999 gesetzt, um
* sicherzustellen, dass das Event am gesamten Tag sichtbar bleibt.
* Für mehrday-Events wird die Endzeit korrekt berechnet.
*
* @param event - Das Event, dessen Endzeit berechnet werden soll
* @returns Die effektive Endzeit des Events
*/
export function getEffectiveEventEnd(event: CalendarEvent): Date {
const end = new Date(event.end);
if (event.allDay) {
end.setHours(23, 59, 59, 999);
}
return end;
}
/**
* Formatiert den Zeitraum eines Events für die Anzeige
*
* Generiert einen benutzerfreundlichen String, der das Start- und Enddatum
* (und Uhrzeit) des Events enthält. Die Daten werden in deutschem Format
* angezeigt, wobei die Zeitzone des Events berücksichtigt wird.
*
* Ganztägige Events und mehrday-Events werden korrekt verküpft oder
* zusammengefasst.
*
* @param event - Das zu formatierende Event
* @returns Formattierter Zeitraum (z.B. "15. Januar 2025 · 14:00 – 18:00")
*
* @example
* ```typescript
* formatEventDateRange(event) // returns "15. Januar 2025 · 14:00 – 18:00"
* ```
*/
export function formatEventDateRange(event: CalendarEvent) {
const startDate = new Date(event.start);
const endDate = new Date(event.end);
const dateFormatter = new Intl.DateTimeFormat("de-DE", {
dateStyle: "long",
timeZone: event.timeZone,
});
const timeFormatter = new Intl.DateTimeFormat("de-DE", {
timeStyle: "short",
timeZone: event.timeZone,
});
if (event.allDay) {
const inclusiveEnd =
endDate.getTime() > startDate.getTime()
? new Date(endDate.getTime() - DAY_IN_MS)
: startDate;
const startKey = formatDateKey(startDate, event.timeZone);
const endKey = formatDateKey(inclusiveEnd, event.timeZone);
if (startKey === endKey) {
return dateFormatter.format(startDate);
}
return `${dateFormatter.format(startDate)} – ${dateFormatter.format(
inclusiveEnd
)}`;
}
const startKey = formatDateKey(startDate, event.timeZone);
const endKey = formatDateKey(endDate, event.timeZone);
if (startKey === endKey) {
return `${dateFormatter.format(startDate)} · ${timeFormatter.format(
startDate
)} – ${timeFormatter.format(endDate)}`;
}
return `${dateFormatter.format(startDate)} ${timeFormatter.format(
startDate
)} – ${dateFormatter.format(endDate)} ${timeFormatter.format(endDate)}`;
}
+223
View File
@@ -0,0 +1,223 @@
import type { CalendarEvent } from "../types";
import { formatEventDateRange, getEffectiveEventEnd } from "./eventFormat";
const HERO_SPECIAL_LIMIT = 5;
export interface CalendarEventGroup {
label: string;
events: CalendarEvent[];
}
export function filterUpcomingEvents(events: CalendarEvent[], now = new Date()): CalendarEvent[] {
const limit = new Date(now);
limit.setUTCHours(23, 59, 59, 999);
limit.setUTCMonth(limit.getUTCMonth() + 12);
return events
.filter((event) => {
const start = new Date(event.start);
return getEffectiveEventEnd(event) >= now && start <= limit;
})
.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime());
}
export function getSpecialEvents(events: CalendarEvent[], now = new Date()): CalendarEvent[] {
return events
.filter((event) => event.special && getEffectiveEventEnd(event) >= now)
.slice(0, HERO_SPECIAL_LIMIT);
}
export function getCalendarGroups(
events: CalendarEvent[],
now = new Date(),
): CalendarEventGroup[] {
const upcomingEvents = filterUpcomingEvents(events, now);
const groups = new Map<string, CalendarEventGroup>();
for (const event of upcomingEvents) {
const start = new Date(event.start);
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: event.timeZone,
year: "numeric",
month: "2-digit",
}).formatToParts(start);
const year = parts.find((part) => part.type === "year")?.value;
const month = parts.find((part) => part.type === "month")?.value;
const key = `${year}-${month}`;
if (!groups.has(key)) {
groups.set(key, {
label: new Intl.DateTimeFormat("de-DE", {
month: "long",
year: "numeric",
timeZone: event.timeZone,
}).format(start),
events: [],
});
}
groups.get(key)?.events.push(event);
}
return Array.from(groups.values());
}
function createMessageElement(
documentRef: Document,
className: string,
message: string,
): HTMLParagraphElement {
const element = documentRef.createElement("p");
element.className = className;
element.textContent = message;
return element;
}
export function createSpecialEventsFragment(
documentRef: Document,
events: CalendarEvent[],
): DocumentFragment {
const fragment = documentRef.createDocumentFragment();
const specialEvents = getSpecialEvents(events);
if (!specialEvents.length) {
fragment.append(
createMessageElement(
documentRef,
"muted",
"Aktuell sind keine besonderen Termine geplant.",
),
);
return fragment;
}
const wrapper = documentRef.createElement("div");
wrapper.className = "hero-special-events";
const list = documentRef.createElement("ul");
const dateFormatter = new Intl.DateTimeFormat("de-DE", { dateStyle: "long" });
for (const event of specialEvents) {
const item = documentRef.createElement("li");
const title = documentRef.createElement("span");
title.className = "group-name";
title.textContent = event.title;
const date = documentRef.createElement("span");
date.textContent = dateFormatter.format(new Date(event.start));
item.append(title, date);
list.append(item);
}
const note = documentRef.createElement("p");
note.className = "calendar-note";
note.append("Alle Termine mit weiteren Details findest Du im ");
const link = documentRef.createElement("a");
link.href = "/kalender";
link.textContent = "Kalender";
note.append(link, ".");
wrapper.append(list, note);
fragment.append(wrapper);
return fragment;
}
export function createCalendarFragment(
documentRef: Document,
events: CalendarEvent[],
): DocumentFragment {
const fragment = documentRef.createDocumentFragment();
const groups = getCalendarGroups(events);
if (!groups.length) {
fragment.append(
createMessageElement(
documentRef,
"muted",
"In den nächsten 12 Monaten sind noch keine Termine geplant.",
),
);
return fragment;
}
const wrapper = documentRef.createElement("div");
wrapper.className = "calendar-table";
for (const group of groups) {
const month = documentRef.createElement("section");
month.className = "calendar-table-month";
month.setAttribute("aria-label", group.label);
const heading = documentRef.createElement("h2");
heading.className = "calendar-month-heading";
heading.textContent = group.label;
const table = documentRef.createElement("div");
table.className = "calendar-table-grid";
table.setAttribute("role", "table");
const headerRow = documentRef.createElement("div");
headerRow.className = "calendar-table-row calendar-table-row-head";
headerRow.setAttribute("role", "row");
const titleHeader = documentRef.createElement("span");
titleHeader.className = "calendar-table-title";
titleHeader.setAttribute("role", "columnheader");
titleHeader.textContent = "Termin";
const dateHeader = documentRef.createElement("span");
dateHeader.className = "calendar-table-date";
dateHeader.setAttribute("role", "columnheader");
dateHeader.textContent = "Datum & Uhrzeit";
headerRow.append(titleHeader, dateHeader);
table.append(headerRow);
for (const event of group.events) {
const row = documentRef.createElement("div");
row.className = "calendar-table-row";
row.setAttribute("role", "row");
const titleCell = documentRef.createElement("span");
titleCell.className = "calendar-table-title";
titleCell.setAttribute("role", "cell");
const titleWrapper = documentRef.createElement("span");
titleWrapper.className = "calendar-event-title";
if (event.special) {
const highlight = documentRef.createElement("span");
highlight.className = "calendar-highlight";
highlight.textContent = "★";
titleWrapper.append(highlight, " ");
}
titleWrapper.append(event.title);
titleCell.append(titleWrapper);
if (event.location) {
const location = documentRef.createElement("span");
location.className = "calendar-event-location";
location.textContent = `, ${event.location}`;
titleCell.append(location);
}
const dateCell = documentRef.createElement("span");
dateCell.className = "calendar-table-date";
dateCell.setAttribute("role", "cell");
dateCell.textContent = formatEventDateRange(event);
row.append(titleCell, dateCell);
table.append(row);
}
month.append(heading, table);
wrapper.append(month);
}
fragment.append(wrapper);
return fragment;
}
+8
View File
@@ -0,0 +1,8 @@
export function serializeJsonLd(value: unknown): string {
return JSON.stringify(value)
.replaceAll("<", "\\u003C")
.replaceAll(">", "\\u003E")
.replaceAll("&", "\\u0026")
.replaceAll("\u2028", "\\u2028")
.replaceAll("\u2029", "\\u2029");
}
+64
View File
@@ -0,0 +1,64 @@
/**
* @fileoverview Hilfsfunktionen für die Behandlung von Beiträgen (Posts)
*
* Dieses Modul bietet Funktionen zum Sortieren von Beiträgen und Extrahieren von
* Textinhalten aus Markdown.
*
* @module utils/postUtils
*/
import type { PostMetadata } from "../types";
/**
* Sortiert eine Liste von Beiträgen nach Erstellungsdatum (neueste zuerst)
*
* @param {PostMetadata[]} posts - Array von Beitrags-Metadaten
* @returns {PostMetadata[]} Sortiertes Array (neueste zuerst)
*/
export function sortPostsByCreatedDate(posts: PostMetadata[]): PostMetadata[] {
return [...posts].sort((a, b) => {
const dateB = b.createdAt.getTime();
const dateA = a.createdAt.getTime();
return dateB - dateA;
});
}
/**
* Extrahiert reinen Text aus Markdown-Inhalten
*
* Entfernt HTML-Tags, Markdown-Syntax (Headings, Bold, etc.), Links und
* normalisiert Whitespace für eine saubere Textdarstellung.
*
* @param {string} content - Markdown-Textinhalt
* @returns {string} Reiner Textinhalt ohne Markdown-Syntax
*/
export function extractPlainText(content: string): string {
return content
.replace(/<[^>]+>/g, " ")
.replace(/[#>*_`~\\-]+/g, " ")
.replace(/\[(.*?)\]\(.*?\)/g, "$1")
.replace(/\s+/g, " ")
.trim();
}
/**
* Erstellt einen kurzen Auszug (Excerpt) aus Text
*
* Schneidet den Text nach der maxLength ab und fügt "..." hinzu,
* wenn der Text zu lang ist.
*
* @param {string} plainText - Der zu kürzende Text
* @param {number} maxLength - Maximale Länge des Auszugs
* @returns {string} Der gekürzte Auszug
*
* @example
* ```typescript
* createExcerpt("Das ist ein sehr langer Text", 10) // returns "Das ist e..."
* ```
*/
export function createExcerpt(plainText: string, maxLength: number): string {
if (plainText.length <= maxLength) {
return plainText;
}
return `${plainText.slice(0, Math.max(0, maxLength - 3))}...`;
}