Werkstatt-App: öffentliche PWA und Redaktions-Backend

Werbefreie, barrierearme Info-App für Werkstätten (WfbM) auf Basis von
SvelteKit, Tailwind, SQLite/Drizzle:

- App: Startseite mit Kacheln, Meldungen, Seitenbaum, Termine inkl.
  Schließzeiten und iCal-Abo, Ansprechpartner, Suche, Kontaktformular,
  Merkliste, Vorlesen, Leichte Sprache, Schriftgrößen, Hell/Dunkel, PWA
- Redaktion: Dashboard, Meldungen, Seiten, Termine, Kacheln,
  Ansprechpartner, Mediathek mit Bildoptimierung, Postfach, Benutzer
  mit Rollen, Einstellungen (Name, Logo, Farbe, Rechtstexte)
- Demo-Seed, CLI zum Anlegen von Benutzern, Dockerfile und Compose

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-29 20:55:13 +00:00
parent 4f145116d8
commit bef8574e07
143 changed files with 13518 additions and 1 deletions

View file

@ -0,0 +1,42 @@
<script lang="ts">
import { untrack } from 'svelte';
import Paperclip from '@lucide/svelte/icons/paperclip';
import X from '@lucide/svelte/icons/x';
import FileText from '@lucide/svelte/icons/file-text';
import MediaPicker from './MediaPicker.svelte';
import type { AttachmentItem } from '$lib/types';
let { name, value = [] }: { name: string; value?: AttachmentItem[] } = $props();
let items = $state(untrack(() => value).map((a) => ({ title: a.title, file: a.file })));
let open = $state(false);
</script>
<div>
<span class="label">Dateien zum Herunterladen</span>
<input type="hidden" {name} value={JSON.stringify(items.map((a) => ({ mediaId: a.file.id, title: a.title })))} />
{#if items.length}
<ul class="space-y-2 mb-2">
{#each items as a, i (a.file.id)}
<li class="flex items-center gap-2 rounded-xl border border-line p-2">
<FileText class="size-5 text-ink-3 shrink-0 ml-1" />
<input bind:value={items[i].title} class="field min-h-9 py-1" placeholder="Titel" aria-label="Titel der Datei" />
<span class="text-xs text-ink-3 truncate max-w-32 hidden sm:block">{a.file.name}</span>
<button type="button" class="btn btn-ghost btn-icon btn-sm" aria-label="Entfernen" onclick={() => (items = items.filter((x) => x !== a))}><X class="size-4" /></button>
</li>
{/each}
</ul>
{/if}
<button type="button" class="btn btn-soft btn-sm" onclick={() => (open = true)}><Paperclip class="size-4" />Datei anhängen</button>
<p class="hint">z. B. Speiseplan, Werkstattordnung oder Flyer als PDF.</p>
</div>
<MediaPicker
bind:open
type="any"
multiple
onselect={(sel) =>
(items = [
...items,
...sel.filter((s) => !items.some((i) => i.file.id === s.id)).map((file) => ({ file, title: file.name.replace(/\.[^.]+$/, '') }))
])}
/>

View file

@ -0,0 +1,52 @@
<script lang="ts">
import { untrack } from 'svelte';
import X from '@lucide/svelte/icons/x';
import Plus from '@lucide/svelte/icons/plus';
type Option = { id: number; name: string; role: string };
let { name, options, value = [] }: { name: string; options: Option[]; value?: number[] } = $props();
let selected = $state<number[]>(untrack(() => value));
let adding = $state('');
const byId = $derived(new Map(options.map((o) => [o.id, o])));
const available = $derived(options.filter((o) => !selected.includes(o.id)));
</script>
<div>
<span class="label">Ansprechpartner</span>
<input type="hidden" {name} value={JSON.stringify(selected)} />
{#if selected.length}
<ul class="flex flex-wrap gap-2 mb-2">
{#each selected as id (id)}
{@const c = byId.get(id)}
{#if c}
<li class="inline-flex items-center gap-2 rounded-full bg-brand-soft text-brand-ink pl-3 pr-1 py-1 text-sm font-semibold">
{c.name}
<button type="button" class="grid place-items-center size-6 rounded-full hover:bg-white/60" aria-label="{c.name} entfernen" onclick={() => (selected = selected.filter((x) => x !== id))}><X class="size-3.5" /></button>
</li>
{/if}
{/each}
</ul>
{/if}
{#if available.length}
<div class="flex gap-2">
<select bind:value={adding} class="field min-h-10 py-1.5" aria-label="Ansprechpartner hinzufügen">
<option value="">Ansprechpartner hinzufügen …</option>
{#each available as o (o.id)}<option value={String(o.id)}>{o.name}{o.role ? ` – ${o.role}` : ''}</option>{/each}
</select>
<button
type="button"
class="btn btn-soft btn-sm btn-icon shrink-0 self-center"
aria-label="Hinzufügen"
disabled={!adding}
onclick={() => {
selected = [...selected, Number(adding)];
adding = '';
}}><Plus class="size-4" /></button
>
</div>
{:else if !options.length}
<p class="hint">Lege zuerst unter „Ansprechpartner“ Personen an.</p>
{/if}
</div>

View file

@ -0,0 +1,28 @@
<script lang="ts">
import { untrack } from 'svelte';
import BookHeart from '@lucide/svelte/icons/book-heart';
import ChevronDown from '@lucide/svelte/icons/chevron-down';
import RichEditor from './RichEditor.svelte';
let { value = '' }: { value?: string } = $props();
let open = $state(untrack(() => !!value));
</script>
<section class="card overflow-hidden tone-emerald">
<button type="button" class="w-full flex items-center gap-3 p-5 text-left" onclick={() => (open = !open)} aria-expanded={open}>
<span class="grid place-items-center size-10 rounded-xl bg-tone-soft text-tone-ink"><BookHeart class="size-5" /></span>
<span class="flex-1">
<span class="block font-display text-lg font-bold">Leichte Sprache</span>
<span class="block text-sm text-ink-3">Optional: eine einfache Fassung des Textes. Wird angezeigt, wenn Leser „Leichte Sprache“ einschalten.</span>
</span>
<ChevronDown class="size-5 text-ink-3 transition-transform {open ? 'rotate-180' : ''}" />
</button>
<div class="px-5 pb-5" hidden={!open}>
<RichEditor
name="contentEasy"
{value}
label="Text in Leichter Sprache"
hint="Tipps: kurze Sätze, ein Gedanke pro Satz, bekannte Wörter, lange Wörter mit Medio·punkt trennen."
/>
</div>
</section>

View file

@ -0,0 +1,62 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import { enhance } from '$app/forms';
import Save from '@lucide/svelte/icons/save';
import Trash2 from '@lucide/svelte/icons/trash-2';
import LoaderCircle from '@lucide/svelte/icons/loader-circle';
import { toasts } from './toast.svelte';
let {
children,
aside,
canDelete = false,
deleteLabel = 'Löschen',
deleteConfirm = 'Wirklich löschen? Das kann nicht rückgängig gemacht werden.',
saveLabel = 'Speichern'
}: {
children: Snippet;
aside?: Snippet;
canDelete?: boolean;
deleteLabel?: string;
deleteConfirm?: string;
saveLabel?: string;
} = $props();
let busy = $state(false);
</script>
<form
method="POST"
action="?/save"
use:enhance={({ submitter, cancel }) => {
if (submitter?.getAttribute('formaction')?.includes('delete') && !confirm(deleteConfirm)) {
cancel();
return;
}
busy = true;
return async ({ result, update }) => {
busy = false;
if (result.type === 'failure') toasts.show(String(result.data?.error ?? 'Bitte Eingaben prüfen.'), 'error');
else if (result.type === 'error') toasts.show(result.error?.message ?? 'Fehler beim Speichern.', 'error');
else if (result.type === 'success') toasts.show('Gespeichert');
await update({ reset: false });
};
}}
>
<div class="grid xl:grid-cols-[1fr_20rem] gap-6 items-start">
<div class="space-y-6 min-w-0">{@render children()}</div>
{#if aside}<aside class="space-y-6 xl:sticky xl:top-6">{@render aside()}</aside>{/if}
</div>
<div class="sticky bottom-0 -mx-4 sm:-mx-8 mt-8 px-4 sm:px-8 py-3 bg-bg/85 backdrop-blur border-t border-line flex items-center gap-2 z-20">
<button class="btn btn-primary" disabled={busy}>
{#if busy}<LoaderCircle class="size-4 animate-spin" />{:else}<Save class="size-4" />{/if}
{saveLabel}
</button>
{#if canDelete}
<button class="btn btn-danger ml-auto" formaction="?/delete" formnovalidate disabled={busy}>
<Trash2 class="size-4" />{deleteLabel}
</button>
{/if}
</div>
</form>

View file

@ -0,0 +1,48 @@
<script lang="ts">
import { untrack } from 'svelte';
import Plus from '@lucide/svelte/icons/plus';
import X from '@lucide/svelte/icons/x';
import ChevronLeft from '@lucide/svelte/icons/chevron-left';
import ChevronRight from '@lucide/svelte/icons/chevron-right';
import MediaPicker from './MediaPicker.svelte';
import type { MediaItem } from '$lib/types';
let { name, value = [] }: { name: string; value?: MediaItem[] } = $props();
let items = $state(untrack(() => value));
let open = $state(false);
function move(i: number, d: number) {
const next = [...items];
[next[i], next[i + d]] = [next[i + d], next[i]];
items = next;
}
</script>
<div>
<span class="label">Bildergalerie</span>
<input type="hidden" {name} value={JSON.stringify(items.map((i) => i.id))} />
<div class="grid grid-cols-3 sm:grid-cols-5 gap-2">
{#each items as img, i (img.id)}
<div class="relative group aspect-square rounded-xl overflow-hidden bg-surface-2">
<img src={img.thumb} alt="" class="size-full object-cover" />
<div class="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition flex items-end justify-between p-1.5">
<span class="flex gap-1">
{#if i > 0}<button type="button" class="grid place-items-center size-7 rounded-full bg-white/90 text-ink" aria-label="Nach vorne" onclick={() => move(i, -1)}><ChevronLeft class="size-4" /></button>{/if}
{#if i < items.length - 1}<button type="button" class="grid place-items-center size-7 rounded-full bg-white/90 text-ink" aria-label="Nach hinten" onclick={() => move(i, 1)}><ChevronRight class="size-4" /></button>{/if}
</span>
<button type="button" class="grid place-items-center size-7 rounded-full bg-white/90 text-danger" aria-label="Entfernen" onclick={() => (items = items.filter((x) => x.id !== img.id))}><X class="size-4" /></button>
</div>
</div>
{/each}
<button type="button" onclick={() => (open = true)} class="aspect-square rounded-xl border-2 border-dashed border-line hover:border-brand text-ink-3 hover:text-brand-ink grid place-items-center">
<Plus class="size-7" />
</button>
</div>
</div>
<MediaPicker
bind:open
type="image"
multiple
onselect={(sel) => (items = [...items, ...sel.filter((s) => !items.some((i) => i.id === s.id))])}
/>

View file

@ -0,0 +1,57 @@
<script lang="ts">
import Icon from '$lib/components/Icon.svelte';
import { ICONS } from '$lib/icons';
import { TONES, toneNames } from '$lib/palette';
let { icon = $bindable('star'), color = $bindable('sky'), label = '' }: { icon?: string; color?: string; label?: string } = $props();
let showAll = $state(false);
</script>
<div class="space-y-4">
<input type="hidden" name="icon" value={icon} />
<input type="hidden" name="color" value={color} />
<div class="flex items-center gap-4">
<div class="tone-{color} flex items-center gap-3 rounded-2xl bg-tone-soft p-3 pr-5">
<span class="grid place-items-center size-12 rounded-2xl bg-tone text-white"><Icon name={icon} class="size-6" /></span>
<span class="font-display font-bold text-tone-ink">{label || 'Vorschau'}</span>
</div>
</div>
<fieldset>
<legend class="label">Farbe</legend>
<div class="flex flex-wrap gap-2">
{#each toneNames as t (t)}
<button
type="button"
class="tone-{t} size-9 rounded-full bg-tone ring-offset-2 ring-offset-surface transition {color === t ? 'ring-3 ring-tone' : 'hover:scale-110'}"
title={TONES[t]}
aria-label={TONES[t]}
aria-pressed={color === t}
onclick={() => (color = t)}
></button>
{/each}
</div>
</fieldset>
<fieldset>
<legend class="label">Symbol</legend>
<div class="grid grid-cols-8 sm:grid-cols-11 gap-1.5 {showAll ? '' : 'max-h-[5.8rem] overflow-hidden'}">
{#each Object.entries(ICONS) as [key, def] (key)}
<button
type="button"
class="tone-{color} grid place-items-center aspect-square rounded-xl transition {icon === key ? 'bg-tone text-white' : 'bg-surface-2 text-ink-2 hover:bg-tone-soft hover:text-tone-ink'}"
title={def.label}
aria-label={def.label}
aria-pressed={icon === key}
onclick={() => (icon = key)}
>
<Icon name={key} class="size-5" />
</button>
{/each}
</div>
<button type="button" class="text-sm font-semibold text-brand-ink mt-2" onclick={() => (showAll = !showAll)}>
{showAll ? 'Weniger anzeigen' : 'Alle Symbole anzeigen'}
</button>
</fieldset>
</div>

View file

@ -0,0 +1,37 @@
<script lang="ts">
import { untrack } from 'svelte';
import ImagePlus from '@lucide/svelte/icons/image-plus';
import X from '@lucide/svelte/icons/x';
import Replace from '@lucide/svelte/icons/replace';
import MediaPicker from './MediaPicker.svelte';
import type { MediaItem } from '$lib/types';
let { name, value = null, label = 'Bild', aspect = 'aspect-video' }: { name: string; value?: MediaItem | null; label?: string; aspect?: string } = $props();
let current = $state(untrack(() => value));
let open = $state(false);
</script>
<div>
<span class="label">{label}</span>
<input type="hidden" {name} value={current?.id ?? ''} />
{#if current}
<div class="relative group rounded-2xl overflow-hidden bg-surface-2 {aspect}">
<img src={current.thumb} alt="" class="size-full object-cover" />
<div class="absolute inset-x-0 bottom-0 p-2 flex gap-2 justify-end bg-gradient-to-t from-black/50">
<button type="button" class="btn btn-sm bg-white/90 text-ink hover:bg-white" onclick={() => (open = true)}><Replace class="size-4" />Ändern</button>
<button type="button" class="btn btn-sm btn-icon bg-white/90 text-danger hover:bg-white" aria-label="Bild entfernen" onclick={() => (current = null)}><X class="size-4" /></button>
</div>
</div>
{:else}
<button
type="button"
onclick={() => (open = true)}
class="w-full {aspect} rounded-2xl border-2 border-dashed border-line hover:border-brand hover:bg-brand-soft/50 text-ink-3 hover:text-brand-ink grid place-items-center transition"
>
<span class="flex flex-col items-center gap-1"><ImagePlus class="size-8" /><span class="text-sm font-semibold">Bild wählen</span></span>
</button>
{/if}
</div>
<MediaPicker bind:open type="image" onselect={(items) => (current = items[0] ?? current)} />

View file

@ -0,0 +1,156 @@
<script lang="ts">
import X from '@lucide/svelte/icons/x';
import Upload from '@lucide/svelte/icons/upload';
import Search from '@lucide/svelte/icons/search';
import FileText from '@lucide/svelte/icons/file-text';
import Check from '@lucide/svelte/icons/check';
import LoaderCircle from '@lucide/svelte/icons/loader-circle';
import type { MediaItem } from '$lib/types';
let {
open = $bindable(false),
type = 'any',
multiple = false,
onselect
}: {
open: boolean;
type?: 'image' | 'document' | 'any';
multiple?: boolean;
onselect: (items: MediaItem[]) => void;
} = $props();
let dialog: HTMLDialogElement;
let items = $state<MediaItem[]>([]);
let selected = $state<MediaItem[]>([]);
let q = $state('');
let loading = $state(false);
let uploading = $state(false);
let errorMsg = $state('');
const accept = $derived(type === 'image' ? 'image/*' : type === 'document' ? '.pdf,.doc,.docx,.xls,.xlsx,.mp3,.m4a,.mp4,.txt' : '');
async function load() {
loading = true;
const params = new URLSearchParams({ type, q });
const res = await fetch(`/admin/api/media?${params}`);
items = res.ok ? await res.json() : [];
loading = false;
}
$effect(() => {
if (open && !dialog.open) {
selected = [];
errorMsg = '';
dialog.showModal();
load();
}
if (!open && dialog.open) dialog.close();
});
async function upload(e: Event) {
const input = e.currentTarget as HTMLInputElement;
if (!input.files?.length) return;
uploading = true;
errorMsg = '';
const body = new FormData();
for (const f of input.files) body.append('files', f);
const res = await fetch('/admin/api/media', { method: 'POST', body });
uploading = false;
input.value = '';
if (!res.ok) {
errorMsg = (await res.json().catch(() => null))?.message ?? 'Hochladen fehlgeschlagen.';
return;
}
const added: MediaItem[] = await res.json();
items = [...added, ...items];
selected = multiple ? [...selected, ...added] : added.slice(0, 1);
}
function toggle(item: MediaItem) {
const isSel = selected.some((s) => s.id === item.id);
if (multiple) selected = isSel ? selected.filter((s) => s.id !== item.id) : [...selected, item];
else selected = isSel ? [] : [item];
}
function confirm() {
onselect(selected);
open = false;
}
let timer: ReturnType<typeof setTimeout>;
const onSearch = () => {
clearTimeout(timer);
timer = setTimeout(load, 250);
};
</script>
<dialog
bind:this={dialog}
onclose={() => (open = false)}
class="m-auto w-[min(56rem,calc(100vw-2rem))] h-[min(44rem,calc(100dvh-2rem))] rounded-3xl bg-surface text-ink p-0 shadow-float backdrop:bg-black/40 backdrop:backdrop-blur-sm"
>
<div class="flex flex-col h-full">
<header class="flex items-center gap-3 px-5 py-4 border-b border-line">
<h2 class="font-display text-xl font-bold mr-auto">
{type === 'image' ? 'Bild' : type === 'document' ? 'Datei' : 'Medium'} auswählen
</h2>
<label class="btn btn-primary btn-sm cursor-pointer">
{#if uploading}<LoaderCircle class="size-4 animate-spin" />{:else}<Upload class="size-4" />{/if}
Hochladen
<input type="file" class="sr-only" {accept} multiple onchange={upload} disabled={uploading} />
</label>
<button type="button" class="btn btn-ghost btn-icon" aria-label="Schließen" onclick={() => (open = false)}><X class="size-5" /></button>
</header>
<div class="px-5 py-3 border-b border-line">
<label class="relative block">
<Search class="size-4 text-ink-3 absolute left-3 top-1/2 -translate-y-1/2" />
<input bind:value={q} oninput={onSearch} type="search" placeholder="Suchen …" class="field pl-9 min-h-10 py-1.5" />
</label>
{#if errorMsg}<p class="text-danger text-sm mt-2 font-semibold">{errorMsg}</p>{/if}
</div>
<div class="flex-1 overflow-y-auto p-5">
{#if loading && !items.length}
<p class="text-ink-3">Lädt …</p>
{:else if !items.length}
<div class="h-full grid place-items-center text-center text-ink-3">
<p>Noch keine Dateien.<br />Lade oben rechts etwas hoch.</p>
</div>
{:else}
<div class="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-3">
{#each items as item (item.id)}
{@const isSel = selected.some((s) => s.id === item.id)}
<button
type="button"
onclick={() => toggle(item)}
ondblclick={() => {
selected = [item];
confirm();
}}
class="relative text-left rounded-2xl overflow-hidden border-2 transition {isSel ? 'border-brand ring-4 ring-brand/20' : 'border-transparent hover:border-line'}"
>
<div class="aspect-square bg-surface-2 grid place-items-center">
{#if item.isImage}
<img src={item.thumb} alt={item.alt} class="size-full object-cover" loading="lazy" />
{:else}
<FileText class="size-10 text-ink-3" />
{/if}
</div>
<p class="text-xs px-2 py-1.5 truncate">{item.name}</p>
{#if isSel}
<span class="absolute top-2 right-2 grid place-items-center size-6 rounded-full bg-brand text-white"><Check class="size-4" /></span>
{/if}
</button>
{/each}
</div>
{/if}
</div>
<footer class="flex items-center justify-end gap-2 px-5 py-4 border-t border-line">
<span class="text-sm text-ink-3 mr-auto">{selected.length ? `${selected.length} ausgewählt` : ''}</span>
<button type="button" class="btn btn-ghost" onclick={() => (open = false)}>Abbrechen</button>
<button type="button" class="btn btn-primary" disabled={!selected.length} onclick={confirm}>Übernehmen</button>
</footer>
</div>
</dialog>

View file

@ -0,0 +1,18 @@
<script lang="ts">
import { enhance } from '$app/forms';
import ChevronUp from '@lucide/svelte/icons/chevron-up';
import ChevronDown from '@lucide/svelte/icons/chevron-down';
/** Pfeile zum Umsortieren – ruft die Action ?/move mit id & Richtung auf */
let { id, first, last }: { id: number; first: boolean; last: boolean } = $props();
</script>
<form method="POST" action="?/move" use:enhance class="flex flex-col">
<input type="hidden" name="id" value={id} />
<button name="dir" value="-1" class="grid place-items-center size-7 rounded-lg text-ink-3 hover:bg-surface-2 hover:text-ink disabled:opacity-30" disabled={first} aria-label="Nach oben">
<ChevronUp class="size-4" />
</button>
<button name="dir" value="1" class="grid place-items-center size-7 rounded-lg text-ink-3 hover:bg-surface-2 hover:text-ink disabled:opacity-30" disabled={last} aria-label="Nach unten">
<ChevronDown class="size-4" />
</button>
</form>

View file

@ -0,0 +1,19 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import ArrowLeft from '@lucide/svelte/icons/arrow-left';
let { title, description = '', back = '', actions }: { title: string; description?: string; back?: string; actions?: Snippet } = $props();
</script>
<div class="mb-7">
{#if back}
<a href={back} class="inline-flex items-center gap-1.5 text-sm font-semibold text-ink-3 hover:text-ink mb-3"><ArrowLeft class="size-4" />Zurück</a>
{/if}
<div class="flex flex-wrap items-end justify-between gap-4">
<div class="min-w-0">
<h1 class="font-display text-[1.75rem] font-extrabold leading-tight">{title}</h1>
{#if description}<p class="text-ink-2 mt-1">{description}</p>{/if}
</div>
{#if actions}<div class="flex flex-wrap gap-2">{@render actions()}</div>{/if}
</div>
</div>

View file

@ -0,0 +1,14 @@
<script lang="ts">
import type { Snippet } from 'svelte';
let { title = '', description = '', children }: { title?: string; description?: string; children: Snippet } = $props();
</script>
<section class="card p-5 sm:p-6 space-y-5">
{#if title}
<header>
<h2 class="font-display text-lg font-bold">{title}</h2>
{#if description}<p class="text-sm text-ink-3 mt-0.5">{description}</p>{/if}
</header>
{/if}
{@render children()}
</section>

View file

@ -0,0 +1,148 @@
<script lang="ts">
import { onMount, onDestroy, untrack } from 'svelte';
import { Editor } from '@tiptap/core';
import StarterKit from '@tiptap/starter-kit';
import Image from '@tiptap/extension-image';
import Bold from '@lucide/svelte/icons/bold';
import Italic from '@lucide/svelte/icons/italic';
import Underline from '@lucide/svelte/icons/underline';
import Heading2 from '@lucide/svelte/icons/heading-2';
import Heading3 from '@lucide/svelte/icons/heading-3';
import List from '@lucide/svelte/icons/list';
import ListOrdered from '@lucide/svelte/icons/list-ordered';
import Quote from '@lucide/svelte/icons/quote';
import Link from '@lucide/svelte/icons/link';
import Unlink from '@lucide/svelte/icons/unlink';
import ImagePlus from '@lucide/svelte/icons/image-plus';
import Minus from '@lucide/svelte/icons/minus';
import Undo2 from '@lucide/svelte/icons/undo-2';
import Redo2 from '@lucide/svelte/icons/redo-2';
import MediaPicker from './MediaPicker.svelte';
let {
name,
value = '',
label = 'Text',
hint = '',
minHeight = '14rem'
}: { name: string; value?: string; label?: string; hint?: string; minHeight?: string } = $props();
let element: HTMLDivElement;
let editor = $state<Editor | null>(null);
let html = $state(untrack(() => value));
let tick = $state(0); // löst Neuzeichnen der Toolbar aus
let pickerOpen = $state(false);
onMount(() => {
editor = new Editor({
element,
extensions: [
StarterKit.configure({
heading: { levels: [2, 3] },
code: false,
codeBlock: false,
link: { openOnClick: false, autolink: true, defaultProtocol: 'https' }
}),
Image
],
content: value,
editorProps: {
attributes: { class: 'rich focus:outline-none px-4 py-3', style: `min-height:${minHeight}` }
},
onTransaction: () => tick++,
onUpdate: ({ editor }) => {
html = editor.isEmpty ? '' : editor.getHTML();
}
});
});
onDestroy(() => editor?.destroy());
const active = (n: string, attrs?: Record<string, unknown>) => {
void tick;
return editor?.isActive(n, attrs) ?? false;
};
function setLink() {
if (!editor) return;
const prev = editor.getAttributes('link').href ?? '';
const url = prompt('Link-Adresse (z. B. https://… oder mailto:…)', prev);
if (url === null) return;
if (url === '') editor.chain().focus().unsetLink().run();
else editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
}
type Btn = { icon: typeof Bold; label: string; run: () => void; on?: () => boolean };
const groups: Btn[][] = [
[
{ icon: Bold, label: 'Fett', run: () => editor?.chain().focus().toggleBold().run(), on: () => active('bold') },
{ icon: Italic, label: 'Kursiv', run: () => editor?.chain().focus().toggleItalic().run(), on: () => active('italic') },
{ icon: Underline, label: 'Unterstrichen', run: () => editor?.chain().focus().toggleUnderline().run(), on: () => active('underline') }
],
[
{ icon: Heading2, label: 'Überschrift', run: () => editor?.chain().focus().toggleHeading({ level: 2 }).run(), on: () => active('heading', { level: 2 }) },
{ icon: Heading3, label: 'Zwischenüberschrift', run: () => editor?.chain().focus().toggleHeading({ level: 3 }).run(), on: () => active('heading', { level: 3 }) }
],
[
{ icon: List, label: 'Aufzählung', run: () => editor?.chain().focus().toggleBulletList().run(), on: () => active('bulletList') },
{ icon: ListOrdered, label: 'Nummerierte Liste', run: () => editor?.chain().focus().toggleOrderedList().run(), on: () => active('orderedList') },
{ icon: Quote, label: 'Zitat', run: () => editor?.chain().focus().toggleBlockquote().run(), on: () => active('blockquote') },
{ icon: Minus, label: 'Trennlinie', run: () => editor?.chain().focus().setHorizontalRule().run() }
],
[
{ icon: Link, label: 'Link', run: setLink, on: () => active('link') },
{ icon: Unlink, label: 'Link entfernen', run: () => editor?.chain().focus().unsetLink().run() },
{ icon: ImagePlus, label: 'Bild einfügen', run: () => (pickerOpen = true) }
],
[
{ icon: Undo2, label: 'Rückgängig', run: () => editor?.chain().focus().undo().run() },
{ icon: Redo2, label: 'Wiederholen', run: () => editor?.chain().focus().redo().run() }
]
];
</script>
<div>
<span class="label">{label}</span>
<input type="hidden" {name} value={html} />
<div class="rounded-2xl border-[1.5px] border-line bg-surface focus-within:border-brand focus-within:ring-4 focus-within:ring-brand/15 transition">
<div class="flex flex-wrap items-center gap-1 px-2 py-1.5 border-b border-line sticky top-0 bg-surface rounded-t-2xl z-10" role="toolbar" aria-label="Textformatierung">
{#each groups as group, gi (gi)}
{#if gi > 0}<span class="w-px h-6 bg-line mx-1"></span>{/if}
{#each group as b (b.label)}
{@const on = b.on?.() ?? false}
<button
type="button"
class="grid place-items-center size-9 rounded-lg transition {on ? 'bg-brand-soft text-brand-ink' : 'text-ink-2 hover:bg-surface-2'}"
title={b.label}
aria-label={b.label}
aria-pressed={b.on ? on : undefined}
onclick={b.run}
>
<b.icon class="size-[1.1rem]" />
</button>
{/each}
{/each}
</div>
<div bind:this={element}></div>
</div>
{#if hint}<p class="hint">{hint}</p>{/if}
</div>
<MediaPicker
bind:open={pickerOpen}
type="image"
onselect={(items) => {
const img = items[0];
if (img) editor?.chain().focus().setImage({ src: img.url, alt: img.alt }).run();
}}
/>
<style>
:global(.ProseMirror p.is-editor-empty:first-child::before) {
content: attr(data-placeholder);
color: var(--ink-3);
float: left;
pointer-events: none;
height: 0;
}
</style>

View file

@ -0,0 +1,39 @@
<script lang="ts">
let { name, checked = false, label, hint = '' }: { name: string; checked?: boolean; label: string; hint?: string } = $props();
</script>
<label class="flex items-start gap-3 cursor-pointer">
<input type="checkbox" {name} {checked} class="switch mt-0.5" />
<span>
<span class="block font-semibold">{label}</span>
{#if hint}<span class="block text-sm text-ink-3">{hint}</span>{/if}
</span>
</label>
<style>
.switch {
appearance: none;
flex-shrink: 0;
width: 2.75rem;
height: 1.6rem;
border-radius: 999px;
background: var(--line);
position: relative;
cursor: pointer;
transition: background 0.2s;
}
.switch::after {
content: '';
position: absolute;
top: 0.2rem;
left: 0.2rem;
width: 1.2rem;
height: 1.2rem;
border-radius: 999px;
background: white;
box-shadow: 0 1px 3px rgb(0 0 0 / 0.3);
transition: transform 0.2s;
}
.switch:checked { background: var(--brand); }
.switch:checked::after { transform: translateX(1.15rem); }
</style>

View file

@ -0,0 +1,18 @@
<script lang="ts">
import CircleCheck from '@lucide/svelte/icons/circle-check';
import CircleAlert from '@lucide/svelte/icons/circle-alert';
import { toasts } from './toast.svelte';
import { fly } from 'svelte/transition';
</script>
<div class="fixed bottom-4 right-4 z-[100] flex flex-col gap-2 items-end" aria-live="polite">
{#each toasts.items as t (t.id)}
<div
transition:fly={{ y: 20, duration: 200 }}
class="flex items-center gap-2 rounded-2xl px-4 py-3 shadow-float font-semibold {t.kind === 'ok' ? 'bg-ink text-bg' : 'bg-danger text-white'}"
>
{#if t.kind === 'ok'}<CircleCheck class="size-5" />{:else}<CircleAlert class="size-5" />{/if}
{t.text}
</div>
{/each}
</div>

View file

@ -0,0 +1,13 @@
/** Kleine Erfolgs-/Fehlermeldungen unten rechts im Admin. */
class Toasts {
items = $state<{ id: number; text: string; kind: 'ok' | 'error' }[]>([]);
#id = 0;
show(text: string, kind: 'ok' | 'error' = 'ok') {
const id = ++this.#id;
this.items = [...this.items, { id, text, kind }];
setTimeout(() => (this.items = this.items.filter((t) => t.id !== id)), 3500);
}
}
export const toasts = new Toasts();

View file

@ -0,0 +1,76 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import Volume2 from '@lucide/svelte/icons/volume-2';
import Square from '@lucide/svelte/icons/square';
import Bookmark from '@lucide/svelte/icons/bookmark';
import BookmarkCheck from '@lucide/svelte/icons/bookmark-check';
import Share2 from '@lucide/svelte/icons/share-2';
import { favorites } from '$lib/favorites.svelte';
import type { Favorite } from '$lib/types';
let { target, favorite }: { target: string; favorite?: Favorite } = $props();
let canSpeak = $state(false);
let speaking = $state(false);
let shared = $state(false);
onMount(() => (canSpeak = 'speechSynthesis' in window));
onDestroy(() => speaking && speechSynthesis.cancel());
/** Liest den Inhalt des Elements #target vor – satzweise, damit lange Texte nicht abbrechen. */
function toggleSpeak() {
if (speaking) {
speechSynthesis.cancel();
speaking = false;
return;
}
const el = document.getElementById(target);
if (!el) return;
const sentences = (el.innerText.match(/[^.!?\n]+[.!?]*/g) ?? []).map((s) => s.trim()).filter(Boolean);
const voice = speechSynthesis.getVoices().find((v) => v.lang.startsWith('de'));
speechSynthesis.cancel();
sentences.forEach((s, i) => {
const u = new SpeechSynthesisUtterance(s);
u.lang = 'de-DE';
u.rate = 0.95;
if (voice) u.voice = voice;
if (i === sentences.length - 1) u.onend = () => (speaking = false);
speechSynthesis.speak(u);
});
speaking = sentences.length > 0;
}
async function share() {
const data = { title: document.title, url: location.href };
if (navigator.share) {
try {
await navigator.share(data);
} catch {
/* abgebrochen */
}
} else {
await navigator.clipboard.writeText(location.href);
shared = true;
setTimeout(() => (shared = false), 2000);
}
}
const saved = $derived(favorite ? favorites.has(favorite.href) : false);
</script>
<div class="flex flex-wrap gap-2">
{#if canSpeak}
<button type="button" class="btn btn-sm {speaking ? 'btn-primary' : 'btn-soft'}" onclick={toggleSpeak} aria-pressed={speaking}>
{#if speaking}<Square class="size-4" /> Stopp{:else}<Volume2 class="size-4" /> Vorlesen{/if}
</button>
{/if}
{#if favorite}
<button type="button" class="btn btn-sm btn-soft" onclick={() => favorites.toggle(favorite)} aria-pressed={saved}>
{#if saved}<BookmarkCheck class="size-4" /> Gemerkt{:else}<Bookmark class="size-4" /> Merken{/if}
</button>
{/if}
<button type="button" class="btn btn-sm btn-soft" onclick={share}>
<Share2 class="size-4" />
{shared ? 'Link kopiert' : 'Teilen'}
</button>
</div>

View file

@ -0,0 +1,36 @@
<script lang="ts">
import FileText from '@lucide/svelte/icons/file-text';
import FileImage from '@lucide/svelte/icons/file-image';
import FileAudio from '@lucide/svelte/icons/file-audio';
import FileVideo from '@lucide/svelte/icons/file-video';
import Download from '@lucide/svelte/icons/download';
import type { AttachmentItem } from '$lib/types';
let { items }: { items: AttachmentItem[] } = $props();
const iconFor = (mime: string) =>
mime.startsWith('image/') ? FileImage : mime.startsWith('audio/') ? FileAudio : mime.startsWith('video/') ? FileVideo : FileText;
const size = (b: number) => (b > 1e6 ? `${(b / 1e6).toFixed(1).replace('.', ',')} MB` : `${Math.max(1, Math.round(b / 1e3))} KB`);
const kind = (mime: string, name: string) => (mime === 'application/pdf' ? 'PDF' : (name.split('.').pop() ?? '').toUpperCase());
</script>
{#if items.length}
<section class="space-y-2">
<h2 class="eyebrow">Dokumente</h2>
<ul class="card divide-y divide-line/70 overflow-hidden">
{#each items as a (a.file.id)}
{@const Ico = iconFor(a.file.mimeType)}
<li>
<a href={a.file.url} target="_blank" rel="noopener" class="flex items-center gap-3 px-4 py-3 hover:bg-surface-2">
<span class="grid place-items-center size-10 rounded-xl bg-brand-soft text-brand-ink shrink-0"><Ico class="size-5" /></span>
<span class="flex-1 min-w-0">
<span class="block font-semibold truncate">{a.title}</span>
<span class="block text-xs text-ink-3">{kind(a.file.mimeType, a.file.name)} · {size(a.file.size)}</span>
</span>
<Download class="size-5 text-ink-3" />
</a>
</li>
{/each}
</ul>
</section>
{/if}

View file

@ -0,0 +1,9 @@
<script lang="ts">
import ArrowLeft from '@lucide/svelte/icons/arrow-left';
let { href, label }: { href: string; label: string } = $props();
</script>
<a {href} class="inline-flex items-center gap-1.5 text-sm font-semibold text-ink-2 hover:text-ink mb-4 -ml-1 px-1 py-1 rounded-lg">
<ArrowLeft class="size-4" />
{label}
</a>

View file

@ -0,0 +1,43 @@
<script lang="ts">
import Mail from '@lucide/svelte/icons/mail';
import Phone from '@lucide/svelte/icons/phone';
import MapPin from '@lucide/svelte/icons/map-pin';
import type { ContactCard } from '$lib/types';
let { contact }: { contact: ContactCard } = $props();
const initials = $derived(
contact.name
.split(/\s+/)
.map((w) => w[0])
.slice(0, 2)
.join('')
);
const tel = $derived(contact.phone.replace(/[^\d+]/g, ''));
</script>
<div class="card p-4 flex gap-4">
{#if contact.photo}
<img src={contact.photo.thumb} alt="" class="size-16 rounded-2xl object-cover shrink-0" loading="lazy" />
{:else}
<div class="size-16 rounded-2xl bg-brand-soft text-brand-ink grid place-items-center font-display font-bold text-xl shrink-0" aria-hidden="true">
{initials}
</div>
{/if}
<div class="min-w-0 flex-1">
<p class="font-display font-bold text-lg leading-tight">{contact.name}</p>
{#if contact.role}<p class="text-sm text-ink-2">{contact.role}</p>{/if}
{#if contact.location}
<p class="text-sm text-ink-3 flex items-center gap-1 mt-0.5"><MapPin class="size-3.5" />{contact.location}</p>
{/if}
{#if contact.phone || contact.email}
<div class="flex flex-wrap gap-2 mt-3">
{#if contact.phone}
<a href="tel:{tel}" class="btn btn-soft btn-sm"><Phone class="size-4" />Anrufen</a>
{/if}
{#if contact.email}
<a href="mailto:{contact.email}" class="btn btn-soft btn-sm"><Mail class="size-4" />E-Mail</a>
{/if}
</div>
{/if}
</div>
</div>

View file

@ -0,0 +1,10 @@
<script lang="ts">
import type { Snippet } from 'svelte';
let { title, children, icon }: { title: string; children?: Snippet; icon?: Snippet } = $props();
</script>
<div class="card p-8 text-center flex flex-col items-center gap-3">
{#if icon}<div class="grid place-items-center size-14 rounded-2xl bg-brand-soft text-brand">{@render icon()}</div>{/if}
<p class="font-display font-bold text-lg">{title}</p>
{#if children}<div class="text-ink-2 max-w-sm">{@render children()}</div>{/if}
</div>

View file

@ -0,0 +1,38 @@
<script lang="ts">
import MapPin from '@lucide/svelte/icons/map-pin';
import Clock from '@lucide/svelte/icons/clock';
import DoorClosed from '@lucide/svelte/icons/door-closed';
import { dayOfMonth, eventWhen, monthAbbr, weekday } from '$lib/dates';
import type { EventItem } from '$lib/types';
let { event, expanded = false }: { event: EventItem; expanded?: boolean } = $props();
const closure = $derived(event.kind === 'closure');
</script>
<article class="flex gap-4 p-3 rounded-2xl {closure ? 'tone-amber bg-tone-soft' : 'card'}">
<div
class="shrink-0 w-16 rounded-xl text-center py-2 {closure ? 'bg-tone text-white' : 'bg-brand-soft text-brand-ink'}"
aria-hidden="true"
>
<div class="text-xs font-bold uppercase tracking-wide">{weekday(event.startDate)}</div>
<div class="font-display text-2xl font-extrabold leading-none my-0.5">{dayOfMonth(event.startDate)}</div>
<div class="text-xs font-semibold">{monthAbbr(event.startDate)}</div>
</div>
<div class="min-w-0 py-0.5">
{#if closure}
<p class="text-xs font-bold uppercase tracking-wide text-tone-ink flex items-center gap-1">
<DoorClosed class="size-3.5" /> Geschlossen
</p>
{/if}
<h3 class="font-display font-bold text-[1.05rem] leading-snug">{event.title}</h3>
<p class="text-sm text-ink-2 mt-1 flex flex-wrap gap-x-4 gap-y-1">
<span class="inline-flex items-center gap-1.5"><Clock class="size-4 text-ink-3" />{eventWhen(event)}</span>
{#if event.location}
<span class="inline-flex items-center gap-1.5"><MapPin class="size-4 text-ink-3" />{event.location}</span>
{/if}
</p>
{#if expanded && event.description}
<p class="text-sm text-ink-2 mt-2 whitespace-pre-line">{event.description}</p>
{/if}
</div>
</article>

View file

@ -0,0 +1,72 @@
<script lang="ts">
import X from '@lucide/svelte/icons/x';
import ChevronLeft from '@lucide/svelte/icons/chevron-left';
import ChevronRight from '@lucide/svelte/icons/chevron-right';
import type { MediaItem } from '$lib/types';
let { images }: { images: MediaItem[] } = $props();
let dialog = $state<HTMLDialogElement>();
let index = $state(0);
function openAt(i: number) {
index = i;
dialog?.showModal();
}
const step = (d: number) => (index = (index + d + images.length) % images.length);
function onKey(e: KeyboardEvent) {
if (e.key === 'ArrowRight') step(1);
if (e.key === 'ArrowLeft') step(-1);
}
let touchX = 0;
</script>
{#if images.length}
<section class="space-y-2">
<h2 class="eyebrow">Bilder</h2>
<div class="grid grid-cols-3 gap-2">
{#each images as img, i (img.id)}
<button
type="button"
class="aspect-square rounded-xl overflow-hidden bg-surface-2 pressable"
onclick={() => openAt(i)}
aria-label="Bild {i + 1} von {images.length} vergrößern"
>
<img src={img.thumb} alt={img.alt} class="size-full object-cover" loading="lazy" />
</button>
{/each}
</div>
</section>
<dialog
bind:this={dialog}
onkeydown={onKey}
class="m-0 size-full max-w-none max-h-none bg-black/95 text-white p-0"
aria-label="Bildergalerie"
>
<div
class="relative size-full grid place-items-center"
role="presentation"
ontouchstart={(e) => (touchX = e.touches[0].clientX)}
ontouchend={(e) => {
const dx = e.changedTouches[0].clientX - touchX;
if (Math.abs(dx) > 50) step(dx < 0 ? 1 : -1);
}}
>
<img src={images[index].url} alt={images[index].alt} class="max-h-[88dvh] max-w-[96vw] object-contain rounded-lg" />
<p class="absolute bottom-6 inset-x-0 text-center text-sm text-white/70">{index + 1} / {images.length}</p>
<button class="absolute top-4 right-4 btn btn-icon bg-white/10 hover:bg-white/20" aria-label="Schließen" onclick={() => dialog?.close()}>
<X class="size-6" />
</button>
{#if images.length > 1}
<button class="absolute left-3 top-1/2 -translate-y-1/2 btn btn-icon bg-white/10 hover:bg-white/20" aria-label="Vorheriges Bild" onclick={() => step(-1)}>
<ChevronLeft class="size-7" />
</button>
<button class="absolute right-3 top-1/2 -translate-y-1/2 btn btn-icon bg-white/10 hover:bg-white/20" aria-label="Nächstes Bild" onclick={() => step(1)}>
<ChevronRight class="size-7" />
</button>
{/if}
</div>
</dialog>
{/if}

View file

@ -0,0 +1,8 @@
<script lang="ts">
import { iconFor } from '$lib/icons';
let { name, class: cls = 'size-6', strokeWidth = 2 }: { name: string; class?: string; strokeWidth?: number } = $props();
const Cmp = $derived(iconFor(name));
</script>
<Cmp class={cls} {strokeWidth} aria-hidden="true" />

View file

@ -0,0 +1,111 @@
<script lang="ts">
import X from '@lucide/svelte/icons/x';
import Users from '@lucide/svelte/icons/users';
import Mail from '@lucide/svelte/icons/mail';
import SlidersHorizontal from '@lucide/svelte/icons/sliders-horizontal';
import ExternalLink from '@lucide/svelte/icons/external-link';
import Scale from '@lucide/svelte/icons/scale';
import ShieldCheck from '@lucide/svelte/icons/shield-check';
import ChevronRight from '@lucide/svelte/icons/chevron-right';
import Icon from './Icon.svelte';
import PrefsControls from './PrefsControls.svelte';
import type { PageCard } from '$lib/types';
let { open = $bindable(false), pages, website }: { open: boolean; pages: PageCard[]; website: string } = $props();
let dialog: HTMLDialogElement;
$effect(() => {
if (open && !dialog.open) dialog.showModal();
if (!open && dialog.open) dialog.close();
});
</script>
<dialog
bind:this={dialog}
onclose={() => (open = false)}
onclick={(e) => e.target === dialog && (open = false)}
class="sheet m-0 ml-auto h-dvh max-h-dvh w-full max-w-md bg-bg text-ink p-0 backdrop:bg-black/40 backdrop:backdrop-blur-sm"
aria-label="Menü"
>
<div class="flex flex-col h-full">
<div class="flex items-center justify-between px-5 h-16 safe-top border-b border-line/60">
<h2 class="font-display text-xl font-bold">Menü</h2>
<button class="btn btn-ghost btn-icon" aria-label="Menü schließen" onclick={() => (open = false)}>
<X class="size-6" />
</button>
</div>
<div class="flex-1 overflow-y-auto px-5 py-5 space-y-7 safe-bottom">
{#if pages.length}
<section>
<h3 class="eyebrow mb-3">Bereiche</h3>
<ul class="card divide-y divide-line/70 overflow-hidden">
{#each pages as p (p.id)}
<li>
<a href="/s/{p.slug}" class="tone-{p.color} flex items-center gap-3 px-4 py-3 hover:bg-surface-2">
<span class="grid place-items-center size-9 rounded-xl bg-tone-soft text-tone-ink">
<Icon name={p.icon} class="size-5" />
</span>
<span class="flex-1 font-semibold">{p.title}</span>
<ChevronRight class="size-5 text-ink-3" />
</a>
</li>
{/each}
</ul>
</section>
{/if}
<section>
<h3 class="eyebrow mb-3">Anzeige</h3>
<div class="card p-4">
<PrefsControls compact />
</div>
</section>
<section>
<h3 class="eyebrow mb-3">Service</h3>
<ul class="card divide-y divide-line/70 overflow-hidden">
{#each [
{ href: '/kontakte', label: 'Ansprechpartner', icon: Users },
{ href: '/kontakt', label: 'Nachricht schreiben', icon: Mail },
{ href: '/einstellungen', label: 'Einstellungen', icon: SlidersHorizontal },
{ href: '/impressum', label: 'Impressum', icon: Scale },
{ href: '/datenschutz', label: 'Datenschutz', icon: ShieldCheck }
] as l (l.href)}
<li>
<a href={l.href} class="flex items-center gap-3 px-4 py-3 hover:bg-surface-2">
<l.icon class="size-5 text-ink-2" />
<span class="flex-1 font-medium">{l.label}</span>
<ChevronRight class="size-5 text-ink-3" />
</a>
</li>
{/each}
{#if website}
<li>
<a href={website} target="_blank" rel="noopener" class="flex items-center gap-3 px-4 py-3 hover:bg-surface-2">
<ExternalLink class="size-5 text-ink-2" />
<span class="flex-1 font-medium">Unsere Website</span>
</a>
</li>
{/if}
</ul>
</section>
</div>
</div>
</dialog>
<style>
.sheet[open] {
animation: slide-in 0.28s cubic-bezier(0.2, 0.8, 0.2, 1);
}
.sheet[open]::backdrop {
animation: fade-in 0.28s ease;
}
@keyframes slide-in {
from { transform: translateX(100%); }
}
@keyframes fade-in {
from { opacity: 0; }
}
</style>

View file

@ -0,0 +1,50 @@
<script lang="ts">
import Pin from '@lucide/svelte/icons/pin';
import Newspaper from '@lucide/svelte/icons/newspaper';
import { relative } from '$lib/dates';
import type { PostCard } from '$lib/types';
let { post, variant = 'row' }: { post: PostCard; variant?: 'row' | 'hero' } = $props();
</script>
{#if variant === 'hero'}
<a href="/meldungen/{post.slug}" class="card pressable group block overflow-hidden">
<div class="aspect-[16/9] bg-brand-soft overflow-hidden">
{#if post.cover}
<img
src={post.cover.url}
alt={post.cover.alt}
class="size-full object-cover transition-transform duration-500 group-hover:scale-[1.03]"
/>
{:else}
<div class="size-full grid place-items-center text-brand"><Newspaper class="size-14 opacity-50" /></div>
{/if}
</div>
<div class="p-5">
<p class="text-sm text-ink-3 flex items-center gap-2">
{#if post.pinned}<Pin class="size-4 text-brand" aria-label="Angeheftet" />{/if}
{relative(post.publishedAt)}
</p>
<h3 class="font-display text-xl font-bold mt-1">{post.title}</h3>
{#if post.teaser}<p class="text-ink-2 mt-2 line-clamp-2">{post.teaser}</p>{/if}
</div>
</a>
{:else}
<a href="/meldungen/{post.slug}" class="card pressable flex gap-4 p-3 items-center">
<div class="size-24 sm:size-28 shrink-0 rounded-2xl overflow-hidden bg-brand-soft">
{#if post.cover}
<img src={post.cover.thumb} alt={post.cover.alt} class="size-full object-cover" loading="lazy" />
{:else}
<div class="size-full grid place-items-center text-brand"><Newspaper class="size-9 opacity-50" /></div>
{/if}
</div>
<div class="min-w-0 py-1 pr-1">
<p class="text-sm text-ink-3 flex items-center gap-1.5">
{#if post.pinned}<Pin class="size-3.5 text-brand" aria-label="Angeheftet" />{/if}
{relative(post.publishedAt)}
</p>
<h3 class="font-display font-bold text-[1.08rem] leading-snug mt-0.5 line-clamp-2">{post.title}</h3>
{#if post.teaser}<p class="text-sm text-ink-2 mt-1 line-clamp-2">{post.teaser}</p>{/if}
</div>
</a>
{/if}

View file

@ -0,0 +1,113 @@
<script lang="ts">
import Sun from '@lucide/svelte/icons/sun';
import Moon from '@lucide/svelte/icons/moon';
import Monitor from '@lucide/svelte/icons/monitor';
import BookHeart from '@lucide/svelte/icons/book-heart';
import { prefs } from '$lib/prefs.svelte';
let { compact = false }: { compact?: boolean } = $props();
const themes = [
{ value: 'light', label: 'Hell', icon: Sun },
{ value: 'dark', label: 'Dunkel', icon: Moon },
{ value: 'system', label: 'Automatisch', icon: Monitor }
] as const;
const sizes = [
{ value: 'm', label: 'Normal', scale: 'text-base' },
{ value: 'l', label: 'Groß', scale: 'text-xl' },
{ value: 'xl', label: 'Sehr groß', scale: 'text-2xl' }
] as const;
</script>
<div class="space-y-5">
<!-- Leichte Sprache -->
<label class="flex items-center gap-3 cursor-pointer">
<span class="grid place-items-center size-10 rounded-xl bg-brand-soft text-brand-ink shrink-0">
<BookHeart class="size-5" />
</span>
<span class="flex-1">
<span class="block font-semibold">Leichte Sprache</span>
{#if !compact}
<span class="block text-sm text-ink-3">Texte werden einfacher angezeigt, wenn es sie gibt.</span>
{/if}
</span>
<input
type="checkbox"
role="switch"
class="switch"
checked={prefs.current.easy}
onchange={(e) => prefs.set({ easy: e.currentTarget.checked })}
/>
</label>
<fieldset>
<legend class="font-semibold mb-2">Schriftgröße</legend>
<div class="grid grid-cols-3 gap-2">
{#each sizes as s (s.value)}
<button
type="button"
class="rounded-xl border-2 py-2 flex flex-col items-center transition-colors {prefs.current.size === s.value
? 'border-brand bg-brand-soft text-brand-ink'
: 'border-line hover:border-ink-3'}"
aria-pressed={prefs.current.size === s.value}
onclick={() => prefs.set({ size: s.value })}
>
<span class="font-display font-bold leading-none {s.scale}">A</span>
<span class="text-xs mt-1">{s.label}</span>
</button>
{/each}
</div>
</fieldset>
<fieldset>
<legend class="font-semibold mb-2">Farbschema</legend>
<div class="grid grid-cols-3 gap-2">
{#each themes as t (t.value)}
<button
type="button"
class="rounded-xl border-2 py-2 flex flex-col items-center gap-1 transition-colors {prefs.current.theme === t.value
? 'border-brand bg-brand-soft text-brand-ink'
: 'border-line hover:border-ink-3'}"
aria-pressed={prefs.current.theme === t.value}
onclick={() => prefs.set({ theme: t.value })}
>
<t.icon class="size-5" />
<span class="text-xs">{t.label}</span>
</button>
{/each}
</div>
</fieldset>
</div>
<style>
.switch {
appearance: none;
flex-shrink: 0;
width: 3.2rem;
height: 1.9rem;
border-radius: 999px;
background: var(--line);
position: relative;
cursor: pointer;
transition: background 0.2s;
}
.switch::after {
content: '';
position: absolute;
top: 0.2rem;
left: 0.2rem;
width: 1.5rem;
height: 1.5rem;
border-radius: 999px;
background: white;
box-shadow: 0 1px 3px rgb(0 0 0 / 0.3);
transition: transform 0.2s;
}
.switch:checked {
background: var(--brand);
}
.switch:checked::after {
transform: translateX(1.3rem);
}
</style>

View file

@ -0,0 +1,34 @@
<script lang="ts">
import BookHeart from '@lucide/svelte/icons/book-heart';
import { prefs } from '$lib/prefs.svelte';
/** Zeigt den Text – bei aktivierter „Leichter Sprache“ die einfache Fassung, falls vorhanden. */
let { content, contentEasy, id = 'vorlesen' }: { content: string; contentEasy: string; id?: string } = $props();
const useEasy = $derived(prefs.current.easy && !!contentEasy);
</script>
{#if contentEasy}
<div class="tone-emerald bg-tone-soft text-tone-ink rounded-2xl px-4 py-3 flex items-center gap-3 text-sm">
<BookHeart class="size-5 shrink-0" />
<span class="flex-1">
{useEasy ? 'Du liest diesen Text in Leichter Sprache.' : 'Diesen Text gibt es auch in Leichter Sprache.'}
</span>
<button class="font-bold underline underline-offset-2" onclick={() => prefs.set({ easy: !prefs.current.easy })}>
{useEasy ? 'Normale Sprache' : 'Leichte Sprache'}
</button>
</div>
{/if}
{#if useEasy || content}
<div {id} class="rich {useEasy ? 'easy' : ''}">
{@html useEasy ? contentEasy : content}
</div>
{/if}
<style>
.easy {
font-size: 1.2rem;
line-height: 1.8;
}
</style>

View file

@ -0,0 +1,24 @@
<script lang="ts">
import Icon from './Icon.svelte';
let { href, label, icon, color, sub = '' }: { href: string; label: string; icon: string; color: string; sub?: string } = $props();
const external = $derived(/^https?:\/\//.test(href));
</script>
<a
{href}
target={external ? '_blank' : undefined}
rel={external ? 'noopener' : undefined}
class="tone-{color} pressable group relative flex flex-col justify-between gap-4 rounded-[1.4rem] bg-tone-soft p-4 min-h-32 overflow-hidden"
>
<span
class="grid place-items-center size-12 rounded-2xl bg-tone text-white shadow-[0_8px_18px_-8px_var(--tone)] transition-transform group-hover:-rotate-6 group-hover:scale-105"
>
<Icon name={icon} class="size-6" />
</span>
<span class="font-display font-bold text-[1.02rem] leading-tight text-tone-ink hyphens-auto" lang="de">
{label}
{#if sub}<span class="block mt-1 font-sans font-normal text-sm text-ink-2">{sub}</span>{/if}
</span>
<span aria-hidden="true" class="absolute -right-6 -top-6 size-24 rounded-full bg-tone opacity-[0.07]"></span>
</a>

View file

@ -0,0 +1,33 @@
<script lang="ts">
import Play from '@lucide/svelte/icons/play';
let { url }: { url: string } = $props();
/** Wandelt YouTube-/Vimeo-Links in datensparsame Einbettungen um. */
const embed = $derived.by(() => {
const yt = url.match(/(?:youtube\.com\/(?:watch\?v=|shorts\/|embed\/)|youtu\.be\/)([\w-]{11})/);
if (yt) return `https://www.youtube-nocookie.com/embed/${yt[1]}?autoplay=1&rel=0`;
const vimeo = url.match(/vimeo\.com\/(\d+)/);
if (vimeo) return `https://player.vimeo.com/video/${vimeo[1]}?autoplay=1&dnt=1`;
return null;
});
// Erst nach Klick laden (Datenschutz: keine Verbindung zu Drittanbietern ohne Zustimmung)
let consent = $state(false);
</script>
{#if embed}
<div class="aspect-video rounded-2xl overflow-hidden bg-black/90 text-white">
{#if consent}
<iframe src={embed} title="Video" class="size-full" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>
{:else}
<button type="button" class="size-full flex flex-col items-center justify-center gap-3 p-6 text-center" onclick={() => (consent = true)}>
<span class="grid place-items-center size-16 rounded-full bg-white text-black"><Play class="size-7 ml-1" /></span>
<span class="font-semibold">Video abspielen</span>
<span class="text-xs text-white/60 max-w-sm">Beim Abspielen werden Daten an den Video-Anbieter übertragen.</span>
</button>
{/if}
</div>
{:else if url}
<a href={url} target="_blank" rel="noopener" class="btn btn-soft"><Play class="size-4" /> Video ansehen</a>
{/if}

71
src/lib/dates.ts Normal file
View file

@ -0,0 +1,71 @@
export const TZ = 'Europe/Berlin';
/** Heutiges Datum in deutscher Zeit als YYYY-MM-DD */
export function today(): string {
return new Intl.DateTimeFormat('sv-SE', { timeZone: TZ }).format(new Date());
}
export function addDays(iso: string, days: number): string {
const d = new Date(`${iso}T12:00:00Z`);
d.setUTCDate(d.getUTCDate() + days);
return d.toISOString().slice(0, 10);
}
const asDate = (iso: string) => new Date(iso.length === 10 ? `${iso}T12:00:00Z` : iso);
const fmt = (opts: Intl.DateTimeFormatOptions) => new Intl.DateTimeFormat('de-DE', { timeZone: TZ, ...opts });
const long = fmt({ weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
const medium = fmt({ day: 'numeric', month: 'long', year: 'numeric' });
const short = fmt({ day: '2-digit', month: '2-digit', year: 'numeric' });
const weekdayShort = fmt({ weekday: 'short' });
const monthShort = fmt({ month: 'short' });
const monthYear = fmt({ month: 'long', year: 'numeric' });
export const formatLong = (iso: string) => long.format(asDate(iso));
export const formatDate = (iso: string) => medium.format(asDate(iso));
export const formatShort = (iso: string) => short.format(asDate(iso));
export const formatMonthYear = (iso: string) => monthYear.format(asDate(iso));
export const weekday = (iso: string) => weekdayShort.format(asDate(iso)).replace('.', '');
export const monthAbbr = (iso: string) => monthShort.format(asDate(iso)).replace('.', '');
export const dayOfMonth = (iso: string) => String(asDate(iso).getUTCDate());
/** „vor 3 Tagen“, „heute“ … für Meldungen */
export function relative(iso: string): string {
const then = new Intl.DateTimeFormat('sv-SE', { timeZone: TZ }).format(new Date(iso));
const diff = Math.round((asDate(today()).getTime() - asDate(then).getTime()) / 864e5);
if (diff <= 0) return 'Heute';
if (diff === 1) return 'Gestern';
if (diff < 7) return `vor ${diff} Tagen`;
return formatDate(iso);
}
export function eventWhen(e: { startDate: string; endDate: string; startTime: string; endTime: string }): string {
const multiDay = e.endDate && e.endDate !== e.startDate;
if (multiDay) return `${formatShort(e.startDate)} – ${formatShort(e.endDate)}`;
if (e.startTime) return e.endTime ? `${e.startTime} – ${e.endTime} Uhr` : `ab ${e.startTime} Uhr`;
return 'ganztägig';
}
/** Date → „YYYY-MM-DDTHH:mm“ in deutscher Zeit (für <input type="datetime-local">) */
export function toLocalInput(date: Date): string {
const p = Object.fromEntries(
new Intl.DateTimeFormat('en-CA', {
timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23'
})
.formatToParts(date)
.map((x) => [x.type, x.value])
);
return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}`;
}
/** „YYYY-MM-DDTHH:mm“ (deutsche Zeit) → Date */
export function fromLocalInput(value: string): Date | null {
const m = value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);
if (!m) return null;
const guess = Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5]);
// Versatz der deutschen Zeit zu UTC an diesem Zeitpunkt bestimmen
const asLocal = toLocalInput(new Date(guess));
const back = Date.UTC(+asLocal.slice(0, 4), +asLocal.slice(5, 7) - 1, +asLocal.slice(8, 10), +asLocal.slice(11, 13), +asLocal.slice(14, 16));
return new Date(guess - (back - guess));
}

View file

@ -0,0 +1,34 @@
import type { Favorite } from './types';
const KEY = 'wa_favorites';
/** Merkliste – bleibt nur auf diesem Gerät gespeichert. */
class Favorites {
items = $state<Favorite[]>([]);
#loaded = false;
load() {
if (this.#loaded || typeof localStorage === 'undefined') return;
this.#loaded = true;
try {
this.items = JSON.parse(localStorage.getItem(KEY) ?? '[]');
} catch {
this.items = [];
}
}
has(href: string) {
return this.items.some((f) => f.href === href);
}
toggle(fav: Favorite) {
this.items = this.has(fav.href) ? this.items.filter((f) => f.href !== fav.href) : [fav, ...this.items];
try {
localStorage.setItem(KEY, JSON.stringify(this.items));
} catch {
/* privater Modus o. Ä. */
}
}
}
export const favorites = new Favorites();

96
src/lib/icons.ts Normal file
View file

@ -0,0 +1,96 @@
import Accessibility from '@lucide/svelte/icons/accessibility';
import Apple from '@lucide/svelte/icons/apple';
import Bell from '@lucide/svelte/icons/bell';
import Bike from '@lucide/svelte/icons/bike';
import BookOpen from '@lucide/svelte/icons/book-open';
import Briefcase from '@lucide/svelte/icons/briefcase';
import Building2 from '@lucide/svelte/icons/building-2';
import CalendarDays from '@lucide/svelte/icons/calendar-days';
import Camera from '@lucide/svelte/icons/camera';
import Car from '@lucide/svelte/icons/car';
import Clock from '@lucide/svelte/icons/clock';
import Coffee from '@lucide/svelte/icons/coffee';
import FileText from '@lucide/svelte/icons/file-text';
import GraduationCap from '@lucide/svelte/icons/graduation-cap';
import Hammer from '@lucide/svelte/icons/hammer';
import HandHeart from '@lucide/svelte/icons/hand-heart';
import Handshake from '@lucide/svelte/icons/handshake';
import Heart from '@lucide/svelte/icons/heart';
import House from '@lucide/svelte/icons/house';
import Info from '@lucide/svelte/icons/info';
import Leaf from '@lucide/svelte/icons/leaf';
import Lightbulb from '@lucide/svelte/icons/lightbulb';
import Mail from '@lucide/svelte/icons/mail';
import MapPin from '@lucide/svelte/icons/map-pin';
import Megaphone from '@lucide/svelte/icons/megaphone';
import MessageCircle from '@lucide/svelte/icons/message-circle';
import Music from '@lucide/svelte/icons/music';
import Newspaper from '@lucide/svelte/icons/newspaper';
import Palette from '@lucide/svelte/icons/palette';
import Phone from '@lucide/svelte/icons/phone';
import Puzzle from '@lucide/svelte/icons/puzzle';
import Scale from '@lucide/svelte/icons/scale';
import ShieldCheck from '@lucide/svelte/icons/shield-check';
import ShoppingBag from '@lucide/svelte/icons/shopping-bag';
import Smile from '@lucide/svelte/icons/smile';
import Sparkles from '@lucide/svelte/icons/sparkles';
import Star from '@lucide/svelte/icons/star';
import Store from '@lucide/svelte/icons/store';
import TreePine from '@lucide/svelte/icons/tree-pine';
import Truck from '@lucide/svelte/icons/truck';
import Users from '@lucide/svelte/icons/users';
import Utensils from '@lucide/svelte/icons/utensils';
import Wrench from '@lucide/svelte/icons/wrench';
import type { Component } from 'svelte';
/**
* Icons, die Redakteure für Kacheln und Seiten auswählen können.
* Neues Icon? Einfach aus https://lucide.dev importieren und hier eintragen.
*/
export const ICONS: Record<string, { label: string; component: Component<any> }> = {
house: { label: 'Haus', component: House },
newspaper: { label: 'Zeitung', component: Newspaper },
megaphone: { label: 'Megafon', component: Megaphone },
'calendar-days': { label: 'Kalender', component: CalendarDays },
clock: { label: 'Uhr', component: Clock },
bell: { label: 'Glocke', component: Bell },
'building-2': { label: 'Gebäude', component: Building2 },
store: { label: 'Laden', component: Store },
'shopping-bag': { label: 'Einkauf', component: ShoppingBag },
users: { label: 'Gruppe', component: Users },
handshake: { label: 'Handschlag', component: Handshake },
'hand-heart': { label: 'Hilfe', component: HandHeart },
heart: { label: 'Herz', component: Heart },
smile: { label: 'Lächeln', component: Smile },
accessibility: { label: 'Barrierefrei', component: Accessibility },
briefcase: { label: 'Arbeit', component: Briefcase },
'graduation-cap': { label: 'Bildung', component: GraduationCap },
'book-open': { label: 'Buch', component: BookOpen },
'file-text': { label: 'Dokument', component: FileText },
info: { label: 'Info', component: Info },
lightbulb: { label: 'Idee', component: Lightbulb },
'shield-check': { label: 'Schutz', component: ShieldCheck },
scale: { label: 'Recht', component: Scale },
utensils: { label: 'Essen', component: Utensils },
coffee: { label: 'Café', component: Coffee },
apple: { label: 'Apfel', component: Apple },
leaf: { label: 'Blatt', component: Leaf },
'tree-pine': { label: 'Baum', component: TreePine },
hammer: { label: 'Hammer', component: Hammer },
wrench: { label: 'Werkzeug', component: Wrench },
palette: { label: 'Kunst', component: Palette },
music: { label: 'Musik', component: Music },
camera: { label: 'Kamera', component: Camera },
sparkles: { label: 'Funkeln', component: Sparkles },
star: { label: 'Stern', component: Star },
puzzle: { label: 'Puzzle', component: Puzzle },
bike: { label: 'Fahrrad', component: Bike },
car: { label: 'Auto', component: Car },
truck: { label: 'Lieferung', component: Truck },
'map-pin': { label: 'Ort', component: MapPin },
phone: { label: 'Telefon', component: Phone },
mail: { label: 'Post', component: Mail },
'message-circle': { label: 'Nachricht', component: MessageCircle }
};
export const iconFor = (name: string) => ICONS[name]?.component ?? FileText;

23
src/lib/palette.ts Normal file
View file

@ -0,0 +1,23 @@
/**
* Farbpalette für Kacheln und Seiten. Bewusst eine feste Auswahl, damit
* Redakteure nichts „kaputt-designen“ können – und alles gut zusammenpasst.
* Die Werte werden als CSS-Variablen genutzt (siehe app.css → .tone-*)
*/
export const TONES = {
coral: 'Koralle',
amber: 'Bernstein',
lime: 'Limette',
emerald: 'Smaragd',
teal: 'Petrol',
sky: 'Himmel',
indigo: 'Indigo',
violet: 'Veilchen',
rose: 'Rose',
slate: 'Schiefer'
} as const;
export type Tone = keyof typeof TONES;
export const toneNames = Object.keys(TONES) as Tone[];
export const isTone = (v: string): v is Tone => v in TONES;

19
src/lib/prefs.svelte.ts Normal file
View file

@ -0,0 +1,19 @@
import { PREFS_COOKIE, type Prefs } from './prefs';
/** Reaktive Anzeige-Einstellungen im Browser. */
class PrefsState {
current = $state<Prefs>({ theme: 'system', size: 'm', easy: false });
init(p: Prefs) {
this.current = { ...p };
}
set(patch: Partial<Prefs>) {
this.current = { ...this.current, ...patch };
document.cookie = `${PREFS_COOKIE}=${encodeURIComponent(JSON.stringify(this.current))}; path=/; max-age=31536000; samesite=lax`;
document.documentElement.dataset.theme = this.current.theme;
document.documentElement.dataset.size = this.current.size;
}
}
export const prefs = new PrefsState();

23
src/lib/prefs.ts Normal file
View file

@ -0,0 +1,23 @@
/** Persönliche Anzeige-Einstellungen – im Cookie gespeichert, damit der Server gleich richtig rendert. */
export type Prefs = {
theme: 'system' | 'light' | 'dark';
size: 'm' | 'l' | 'xl';
easy: boolean;
};
export const PREFS_COOKIE = 'wa_prefs';
export const DEFAULT_PREFS: Prefs = { theme: 'system', size: 'm', easy: false };
export function parsePrefs(raw: string | undefined): Prefs {
if (!raw) return DEFAULT_PREFS;
try {
const p = JSON.parse(decodeURIComponent(raw));
return {
theme: ['system', 'light', 'dark'].includes(p.theme) ? p.theme : 'system',
size: ['m', 'l', 'xl'].includes(p.size) ? p.size : 'm',
easy: p.easy === true
};
} catch {
return DEFAULT_PREFS;
}
}

86
src/lib/server/auth.ts Normal file
View file

@ -0,0 +1,86 @@
import { randomBytes, scrypt, timingSafeEqual, createHash } from 'node:crypto';
import { promisify } from 'node:util';
import { eq, lt } from 'drizzle-orm';
import type { Cookies } from '@sveltejs/kit';
import { db } from './db';
import { sessions, users, type User } from './db/schema';
const scryptAsync = promisify(scrypt) as (pw: string, salt: Buffer, len: number) => Promise<Buffer>;
export const SESSION_COOKIE = 'wa_session';
const SESSION_DAYS = 30;
export async function hashPassword(password: string): Promise<string> {
const salt = randomBytes(16);
const key = await scryptAsync(password, salt, 64);
return `scrypt$${salt.toString('base64')}$${key.toString('base64')}`;
}
export async function verifyPassword(password: string, stored: string): Promise<boolean> {
const [algo, saltB64, keyB64] = stored.split('$');
if (algo !== 'scrypt' || !saltB64 || !keyB64) return false;
const expected = Buffer.from(keyB64, 'base64');
const actual = await scryptAsync(password, Buffer.from(saltB64, 'base64'), expected.length);
return timingSafeEqual(expected, actual);
}
const hashToken = (token: string) => createHash('sha256').update(token).digest('hex');
export function createSession(cookies: Cookies, userId: number) {
const token = randomBytes(32).toString('base64url');
const expiresAt = new Date(Date.now() + SESSION_DAYS * 864e5);
db.insert(sessions).values({ id: hashToken(token), userId, expiresAt }).run();
cookies.set(SESSION_COOKIE, token, {
path: '/',
httpOnly: true,
sameSite: 'lax',
expires: expiresAt
});
}
export type SessionUser = Pick<User, 'id' | 'email' | 'name' | 'role'>;
export function validateSession(token: string | undefined): SessionUser | null {
if (!token) return null;
const row = db
.select({ session: sessions, user: users })
.from(sessions)
.innerJoin(users, eq(sessions.userId, users.id))
.where(eq(sessions.id, hashToken(token)))
.get();
if (!row) return null;
if (row.session.expiresAt.getTime() < Date.now()) {
db.delete(sessions).where(eq(sessions.id, row.session.id)).run();
return null;
}
const { id, email, name, role } = row.user;
return { id, email, name, role };
}
export function destroySession(cookies: Cookies) {
const token = cookies.get(SESSION_COOKIE);
if (token) db.delete(sessions).where(eq(sessions.id, hashToken(token))).run();
cookies.delete(SESSION_COOKIE, { path: '/' });
}
export function purgeExpiredSessions() {
db.delete(sessions).where(lt(sessions.expiresAt, new Date())).run();
}
/** Legt beim allerersten Start einen Admin aus den Umgebungsvariablen an. */
export async function ensureInitialAdmin() {
const existing = db.select({ id: users.id }).from(users).limit(1).get();
if (existing) return;
const email = process.env.ADMIN_EMAIL;
const password = process.env.ADMIN_PASSWORD;
if (!email || !password) {
console.warn(
'[setup] Noch kein Benutzer vorhanden. Setze ADMIN_EMAIL und ADMIN_PASSWORD oder nutze `npm run user:create`.'
);
return;
}
db.insert(users)
.values({ email: email.toLowerCase(), name: 'Administrator', role: 'admin', passwordHash: await hashPassword(password) })
.run();
console.log(`[setup] Admin-Zugang ${email} angelegt.`);
}

229
src/lib/server/content.ts Normal file
View file

@ -0,0 +1,229 @@
import { and, asc, desc, eq, gte, inArray, like, lte, or, sql } from 'drizzle-orm';
import { db } from './db';
import { contacts, events, media, pages, posts, type Attachment, type Media, type Page, type Post } from './db/schema';
import { mediaUrl, thumbUrl } from './uploads';
import type { AttachmentItem, ContactCard, EventItem, MediaItem, PageCard, PostCard } from '$lib/types';
import { today } from '$lib/dates';
export function toMediaItem(m: Media): MediaItem {
return {
id: m.id,
url: mediaUrl(m),
thumb: thumbUrl(m),
alt: m.alt,
width: m.width,
height: m.height,
mimeType: m.mimeType,
name: m.originalName,
size: m.size,
isImage: m.mimeType.startsWith('image/')
};
}
export function mediaByIds(ids: (number | null | undefined)[]): Map<number, MediaItem> {
const clean = [...new Set(ids.filter((x): x is number => typeof x === 'number'))];
if (!clean.length) return new Map();
return new Map(db.select().from(media).where(inArray(media.id, clean)).all().map((m) => [m.id, toMediaItem(m)]));
}
export function getMedia(id: number | null | undefined): MediaItem | null {
if (!id) return null;
return mediaByIds([id]).get(id) ?? null;
}
export function contactsByIds(ids: number[]): ContactCard[] {
if (!ids.length) return [];
const rows = db.select().from(contacts).where(inArray(contacts.id, ids)).all();
const photos = mediaByIds(rows.map((r) => r.photoId));
const byId = new Map(rows.map((r) => [r.id, r]));
return ids
.map((id) => byId.get(id))
.filter((r) => !!r)
.map((r) => ({
id: r.id,
name: r.name,
role: r.role,
location: r.location,
email: r.email,
phone: r.phone,
photo: r.photoId ? (photos.get(r.photoId) ?? null) : null
}));
}
export function listedContacts(): ContactCard[] {
const rows = db
.select({ id: contacts.id })
.from(contacts)
.where(eq(contacts.listed, true))
.orderBy(asc(contacts.sortOrder), asc(contacts.name))
.all();
return contactsByIds(rows.map((r) => r.id));
}
export function attachmentsOf(list: Attachment[]): AttachmentItem[] {
const files = mediaByIds(list.map((a) => a.mediaId));
return list.flatMap((a) => {
const file = files.get(a.mediaId);
return file ? [{ title: a.title || file.name, file }] : [];
});
}
// ─── Meldungen ────────────────────────────────────────────────────────────────
const visiblePost = () => and(eq(posts.published, true), lte(posts.publishedAt, new Date()));
function toPostCards(rows: Post[]): PostCard[] {
const covers = mediaByIds(rows.map((r) => r.coverId));
return rows.map((r) => ({
id: r.id,
slug: r.slug,
title: r.title,
teaser: r.teaser,
cover: r.coverId ? (covers.get(r.coverId) ?? null) : null,
publishedAt: r.publishedAt.toISOString(),
pinned: r.pinned
}));
}
export function listPosts({ limit = 20, offset = 0 } = {}) {
const rows = db
.select()
.from(posts)
.where(visiblePost())
.orderBy(desc(posts.pinned), desc(posts.publishedAt))
.limit(limit)
.offset(offset)
.all();
const total = db.select({ n: sql<number>`count(*)` }).from(posts).where(visiblePost()).get()?.n ?? 0;
return { items: toPostCards(rows), total };
}
export function getPost(slug: string) {
const post = db.select().from(posts).where(and(eq(posts.slug, slug), visiblePost())).get();
if (!post) return null;
const gallery = mediaByIds(post.gallery);
return {
id: post.id,
slug: post.slug,
title: post.title,
teaser: post.teaser,
content: post.content,
contentEasy: post.contentEasy,
videoUrl: post.videoUrl,
publishedAt: post.publishedAt.toISOString(),
cover: getMedia(post.coverId),
gallery: post.gallery.map((id) => gallery.get(id)).filter((m): m is MediaItem => !!m),
attachments: attachmentsOf(post.attachments),
contacts: contactsByIds(post.contactIds)
};
}
// ─── Seiten ───────────────────────────────────────────────────────────────────
const toPageCard = (p: Page): PageCard => ({
id: p.id,
slug: p.slug,
title: p.title,
teaser: p.teaser,
icon: p.icon,
color: p.color
});
export function childPages(parentId: number | null): PageCard[] {
return db
.select()
.from(pages)
.where(and(eq(pages.published, true), parentId === null ? sql`${pages.parentId} is null` : eq(pages.parentId, parentId)))
.orderBy(asc(pages.sortOrder), asc(pages.title))
.all()
.map(toPageCard);
}
export function getPage(slug: string) {
const page = db.select().from(pages).where(and(eq(pages.slug, slug), eq(pages.published, true))).get();
if (!page) return null;
const trail: { slug: string; title: string }[] = [];
let parentId = page.parentId;
for (let depth = 0; parentId && depth < 10; depth++) {
const parent = db.select().from(pages).where(eq(pages.id, parentId)).get();
if (!parent) break;
trail.unshift({ slug: parent.slug, title: parent.title });
parentId = parent.parentId;
}
return {
id: page.id,
slug: page.slug,
title: page.title,
teaser: page.teaser,
icon: page.icon,
color: page.color,
content: page.content,
contentEasy: page.contentEasy,
cover: getMedia(page.coverId),
attachments: attachmentsOf(page.attachments),
contacts: contactsByIds(page.contactIds),
children: childPages(page.id),
trail
};
}
// ─── Termine ──────────────────────────────────────────────────────────────────
const toEventItem = (e: typeof events.$inferSelect): EventItem => ({
id: e.id,
title: e.title,
kind: e.kind,
startDate: e.startDate,
endDate: e.endDate,
startTime: e.startTime,
endTime: e.endTime,
location: e.location,
description: e.description
});
/** Termine, die ab `from` noch stattfinden (auch laufende mehrtägige). */
export function upcomingEvents({ from = today(), to, limit, kind }: { from?: string; to?: string; limit?: number; kind?: 'event' | 'closure' } = {}) {
const endOrStart = sql`coalesce(nullif(${events.endDate}, ''), ${events.startDate})`;
const conditions = [eq(events.published, true), gte(endOrStart, from)];
if (to) conditions.push(lte(events.startDate, to));
if (kind) conditions.push(eq(events.kind, kind));
const q = db
.select()
.from(events)
.where(and(...conditions))
.orderBy(asc(events.startDate), asc(events.startTime));
return (limit ? q.limit(limit) : q).all().map(toEventItem);
}
// ─── Suche ────────────────────────────────────────────────────────────────────
export function search(term: string) {
const q = `%${term.replace(/[%_]/g, '')}%`;
const postHits = db
.select()
.from(posts)
.where(and(visiblePost(), or(like(posts.title, q), like(posts.teaser, q), like(posts.content, q))))
.orderBy(desc(posts.publishedAt))
.limit(20)
.all();
const pageHits = db
.select()
.from(pages)
.where(and(eq(pages.published, true), or(like(pages.title, q), like(pages.teaser, q), like(pages.content, q))))
.limit(20)
.all();
const eventHits = db
.select()
.from(events)
.where(and(eq(events.published, true), gte(events.startDate, today()), or(like(events.title, q), like(events.location, q), like(events.description, q))))
.orderBy(asc(events.startDate))
.limit(20)
.all();
return {
posts: toPostCards(postHits),
pages: pageHits.map(toPageCard),
events: eventHits.map(toEventItem)
};
}

View file

@ -0,0 +1,17 @@
import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import { migrate } from 'drizzle-orm/better-sqlite3/migrator';
import path from 'node:path';
import { DB_PATH } from '../env';
import * as schema from './schema';
const sqlite = new Database(DB_PATH);
sqlite.pragma('journal_mode = WAL');
sqlite.pragma('foreign_keys = ON');
sqlite.pragma('busy_timeout = 5000');
export const db = drizzle(sqlite, { schema });
migrate(db, { migrationsFolder: path.resolve(process.env.MIGRATIONS_DIR ?? 'drizzle') });
export { schema };

186
src/lib/server/db/schema.ts Normal file
View file

@ -0,0 +1,186 @@
import { sql } from 'drizzle-orm';
import { integer, sqliteTable, text, index, uniqueIndex, type AnySQLiteColumn } from 'drizzle-orm/sqlite-core';
const timestamps = {
createdAt: integer('created_at', { mode: 'timestamp' })
.notNull()
.default(sql`(unixepoch())`),
updatedAt: integer('updated_at', { mode: 'timestamp' })
.notNull()
.default(sql`(unixepoch())`)
.$onUpdate(() => new Date())
};
/** Anhang (PDF, Bild …) an einem Inhalt */
export type Attachment = { mediaId: number; title: string };
// ─── Benutzer & Sitzungen ──────────────────────────────────────────────────────
export const users = sqliteTable('users', {
id: integer('id').primaryKey({ autoIncrement: true }),
email: text('email').notNull().unique(),
name: text('name').notNull(),
passwordHash: text('password_hash').notNull(),
role: text('role', { enum: ['admin', 'editor'] })
.notNull()
.default('editor'),
...timestamps
});
export const sessions = sqliteTable('sessions', {
id: text('id').primaryKey(),
userId: integer('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
expiresAt: integer('expires_at', { mode: 'timestamp' }).notNull()
});
// ─── Einstellungen (Key/Value) ─────────────────────────────────────────────────
export const settings = sqliteTable('settings', {
key: text('key').primaryKey(),
value: text('value', { mode: 'json' }).notNull()
});
// ─── Medien ────────────────────────────────────────────────────────────────────
export const media = sqliteTable('media', {
id: integer('id').primaryKey({ autoIncrement: true }),
/** Dateiname im Upload-Verzeichnis */
filename: text('filename').notNull().unique(),
/** Vorschaubild (nur bei Bildern) */
thumbnail: text('thumbnail'),
originalName: text('original_name').notNull(),
mimeType: text('mime_type').notNull(),
size: integer('size').notNull(),
width: integer('width'),
height: integer('height'),
alt: text('alt').notNull().default(''),
...timestamps
});
// ─── Ansprechpartner ───────────────────────────────────────────────────────────
export const contacts = sqliteTable('contacts', {
id: integer('id').primaryKey({ autoIncrement: true }),
name: text('name').notNull(),
role: text('role').notNull().default(''),
location: text('location').notNull().default(''),
email: text('email').notNull().default(''),
phone: text('phone').notNull().default(''),
photoId: integer('photo_id').references(() => media.id, { onDelete: 'set null' }),
/** Im öffentlichen Verzeichnis anzeigen */
listed: integer('listed', { mode: 'boolean' }).notNull().default(true),
sortOrder: integer('sort_order').notNull().default(0),
...timestamps
});
// ─── Seiten (hierarchisch) ─────────────────────────────────────────────────────
export const pages = sqliteTable(
'pages',
{
id: integer('id').primaryKey({ autoIncrement: true }),
parentId: integer('parent_id').references((): AnySQLiteColumn => pages.id, { onDelete: 'set null' }),
title: text('title').notNull(),
slug: text('slug').notNull(),
teaser: text('teaser').notNull().default(''),
icon: text('icon').notNull().default('file-text'),
color: text('color').notNull().default('sky'),
coverId: integer('cover_id').references(() => media.id, { onDelete: 'set null' }),
content: text('content').notNull().default(''),
/** Optionale Fassung in Leichter Sprache */
contentEasy: text('content_easy').notNull().default(''),
attachments: text('attachments', { mode: 'json' }).$type<Attachment[]>().notNull().default([]),
contactIds: text('contact_ids', { mode: 'json' }).$type<number[]>().notNull().default([]),
sortOrder: integer('sort_order').notNull().default(0),
published: integer('published', { mode: 'boolean' }).notNull().default(true),
...timestamps
},
(t) => [uniqueIndex('pages_slug_idx').on(t.slug), index('pages_parent_idx').on(t.parentId)]
);
// ─── Meldungen / News ──────────────────────────────────────────────────────────
export const posts = sqliteTable(
'posts',
{
id: integer('id').primaryKey({ autoIncrement: true }),
title: text('title').notNull(),
slug: text('slug').notNull(),
teaser: text('teaser').notNull().default(''),
coverId: integer('cover_id').references(() => media.id, { onDelete: 'set null' }),
content: text('content').notNull().default(''),
contentEasy: text('content_easy').notNull().default(''),
/** YouTube-/Vimeo-Link oder leer */
videoUrl: text('video_url').notNull().default(''),
gallery: text('gallery', { mode: 'json' }).$type<number[]>().notNull().default([]),
attachments: text('attachments', { mode: 'json' }).$type<Attachment[]>().notNull().default([]),
contactIds: text('contact_ids', { mode: 'json' }).$type<number[]>().notNull().default([]),
pinned: integer('pinned', { mode: 'boolean' }).notNull().default(false),
published: integer('published', { mode: 'boolean' }).notNull().default(true),
publishedAt: integer('published_at', { mode: 'timestamp' })
.notNull()
.default(sql`(unixepoch())`),
...timestamps
},
(t) => [uniqueIndex('posts_slug_idx').on(t.slug), index('posts_published_idx').on(t.publishedAt)]
);
// ─── Termine & Schließzeiten ───────────────────────────────────────────────────
export const events = sqliteTable(
'events',
{
id: integer('id').primaryKey({ autoIncrement: true }),
title: text('title').notNull(),
kind: text('kind', { enum: ['event', 'closure'] })
.notNull()
.default('event'),
/** YYYY-MM-DD */
startDate: text('start_date').notNull(),
/** YYYY-MM-DD, leer = eintägig */
endDate: text('end_date').notNull().default(''),
/** HH:MM, leer = ganztägig */
startTime: text('start_time').notNull().default(''),
endTime: text('end_time').notNull().default(''),
location: text('location').notNull().default(''),
description: text('description').notNull().default(''),
published: integer('published', { mode: 'boolean' }).notNull().default(true),
...timestamps
},
(t) => [index('events_start_idx').on(t.startDate)]
);
// ─── Startseiten-Kacheln ───────────────────────────────────────────────────────
export const tiles = sqliteTable('tiles', {
id: integer('id').primaryKey({ autoIncrement: true }),
label: text('label').notNull(),
icon: text('icon').notNull().default('star'),
color: text('color').notNull().default('sky'),
/** Interner Pfad (/meldungen, /s/slug …) oder externe URL */
href: text('href').notNull(),
sortOrder: integer('sort_order').notNull().default(0),
...timestamps
});
// ─── Nachrichten aus dem Kontaktformular ───────────────────────────────────────
export const messages = sqliteTable('messages', {
id: integer('id').primaryKey({ autoIncrement: true }),
name: text('name').notNull(),
email: text('email').notNull(),
message: text('message').notNull(),
read: integer('read', { mode: 'boolean' }).notNull().default(false),
...timestamps
});
export type User = typeof users.$inferSelect;
export type Media = typeof media.$inferSelect;
export type Contact = typeof contacts.$inferSelect;
export type Page = typeof pages.$inferSelect;
export type Post = typeof posts.$inferSelect;
export type Event = typeof events.$inferSelect;
export type Tile = typeof tiles.$inferSelect;
export type Message = typeof messages.$inferSelect;

8
src/lib/server/env.ts Normal file
View file

@ -0,0 +1,8 @@
import path from 'node:path';
import fs from 'node:fs';
export const DATA_DIR = path.resolve(process.env.DATA_DIR ?? 'data');
export const UPLOAD_DIR = path.join(DATA_DIR, 'uploads');
export const DB_PATH = process.env.DATABASE_PATH ?? path.join(DATA_DIR, 'app.db');
fs.mkdirSync(UPLOAD_DIR, { recursive: true });

78
src/lib/server/forms.ts Normal file
View file

@ -0,0 +1,78 @@
import { error } from '@sveltejs/kit';
import { and, eq, ne } from 'drizzle-orm';
import type { SQLiteColumn, SQLiteTable } from 'drizzle-orm/sqlite-core';
import { db } from './db';
import type { SessionUser } from './auth';
import type { Attachment } from './db/schema';
/** Bequemes, sicheres Auslesen von Formularfeldern. */
export function fields(form: FormData) {
const raw = (k: string) => {
const v = form.get(k);
return typeof v === 'string' ? v : '';
};
const json = <T>(k: string, fallback: T): T => {
try {
return JSON.parse(raw(k)) ?? fallback;
} catch {
return fallback;
}
};
return {
str: (k: string, max = 200) => raw(k).trim().slice(0, max),
html: (k: string) => raw(k).slice(0, 500_000),
int: (k: string): number | null => {
const v = raw(k).trim();
const n = Number(v);
return v !== '' && Number.isFinite(n) ? Math.trunc(n) : null;
},
bool: (k: string) => ['on', 'true', '1'].includes(raw(k)),
ids: (k: string): number[] => json<unknown[]>(k, []).filter((x): x is number => Number.isInteger(x)),
attachments: (k: string): Attachment[] =>
json<unknown[]>(k, [])
.filter((a): a is Attachment => !!a && typeof a === 'object' && Number.isInteger((a as Attachment).mediaId))
.map((a) => ({ mediaId: a.mediaId, title: String(a.title ?? '').slice(0, 200) }))
};
}
export function slugify(input: string): string {
return (
input
.toLowerCase()
.replace(/ä/g, 'ae')
.replace(/ö/g, 'oe')
.replace(/ü/g, 'ue')
.replace(/ß/g, 'ss')
.normalize('NFKD')
.replace(/[̀-ͯ]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 80) || 'eintrag'
);
}
/** Macht einen Slug eindeutig (text, text-2, text-3 …). */
export function uniqueSlug(table: SQLiteTable & { slug: SQLiteColumn; id: SQLiteColumn }, wanted: string, excludeId?: number) {
const base = slugify(wanted);
for (let i = 1; ; i++) {
const candidate = i === 1 ? base : `${base}-${i}`;
const clash = db
.select({ id: table.id })
.from(table)
.where(excludeId ? and(eq(table.slug, candidate), ne(table.id, excludeId)) : eq(table.slug, candidate))
.get();
if (!clash) return candidate;
}
}
export function requireAdmin(user: SessionUser | null) {
if (user?.role !== 'admin') error(403, 'Nur für Administratoren.');
}
/** „neu“ oder numerische ID aus der URL */
export function parseId(param: string): number | 'new' {
if (param === 'neu') return 'new';
const id = Number(param);
if (!Number.isInteger(id) || id < 1) error(404);
return id;
}

View file

@ -0,0 +1,56 @@
import { asc } from 'drizzle-orm';
import { db } from './db';
import { pages } from './db/schema';
export type TreeRow = {
id: number;
parentId: number | null;
title: string;
slug: string;
icon: string;
color: string;
published: boolean;
depth: number;
first: boolean;
last: boolean;
};
/** Alle Seiten als eingerückte, sortierte Liste (Baum in Lesereihenfolge). */
export function pageTree(): TreeRow[] {
const all = db.select().from(pages).orderBy(asc(pages.sortOrder), asc(pages.title)).all();
const byParent = new Map<number | null, typeof all>();
for (const p of all) {
const key = p.parentId && all.some((x) => x.id === p.parentId) ? p.parentId : null;
byParent.set(key, [...(byParent.get(key) ?? []), p]);
}
const out: TreeRow[] = [];
const walk = (parent: number | null, depth: number) => {
const kids = byParent.get(parent) ?? [];
kids.forEach((p, i) => {
out.push({
id: p.id, parentId: p.parentId, title: p.title, slug: p.slug, icon: p.icon, color: p.color,
published: p.published, depth, first: i === 0, last: i === kids.length - 1
});
if (depth < 12) walk(p.id, depth + 1);
});
};
walk(null, 0);
return out;
}
/** IDs einer Seite und aller Unterseiten (damit man nichts in sich selbst verschiebt). */
export function descendantsOf(id: number): Set<number> {
const tree = pageTree();
const result = new Set([id]);
let changed = true;
while (changed) {
changed = false;
for (const r of tree) {
if (r.parentId && result.has(r.parentId) && !result.has(r.id)) {
result.add(r.id);
changed = true;
}
}
}
return result;
}

View file

@ -0,0 +1,34 @@
import sanitizeHtml from 'sanitize-html';
/** Bereinigt HTML aus dem Editor – nur harmlose Formatierungen bleiben übrig. */
export function cleanHtml(html: string): string {
return sanitizeHtml(html, {
allowedTags: [
'p', 'br', 'strong', 'em', 'u', 's', 'a', 'h2', 'h3', 'h4', 'ul', 'ol', 'li',
'blockquote', 'hr', 'img', 'figure', 'figcaption', 'mark', 'code'
],
allowedAttributes: {
a: ['href', 'target', 'rel'],
img: ['src', 'alt', 'width', 'height']
},
allowedSchemes: ['http', 'https', 'mailto', 'tel'],
allowedSchemesByTag: { img: ['http', 'https'] },
allowProtocolRelative: false,
transformTags: {
a: (tagName, attribs) => {
const external = /^https?:/i.test(attribs.href ?? '');
return {
tagName,
attribs: external ? { ...attribs, target: '_blank', rel: 'noopener noreferrer' } : attribs
};
}
}
}).trim();
}
/** Reiner Text (z. B. für Suche und Vorlesen). */
export function toPlainText(html: string): string {
return sanitizeHtml(html, { allowedTags: [], allowedAttributes: {} })
.replace(/\s+/g, ' ')
.trim();
}

View file

@ -0,0 +1,23 @@
import { db } from './db';
import { settings } from './db/schema';
import { DEFAULT_SETTINGS, type AppSettings } from '$lib/settings';
const KEY = 'app';
let cache: AppSettings | null = null;
export function getSettings(): AppSettings {
if (cache) return cache;
const row = db.select().from(settings).all().find((r) => r.key === KEY);
cache = { ...DEFAULT_SETTINGS, ...((row?.value as Partial<AppSettings>) ?? {}) };
return cache;
}
export function saveSettings(patch: Partial<AppSettings>) {
const next = { ...getSettings(), ...patch };
db.insert(settings)
.values({ key: KEY, value: next })
.onConflictDoUpdate({ target: settings.key, set: { value: next } })
.run();
cache = next;
return next;
}

32
src/lib/server/sorting.ts Normal file
View file

@ -0,0 +1,32 @@
import { asc, eq } from 'drizzle-orm';
import type { SQLiteColumn, SQLiteTable } from 'drizzle-orm/sqlite-core';
import type { SQL } from 'drizzle-orm';
import { db } from './db';
type Sortable = SQLiteTable & { id: SQLiteColumn; sortOrder: SQLiteColumn };
/**
* Verschiebt einen Eintrag um eine Position (dir = -1 / 1) innerhalb
* seiner Geschwister und nummeriert dabei sauber neu durch.
*/
export function moveItem(table: Sortable, id: number, dir: number, scope?: SQL) {
const rows = db
.select({ id: table.id })
.from(table)
.where(scope)
.orderBy(asc(table.sortOrder), asc(table.id))
.all() as { id: number }[];
const i = rows.findIndex((r) => r.id === id);
const j = i + dir;
if (i < 0 || j < 0 || j >= rows.length) return;
[rows[i], rows[j]] = [rows[j], rows[i]];
db.transaction((tx) => {
rows.forEach((r, idx) => tx.update(table).set({ sortOrder: idx } as never).where(eq(table.id, r.id)).run());
});
}
/** Nächste freie Position am Ende */
export function nextSortOrder(table: Sortable, scope?: SQL): number {
const rows = db.select({ s: table.sortOrder }).from(table).where(scope).all() as { s: number }[];
return rows.reduce((m, r) => Math.max(m, r.s + 1), 0);
}

92
src/lib/server/uploads.ts Normal file
View file

@ -0,0 +1,92 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { randomBytes } from 'node:crypto';
import sharp from 'sharp';
import { eq } from 'drizzle-orm';
import { db } from './db';
import { media, type Media } from './db/schema';
import { UPLOAD_DIR } from './env';
export const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
const IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/avif', 'image/heic', 'image/heif']);
const DOCUMENT_TYPES: Record<string, string> = {
'application/pdf': '.pdf',
'application/msword': '.doc',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
'application/vnd.ms-excel': '.xls',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',
'audio/mpeg': '.mp3',
'audio/mp4': '.m4a',
'video/mp4': '.mp4',
'text/plain': '.txt'
};
export const ACCEPTED_TYPES = [...IMAGE_TYPES, ...Object.keys(DOCUMENT_TYPES)].join(',');
const newName = () => `${Date.now().toString(36)}-${randomBytes(6).toString('hex')}`;
export class UploadError extends Error {}
/**
* Speichert eine hochgeladene Datei. Bilder werden automatisch gedreht,
* auf max. 2000 px verkleinert und als WebP gespeichert (inkl. Vorschaubild).
*/
export async function storeUpload(file: File, alt = ''): Promise<Media> {
if (file.size === 0) throw new UploadError('Die Datei ist leer.');
if (file.size > MAX_UPLOAD_BYTES) throw new UploadError('Die Datei ist größer als 25 MB.');
const buffer = Buffer.from(await file.arrayBuffer());
const base = newName();
if (IMAGE_TYPES.has(file.type)) {
const image = sharp(buffer, { failOn: 'none' }).rotate();
const main = await image
.clone()
.resize({ width: 2000, height: 2000, fit: 'inside', withoutEnlargement: true })
.webp({ quality: 82 })
.toBuffer({ resolveWithObject: true });
const thumb = await image
.clone()
.resize({ width: 480, height: 480, fit: 'inside', withoutEnlargement: true })
.webp({ quality: 75 })
.toBuffer();
await fs.writeFile(path.join(UPLOAD_DIR, `${base}.webp`), main.data);
await fs.writeFile(path.join(UPLOAD_DIR, `${base}-thumb.webp`), thumb);
return db
.insert(media)
.values({
filename: `${base}.webp`,
thumbnail: `${base}-thumb.webp`,
originalName: file.name,
mimeType: 'image/webp',
size: main.data.length,
width: main.info.width,
height: main.info.height,
alt
})
.returning()
.get();
}
const ext = DOCUMENT_TYPES[file.type];
if (!ext) throw new UploadError(`Dateityp „${file.type || 'unbekannt'}“ wird nicht unterstützt.`);
await fs.writeFile(path.join(UPLOAD_DIR, base + ext), buffer);
return db
.insert(media)
.values({ filename: base + ext, originalName: file.name, mimeType: file.type, size: file.size, alt })
.returning()
.get();
}
export async function deleteMedia(id: number) {
const item = db.select().from(media).where(eq(media.id, id)).get();
if (!item) return;
db.delete(media).where(eq(media.id, id)).run();
for (const f of [item.filename, item.thumbnail]) {
if (f) await fs.rm(path.join(UPLOAD_DIR, f), { force: true });
}
}
export const mediaUrl = (m: Pick<Media, 'filename'>) => `/uploads/${m.filename}`;
export const thumbUrl = (m: Pick<Media, 'filename' | 'thumbnail'>) => `/uploads/${m.thumbnail ?? m.filename}`;

38
src/lib/settings.ts Normal file
View file

@ -0,0 +1,38 @@
/** Einstellungen, die im Admin unter „Einstellungen“ gepflegt werden. */
export type AppSettings = {
/** Name der App (Kopfzeile, Homescreen-Symbol) */
appName: string;
/** Name der Einrichtung / des Trägers */
orgName: string;
/** Begrüßung auf der Startseite */
greeting: string;
/** Kurzer Text unter der Begrüßung */
intro: string;
/** Markenfarbe als Hex-Wert */
brandColor: string;
logoId: number | null;
website: string;
contactEmail: string;
contactIntro: string;
imprint: string;
privacy: string;
/** Wie viele Meldungen/Termine die Startseite zeigt */
homeNewsCount: number;
homeEventsCount: number;
};
export const DEFAULT_SETTINGS: AppSettings = {
appName: 'Werkstatt-App',
orgName: 'Unsere Werkstätten',
greeting: 'Schön, dass du da bist!',
intro: 'Hier findest du Neuigkeiten, Termine und alles Wichtige rund um deine Werkstatt.',
brandColor: '#0e7c66',
logoId: null,
website: '',
contactEmail: '',
contactIntro: 'Du hast Fragen oder Ideen für die App? Schreib uns gerne!',
imprint: '<p>Bitte im Admin-Bereich unter „Einstellungen“ ausfüllen.</p>',
privacy: '<p>Bitte im Admin-Bereich unter „Einstellungen“ ausfüllen.</p>',
homeNewsCount: 4,
homeEventsCount: 4
};

59
src/lib/types.ts Normal file
View file

@ -0,0 +1,59 @@
/** Datenformen, die an die Oberfläche gehen (Server → Browser). */
export type MediaItem = {
id: number;
url: string;
thumb: string;
alt: string;
width: number | null;
height: number | null;
mimeType: string;
name: string;
size: number;
isImage: boolean;
};
export type ContactCard = {
id: number;
name: string;
role: string;
location: string;
email: string;
phone: string;
photo: MediaItem | null;
};
export type AttachmentItem = { title: string; file: MediaItem };
export type PostCard = {
id: number;
slug: string;
title: string;
teaser: string;
cover: MediaItem | null;
publishedAt: string;
pinned: boolean;
};
export type EventItem = {
id: number;
title: string;
kind: 'event' | 'closure';
startDate: string;
endDate: string;
startTime: string;
endTime: string;
location: string;
description: string;
};
export type PageCard = {
id: number;
slug: string;
title: string;
teaser: string;
icon: string;
color: string;
};
export type Favorite = { href: string; title: string; kind: 'post' | 'page' | 'event' };