Führe eine zentrale Widget-Registry mit visuellem Seiteneditor ein.
CI Feature / test (push) Successful in 31s

- Codebasiertes Widget-Register (config/cms.php) mit Vertrag
  {id, type, v, variant, settings, data, refs}: Typkennung, Schemaversion,
  Prüfregeln, freigegebene Varianten, Editorfelder, Blade-Ansicht,
  Verweisauflösung und Medienliste je Widget-Art.
- Die sechs Bestandsbausteine bleiben als Version 1 lesbar; gespeicherte
  Revisionen werden nicht umgeschrieben, sondern beim Lesen angehoben
  (Bild und Text: Version 2 mit Titel, formatiertem Text, Bild links/rechts).
  Wiederherstellen kopiert eine Revision unverändert.
- Neue Widgets: Einstieg (Hero) und Programm-/Modulkarten. Letztere speichern
  nur Verweise; Titel und Kurzbeschreibung kommen aus den Fachdaten. Öffentlich
  erscheinen nur Programme mit Anzeigefreigabe (gleiche Regel wie /programme,
  jetzt in PublicCatalogReader); Module nur in der Redaktionsvorschau, bis
  öffentliche Profile (ADR-29) bestehen.
- Ein Renderer für öffentliche Seite, Vorschau und Blockvorschau im Editor.
- Seiteneditor als Filament-Builder: Auswahl mit Beschreibung und Schema,
  kompakte Abschnitte mit Vorschau, Bearbeitung im Dialog, Sortieren,
  Duplizieren. Speichern erzeugt nur einen Entwurf.
- Vorschau einer Revision in 390/768/1440 px; Vorschauroute nutzt den
  Personal-Guard (vorher war sie für Redakteure ohne Mitgliedersitzung
  nicht erreichbar).
- Basislayout in Komponenten (Marke, Kopf, Fuß, Seitenvorlage).
- Navigation: bearbeiten, ausblenden, löschen, per Ziehen sortieren;
  unsichere Adressen (javascript:) werden abgewiesen und nicht ausgegeben.
  Ergänzende Migration is_visible (Vorgabe sichtbar).
- Pfadfehler und doppelte Pfade erscheinen am Pfadfeld statt still zu scheitern.

Tests: BlockRegistryTest geht in WidgetRegistryTest auf (gleiche Prüfungen
plus Registrierung, Versionierung, Bereinigung). Bestandsseiten werden gegen
Textfixtures aus dem Stand vor der Umstellung geprüft.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-17 17:49:30 +01:00
1 parent cfdd6de0c7
commit 9d936bfa4a
76 files changed
+4237 -475

No files matched your search

-181
View File
@@ -1,181 +0,0 @@
<?php
namespace App\Domain\Cms\Blocks;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
class BlockRegistry
{
/**
* @return array<string, string>
*/
public function labels(): array
{
return [
'heading' => 'Überschrift und Einleitung',
'prose' => 'Fließtext',
'image_text' => 'Bild und Text',
'call_to_action' => 'Handlungsaufruf',
'cards' => 'Karten',
'faq' => 'FAQ',
];
}
/**
* @param list<array<string, mixed>> $blocks
* @return list<array<string, mixed>>
*/
public function normalize(array $blocks): array
{
$normalized = [];
foreach (array_values($blocks) as $index => $block) {
if (! is_array($block)) {
throw ValidationException::withMessages([
"blocks.$index" => 'Ein Baustein ist unvollständig.',
]);
}
$type = $block['type'] ?? null;
if (! is_string($type) || ! array_key_exists($type, $this->labels())) {
throw ValidationException::withMessages([
"blocks.$index.type" => 'Dieser Bausteintyp ist nicht freigegeben.',
]);
}
$normalized[] = $this->normalizeOne($type, $block, $index);
}
return $normalized;
}
/**
* @param array<string, mixed> $block
* @return array<string, mixed>
*/
private function normalizeOne(string $type, array $block, int $index): array
{
$rules = match ($type) {
'heading' => [
'heading' => ['required', 'string', 'max:200'],
'intro' => ['nullable', 'string', 'max:1000'],
],
'prose' => [
'body' => ['required', 'string', 'max:20000'],
],
'image_text' => [
'image' => ['nullable', 'string', 'max:255'],
'alt' => ['required', 'string', 'max:300'],
'body' => ['required', 'string', 'max:5000'],
],
'call_to_action' => [
'heading' => ['required', 'string', 'max:200'],
'text' => ['nullable', 'string', 'max:1000'],
'label' => ['required', 'string', 'max:80'],
'url' => ['required', 'string', 'max:500'],
],
'cards' => [
'items' => ['required', 'array', 'min:1', 'max:6'],
'items.*.title' => ['required', 'string', 'max:120'],
'items.*.text' => ['nullable', 'string', 'max:500'],
'items.*.url' => ['nullable', 'string', 'max:500'],
],
'faq' => [
'items' => ['required', 'array', 'min:1', 'max:20'],
'items.*.question' => ['required', 'string', 'max:300'],
'items.*.answer' => ['required', 'string', 'max:2000'],
],
default => [],
};
$validator = Validator::make($block, $rules);
if ($validator->fails()) {
$messages = [];
foreach ($validator->errors()->messages() as $key => $errors) {
$messages["blocks.$index.$key"] = $errors;
}
throw ValidationException::withMessages($messages);
}
$clean = ['type' => $type];
foreach (array_keys($rules) as $key) {
if (str_contains($key, '.*')) {
continue;
}
$clean[$key] = $block[$key] ?? null;
}
if ($type === 'image_text') {
$clean['image'] = $this->imagePath($clean['image'] ?? null, $index);
}
if (in_array($type, ['call_to_action', 'cards'], true)) {
$clean = $this->assertSafeUrls($clean, $index);
}
return $clean;
}
private function imagePath(mixed $image, int $index): ?string
{
if (is_array($image)) {
$image = $image[0] ?? null;
}
if ($image === null || $image === '') {
return null;
}
if (! is_string($image) || str_contains($image, '..') || ! str_starts_with($image, 'cms/')) {
throw ValidationException::withMessages([
"blocks.$index.image" => 'Das Bild liegt nicht im öffentlichen Medienbereich.',
]);
}
return $image;
}
/**
* @param array<string, mixed> $block
* @return array<string, mixed>
*/
private function assertSafeUrls(array $block, int $index): array
{
if (array_key_exists('url', $block)) {
$block['url'] = $this->safeUrl($block['url'], "blocks.$index.url");
}
if (isset($block['items']) && is_array($block['items'])) {
foreach ($block['items'] as $itemIndex => $item) {
if (is_array($item) && filled($item['url'] ?? null)) {
$block['items'][$itemIndex]['url'] = $this->safeUrl($item['url'], "blocks.$index.items.$itemIndex.url");
}
}
}
return $block;
}
private function safeUrl(mixed $url, string $key): string
{
if (! is_string($url)) {
throw ValidationException::withMessages([$key => 'Die Adresse ist ungültig.']);
}
$isRelative = str_starts_with($url, '/') && ! str_starts_with($url, '//');
$isAbsolute = preg_match('#^https?://#i', $url) === 1;
if (! $isRelative && ! $isAbsolute) {
throw ValidationException::withMessages([$key => 'Erlaubt sind Seitenpfade oder http(s)-Adressen.']);
}
return $url;
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Domain\Cms\Catalog;
/**
* Anzeigedaten eines Fachobjekts, zur Laufzeit aus den maßgeblichen Fachdaten gelesen. Wird nie gespeichert.
*/
final readonly class CatalogEntry
{
public function __construct(
public int $id,
public string $title,
public ?string $summary,
public string $kindLabel,
public ?string $url,
public bool $public,
) {}
}
@@ -0,0 +1,185 @@
<?php
namespace App\Domain\Cms\Catalog;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionDisplayRelease;
use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\EditorialContentKind;
use Illuminate\Support\Collection;
/**
* Lesesicht „Öffentlicher Katalog“ für Website und CMS (Website-CMS-Zielarchitektur 5.1, 6.2).
*
* Übergangsregel, solange öffentliche Fachobjektprofile (ADR-29) fehlen:
* Öffentlich gezeigt wird nur, was die Website bereits heute öffentlich zeigt, nämlich Kompositionen
* der Inhaltsart „programm“ mit einer zur Anzeige freigegebenen Fassung (Route /programme).
* Module haben noch keine öffentliche Seitenart; sie sind im Editor wählbar und erscheinen nur in
* der geschützten Redaktionsvorschau, nie auf der öffentlichen Seite.
*
* Gelesen werden nur Anzeigetitel, Kurzbeschreibung und Inhaltsart, nie Dateien, Lehrtexte oder
* Vorschaubilder der Bibliothek (diese sind geschützt, Paket 6).
*/
class PublicCatalogReader
{
/** Inhaltsarten mit öffentlicher Seitenart. */
public const PUBLIC_KINDS = ['programm'];
/** Inhaltsarten, die ein Katalog-Widget referenzieren darf. */
public const SELECTABLE_KINDS = ['programm', 'modul'];
public function __construct(private readonly CompositionDisplayRelease $releases) {}
/**
* @return Collection<int, Composition>
*/
public function publicPrograms(): Collection
{
$kind = EditorialContentKind::query()->where('slug', 'programm')->first();
if ($kind === null) {
return collect();
}
return Composition::query()
->where('editorial_content_kind_id', $kind->id)
->orderBy('designation')
->get()
->filter(fn (Composition $composition): bool => $this->shownVersion($composition) !== null)
->values();
}
/**
* Gezeigte Fassung einer öffentlich gezeigten Komposition, sonst null.
*/
public function shownVersion(Composition $composition): ?CompositionVersion
{
if (! in_array($composition->editorialContentKind?->slug, self::PUBLIC_KINDS, true)) {
return null;
}
return $this->releases->highestReleasedVersion($composition);
}
public function isPublic(Composition $composition): bool
{
return $this->shownVersion($composition) !== null;
}
/**
* Wählbar sind Programme und Module mit zur Anzeige freigegebener Fassung, die nicht archiviert sind.
*/
public function isSelectable(Composition $composition): bool
{
return $composition->archived_at === null
&& in_array($composition->editorialContentKind?->slug, self::SELECTABLE_KINDS, true)
&& $this->releases->highestReleasedVersion($composition) !== null;
}
/**
* Suchtreffer für die Auswahl im Editor: Kennung => Bezeichnung mit Sichtbarkeitshinweis.
*
* @return array<int, string>
*/
public function search(?string $term, int $limit = 25): array
{
$term = trim((string) $term);
$candidates = Composition::query()
->with('editorialContentKind')
->whereNull('archived_at')
->whereHas('editorialContentKind', fn ($query) => $query->whereIn('slug', self::SELECTABLE_KINDS))
->when($term !== '', function ($query) use ($term): void {
$like = '%'.mb_strtolower($term).'%';
$query->where(fn ($inner) => $inner
->whereRaw('LOWER(designation) LIKE ?', [$like])
->orWhereRaw('LOWER(COALESCE(display_title, \'\')) LIKE ?', [$like]));
})
->orderBy('designation')
->limit($limit * 3)
->get();
$options = [];
foreach ($candidates as $composition) {
if (! $this->isSelectable($composition)) {
continue;
}
$options[$composition->id] = $this->optionLabel($composition);
if (count($options) >= $limit) {
break;
}
}
return $options;
}
public function labelFor(mixed $id): ?string
{
$composition = is_numeric($id) ? Composition::query()->with('editorialContentKind')->find((int) $id) : null;
return $composition === null ? null : $this->optionLabel($composition);
}
/**
* Löst Verweise in Anzeigeeinträge auf. Öffentlich entfallen nicht öffentliche Objekte stillschweigend.
*
* @param list<array{type?: mixed, id?: mixed}> $refs
* @return list<CatalogEntry>
*/
public function entries(array $refs, bool $includeNonPublic): array
{
$ids = [];
foreach ($refs as $ref) {
if (is_array($ref) && ($ref['type'] ?? null) === 'composition' && is_numeric($ref['id'] ?? null)) {
$ids[] = (int) $ref['id'];
}
}
if ($ids === []) {
return [];
}
$compositions = Composition::query()->with('editorialContentKind')->whereIn('id', $ids)->get()->keyBy('id');
$entries = [];
foreach (array_unique($ids) as $id) {
$composition = $compositions->get($id);
if ($composition === null || ! $this->isSelectable($composition)) {
continue;
}
$public = $this->isPublic($composition);
if (! $public && ! $includeNonPublic) {
continue;
}
$entries[] = new CatalogEntry(
id: $composition->id,
title: $this->title($composition),
summary: filled($composition->summary) ? (string) $composition->summary : null,
kindLabel: (string) ($composition->editorialContentKind?->label ?? ''),
url: $public ? route('public.program', $composition) : null,
public: $public,
);
}
return $entries;
}
private function title(Composition $composition): string
{
return (string) ($composition->display_title ?: $composition->designation);
}
private function optionLabel(Composition $composition): string
{
$visibility = $this->isPublic($composition) ? 'öffentlich sichtbar' : 'nur Redaktionsvorschau';
return $this->title($composition).' · '.($composition->editorialContentKind?->label ?? '').' · '.$visibility;
}
}
+25 -2
View File
@@ -2,35 +2,58 @@
namespace App\Domain\Cms;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class NavigationItem extends Model
{
public const PLACEMENTS = [
'header' => 'Kopfzeile',
'footer' => 'Fußzeile',
];
protected $fillable = [
'label',
'page_id',
'url',
'placement',
'sort_order',
'is_visible',
];
protected function casts(): array
{
return [
'is_visible' => 'boolean',
];
}
public function page(): BelongsTo
{
return $this->belongsTo(Page::class);
}
/**
* @param Builder<NavigationItem> $query
*/
public function scopeVisible(Builder $query): void
{
$query->where('is_visible', true);
}
public function href(): ?string
{
if ($this->page !== null) {
return $this->page->path === '/' ? url('/') : url($this->page->path);
}
if ($this->url === null || $this->url === '') {
if ($this->url === null || $this->url === '' || ! SafeUrl::isSafe($this->url)) {
return null;
}
if (str_starts_with($this->url, '/') && ! str_starts_with($this->url, '//')) {
if (str_starts_with($this->url, '/')) {
return url($this->url);
}
+1 -6
View File
@@ -48,17 +48,12 @@ public function publicUrl(): string
public function publicTitle(): string
{
$revision = $this->publishedRevision;
$heading = collect($revision?->blocks ?? [])->firstWhere('type', 'heading');
if (is_string($revision?->seo_title) && $revision->seo_title !== '') {
return $revision->seo_title;
}
if (is_array($heading) && is_string($heading['heading'] ?? null) && $heading['heading'] !== '') {
return $heading['heading'];
}
return $this->path;
return $revision?->contentTitle() ?? $this->path;
}
public function pillars(): BelongsToMany
+19
View File
@@ -2,6 +2,7 @@
namespace App\Domain\Cms;
use App\Domain\Cms\Widgets\WidgetRegistry;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -35,4 +36,22 @@ public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
/**
* Bausteine als aktuelle Widget-Hüllen. Die gespeicherten Daten bleiben unverändert.
*
* @return list<array<string, mixed>>
*/
public function widgets(): array
{
return app(WidgetRegistry::class)->read($this->blocks);
}
/**
* Titel aus dem ersten Überschriften- oder Einstiegs-Widget.
*/
public function contentTitle(): ?string
{
return app(WidgetRegistry::class)->pageTitle($this->blocks);
}
}
+52 -21
View File
@@ -2,36 +2,23 @@
namespace App\Domain\Cms;
use App\Domain\Cms\Blocks\BlockRegistry;
use App\Domain\Cms\Widgets\WidgetRegistry;
use App\Jobs\PublishPublicMedia;
use App\Models\User;
use Illuminate\Validation\ValidationException;
class PageService
{
public function __construct(private readonly BlockRegistry $blocks) {}
public function __construct(private readonly WidgetRegistry $widgets) {}
/**
* @param list<array<string, mixed>> $blocks
* Speichert einen Entwurf als neue Revision. Veröffentlicht nichts.
*
* @param array<int|string, mixed> $blocks Bausteine im Altformat oder als Widget-Hülle
*/
public function saveRevision(Page $page, array $blocks, ?string $seoTitle, ?string $seoDescription, ?User $author): PageRevision
{
$normalized = $this->blocks->normalize($blocks);
$revision = $page->revisions()->create([
'blocks' => $normalized,
'seo_title' => $seoTitle !== null && $seoTitle !== '' ? $seoTitle : null,
'seo_description' => $seoDescription !== null && $seoDescription !== '' ? $seoDescription : null,
'created_by' => $author?->id,
]);
foreach ($normalized as $block) {
if (($block['type'] ?? null) === 'image_text' && filled($block['image'] ?? null)) {
PublishPublicMedia::dispatch($block['image']);
}
}
return $revision;
return $this->storeRevision($page, $this->widgets->normalize($blocks), $seoTitle, $seoDescription, $author);
}
public function publish(Page $page, PageRevision $revision): void
@@ -46,6 +33,10 @@ public function publish(Page $page, PageRevision $revision): void
$page->save();
}
/**
* Legt den Stand einer früheren Revision unverändert als neue Revision an. Die gespeicherten Bausteine
* werden nicht umgeschrieben; ältere Formate werden erst beim Lesen angehoben.
*/
public function restore(Page $page, PageRevision $source, ?User $author): PageRevision
{
if ($source->page_id !== $page->id) {
@@ -54,15 +45,36 @@ public function restore(Page $page, PageRevision $source, ?User $author): PageRe
]);
}
return $this->saveRevision(
return $this->storeRevision(
$page,
$source->blocks,
$source->blocks ?? [],
$source->seo_title,
$source->seo_description,
$author,
);
}
/**
* Normalisiert den Pfad und prüft, dass keine andere Seite ihn verwendet.
*/
public function availablePath(string $path, ?Page $except = null): string
{
$path = $this->normalizePath($path);
$taken = Page::query()
->where('path', $path)
->when($except !== null, fn ($query) => $query->whereKeyNot($except->getKey()))
->exists();
if ($taken) {
throw ValidationException::withMessages([
'path' => 'Diesen Pfad verwendet bereits eine andere Seite.',
]);
}
return $path;
}
public function normalizePath(string $path): string
{
$path = '/'.trim($path, '/');
@@ -81,4 +93,23 @@ public function normalizePath(string $path): string
return $path;
}
/**
* @param array<int|string, mixed> $blocks
*/
private function storeRevision(Page $page, array $blocks, ?string $seoTitle, ?string $seoDescription, ?User $author): PageRevision
{
$revision = $page->revisions()->create([
'blocks' => array_values($blocks),
'seo_title' => $seoTitle !== null && $seoTitle !== '' ? $seoTitle : null,
'seo_description' => $seoDescription !== null && $seoDescription !== '' ? $seoDescription : null,
'created_by' => $author?->id,
]);
foreach ($this->widgets->mediaPaths($revision->blocks) as $path) {
PublishPublicMedia::dispatch($path);
}
return $revision;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Domain\Cms;
/**
* Seitenvorlagen der öffentlichen Website. Eine Vorlage ordnet die gerenderten Widgets im Inhaltsbereich
* des gemeinsamen Layouts an. Derzeit gibt es nur „standard“; weitere Vorlagen (zum Beispiel für
* Themen- oder Landingpages) werden in config/cms.php ergänzt und später über einen Seitentyp gewählt.
*/
class PageTemplates
{
public const DEFAULT = 'standard';
/**
* @return array<string, string>
*/
public function all(): array
{
return config('cms.templates', [self::DEFAULT => 'site.templates.standard']);
}
public function viewFor(Page $page): string
{
$templates = $this->all();
return $templates[self::DEFAULT];
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Domain\Cms\Widgets;
/**
* Darstellungsrahmen. In der Vorschau zeigen Widgets zusätzlich redaktionelle Hinweise,
* zum Beispiel auf Verweise, die öffentlich nicht erscheinen.
*/
final readonly class RenderContext
{
public function __construct(public bool $preview = false) {}
public static function publicPage(): self
{
return new self(preview: false);
}
public static function preview(): self
{
return new self(preview: true);
}
}
@@ -0,0 +1,73 @@
<?php
namespace App\Domain\Cms\Widgets\Support;
use App\Domain\Cms\Widgets\WidgetErrors;
use Filament\Forms\Components\Field;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Select;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
/**
* Gemeinsame Bildauswahl für Widgets: vorhandenes Bild aus dem öffentlichen Website-Bereich wählen
* oder ein neues hochladen. Keine eigene Medienverwaltung.
*/
final class ImageRefFields
{
/**
* @return list<Field>
*/
public static function fields(string $label = 'Bild'): array
{
return [
Select::make('image')
->label($label.': vorhandenes Bild')
->options(fn (): array => PublicMedia::imageOptions())
->searchable()
->placeholder('Kein Bild')
->helperText('Auswahl aus den Bildern, die bereits für die Website hochgeladen wurden.'),
FileUpload::make('_upload')
->label($label.': neu hochladen')
->disk('cms_incoming')
->directory('cms')
->image()
->maxSize(8192)
->acceptedFileTypes(['image/jpeg', 'image/png', 'image/webp'])
->getUploadedFileNameForStorageUsing(fn (TemporaryUploadedFile $file): string => Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)).'-'.Str::lower(Str::random(6)).'.'.$file->guessExtension())
->helperText('Ein neues Bild ersetzt die Auswahl oben. Es wird beim Speichern im öffentlichen Bereich der Website abgelegt.'),
];
}
/**
* @return array<string, mixed>
*/
public static function rules(): array
{
return [
'image' => ['nullable', 'string', 'max:255'],
'_upload' => ['nullable'],
];
}
/**
* Übernimmt einen neuen Upload als Bild und prüft, dass das Bild im öffentlichen Bereich liegt.
*
* @param array<string, mixed> $refs
* @return array<string, mixed>
*/
public static function clean(array $refs, WidgetErrors $errors, string $key = 'image', ?string $errorKey = null): array
{
$upload = PublicMedia::fromUploadState($refs['_upload'] ?? null);
$image = $upload ?? PublicMedia::fromUploadState($refs[$key] ?? null);
if ($image !== null && ! PublicMedia::isPublicPath($image)) {
$errors->add($errorKey ?? "refs.$key", 'Das Bild liegt nicht im öffentlichen Medienbereich.');
}
$refs[$key] = $image;
unset($refs['_upload']);
return $refs;
}
}
@@ -0,0 +1,100 @@
<?php
namespace App\Domain\Cms\Widgets\Support;
use Illuminate\Support\Facades\Storage;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Throwable;
/**
* Öffentlicher Medienbereich der Website ("cms/"). Nur Dateien aus diesem Bereich dürfen in Widgets
* verwendet werden. Geschützte Bibliotheksmedien (Inhaltsdateien, Vorschaubilder) sind hier nie wählbar.
*/
final class PublicMedia
{
public const PREFIX = 'cms/';
private const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'avif'];
public static function isPublicPath(mixed $path): bool
{
return is_string($path)
&& str_starts_with($path, self::PREFIX)
&& ! str_contains($path, '..')
&& preg_match('#^cms/[A-Za-z0-9._\-/]+$#', $path) === 1;
}
public static function url(string $path): string
{
return route('media.public', ['path' => $path]);
}
/**
* Bereits vorhandene Bilder im öffentlichen Bereich (veröffentlicht oder zur Veröffentlichung vorgemerkt).
*
* @return array<string, string>
*/
public static function imageOptions(): array
{
$options = [];
foreach (['media_public', 'cms_incoming'] as $disk) {
try {
$files = Storage::disk($disk)->allFiles(rtrim(self::PREFIX, '/'));
} catch (Throwable) {
$files = [];
}
foreach ($files as $file) {
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (self::isPublicPath($file) && in_array($extension, self::IMAGE_EXTENSIONS, true)) {
$options[$file] = substr($file, strlen(self::PREFIX));
}
}
}
ksort($options);
return $options;
}
/**
* Pfad aus dem Zustand eines Upload-Felds (Zeichenkette oder Liste).
*/
public static function fromUploadState(mixed $state): ?string
{
if (is_array($state)) {
$state = array_values($state)[0] ?? null;
}
return is_string($state) && $state !== '' ? $state : null;
}
/**
* Bildadresse für Darstellung und Blockvorschau. In der Vorschau kann ein noch nicht gespeicherter Upload vorliegen.
*
* @param array<string, mixed> $refs
*/
public static function imageUrl(array $refs, string $key = 'image'): ?string
{
$upload = $refs['_upload'] ?? null;
$upload = is_array($upload) ? (array_values($upload)[0] ?? null) : $upload;
if ($upload instanceof TemporaryUploadedFile) {
try {
return $upload->temporaryUrl();
} catch (Throwable) {
return null;
}
}
if (self::isPublicPath($upload)) {
return self::url($upload);
}
$path = $refs[$key] ?? null;
return self::isPublicPath($path) ? self::url($path) : null;
}
}
@@ -0,0 +1,79 @@
<?php
namespace App\Domain\Cms\Widgets\Support;
use Symfony\Component\HtmlSanitizer\HtmlSanitizer;
use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig;
/**
* Formatierter Text in Widgets: feste Auswahl an Auszeichnungen, kein freies HTML, keine Skripte.
* Bereinigt wird beim Speichern und erneut bei der Darstellung.
*/
final class RichText
{
/** Werkzeugleiste des Editors; muss zur Erlaubnisliste unten passen. */
public const TOOLBAR = [['bold', 'italic', 'link'], ['bulletList', 'orderedList'], ['undo', 'redo']];
private static ?HtmlSanitizer $sanitizer = null;
public static function sanitize(?string $html): string
{
if ($html === null || trim($html) === '') {
return '';
}
return trim(self::sanitizer()->sanitize($html));
}
/**
* Übernimmt Klartext aus dem Altbestand: Absätze an Leerzeilen, Zeichen maskiert.
*/
public static function fromPlainText(?string $text): string
{
$text = trim((string) $text);
if ($text === '') {
return '';
}
$paragraphs = preg_split("/\n\s*\n/", $text) ?: [];
return implode('', array_map(
fn (string $paragraph): string => '<p>'.e(trim($paragraph)).'</p>',
$paragraphs,
));
}
public static function isBlank(?string $html): bool
{
return trim(html_entity_decode(strip_tags((string) $html), ENT_QUOTES | ENT_HTML5, 'UTF-8')) === '';
}
public static function excerpt(?string $html, int $length = 80): string
{
$text = trim(preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags(str_replace('<', ' <', (string) $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8')) ?? '');
return mb_strlen($text) > $length ? rtrim(mb_substr($text, 0, $length - 1)).'…' : $text;
}
private static function sanitizer(): HtmlSanitizer
{
return self::$sanitizer ??= new HtmlSanitizer(
(new HtmlSanitizerConfig)
->allowElement('p')
->allowElement('br')
->allowElement('strong')
->allowElement('b')
->allowElement('em')
->allowElement('i')
->allowElement('ul')
->allowElement('ol')
->allowElement('li')
->allowElement('a', ['href'])
->allowLinkSchemes(['http', 'https', 'mailto'])
->allowRelativeLinks()
->forceAttribute('a', 'rel', 'noopener')
->withMaxInputLength(40000),
);
}
}
@@ -0,0 +1,44 @@
<?php
namespace App\Domain\Cms\Widgets\Support;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
/**
* Zulässige Linkziele in redaktionellen Inhalten: Seitenpfade ("/...") oder http(s)-Adressen.
*/
final class SafeUrl implements ValidationRule
{
public static function isSafe(mixed $url): bool
{
if (! is_string($url) || $url === '' || preg_match('/[\s\x00-\x1F\x7F]/', $url) === 1) {
return false;
}
$isRelative = str_starts_with($url, '/') && ! str_starts_with($url, '//') && ! str_starts_with($url, '/\\');
$isAbsolute = preg_match('#^https?://[^/\s]+#i', $url) === 1;
return $isRelative || $isAbsolute;
}
public static function message(): string
{
return 'Erlaubt sind Seitenpfade (beginnend mit /) oder http(s)-Adressen.';
}
/**
* Prüfregel für Formularfelder.
*/
public static function rule(): self
{
return new self;
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if ($value !== null && $value !== '' && ! self::isSafe($value)) {
$fail(self::message());
}
}
}
@@ -0,0 +1,76 @@
<?php
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
class CallToActionWidget extends WidgetType
{
public function key(): string
{
return 'call_to_action';
}
public function label(): string
{
return 'Handlungsaufruf';
}
public function description(): string
{
return 'Hervorgehobene Fläche mit Überschrift, Text und einer Schaltfläche.';
}
public function icon(): string
{
return 'heroicon-o-megaphone';
}
public function schematic(): array
{
return [[2, 4, 56, 28, 'ink'], [8, 9, 30, 4, 'line'], [8, 16, 40, 3, 'line'], [8, 23, 16, 5, 'accent']];
}
public function dataRules(): array
{
return [
'heading' => ['required', 'string', 'max:200'],
'text' => ['nullable', 'string', 'max:1000'],
'label' => ['required', 'string', 'max:80'],
'url' => ['required', 'string', 'max:500'],
];
}
public function dataFields(): array
{
return [
TextInput::make('heading')->label('Überschrift')->required()->maxLength(200),
Textarea::make('text')->label('Text')->rows(3)->maxLength(1000),
TextInput::make('label')->label('Beschriftung der Schaltfläche')->required()->maxLength(80),
TextInput::make('url')
->label('Linkziel')
->required()
->maxLength(500)
->rule(SafeUrl::rule())
->helperText('Seitenpfad wie /angebote oder eine vollständige http(s)-Adresse.'),
];
}
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
if (! SafeUrl::isSafe($data['url'] ?? null)) {
$errors->add('data.url', SafeUrl::message());
}
return [$data, $refs];
}
public function summary(array $widget): string
{
return trim(($widget['data']['heading'] ?? '').' → '.($widget['data']['label'] ?? ''));
}
}
@@ -0,0 +1,155 @@
<?php
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\ImageRefFields;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
/**
* Redaktionelle Karten. Die Einträge sind freie redaktionelle Verweise, keine Produkte oder Lizenzartikel.
*
* Version 1 umfasst den Bestand (Titel, Text, Adresse). Das optionale Bild je Karte ist eine
* abwärtskompatible Ergänzung derselben Version: ältere Karten haben schlicht kein Bild.
*/
class CardsWidget extends WidgetType
{
public function key(): string
{
return 'cards';
}
public function label(): string
{
return 'Redaktionelle Karten';
}
public function description(): string
{
return 'Mehrere Karten mit Titel, Text, Linkziel und optionalem Bild. Als Raster oder kompakte Liste.';
}
public function icon(): string
{
return 'heroicon-o-squares-2x2';
}
public function schematic(): array
{
return [[2, 6, 17, 24, 'line'], [21, 6, 17, 24, 'line'], [40, 6, 17, 24, 'line'], [2, 6, 17, 2, 'accent'], [21, 6, 17, 2, 'accent'], [40, 6, 17, 2, 'accent']];
}
public function variants(): array
{
return [
'standard' => 'Raster',
'compact' => 'Kompakte Liste',
];
}
public function dataRules(): array
{
return [
'items' => ['required', 'array', 'min:1', 'max:12'],
'items.*.title' => ['required', 'string', 'max:120'],
'items.*.text' => ['nullable', 'string', 'max:500'],
'items.*.url' => ['nullable', 'string', 'max:500'],
'items.*.image' => ['nullable', 'string', 'max:255'],
'items.*._upload' => ['nullable'],
];
}
public function dataFields(): array
{
[$image, $upload] = ImageRefFields::fields('Bild (optional)');
return [
Repeater::make('items')
->label('Karten')
->schema([
TextInput::make('title')->label('Titel')->required()->maxLength(120),
Textarea::make('text')->label('Beschreibung')->rows(2)->maxLength(500),
TextInput::make('url')
->label('Linkziel')
->maxLength(500)
->rule(SafeUrl::rule())
->helperText('Seitenpfad wie /praevention oder eine http(s)-Adresse. Leer lassen für eine Karte ohne Link.'),
$image,
$upload,
])
->minItems(1)
->maxItems(12)
->reorderableWithButtons()
->collapsible()
->cloneable()
->itemLabel(fn (array $state): ?string => $state['title'] ?? null)
->addActionLabel('Karte hinzufügen'),
];
}
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
foreach ($data['items'] as $index => $item) {
if (filled($item['url'] ?? null) && ! SafeUrl::isSafe($item['url'])) {
$errors->add("data.items.$index.url", SafeUrl::message());
}
$itemRefs = ImageRefFields::clean(['image' => $item['image'] ?? null, '_upload' => $item['_upload'] ?? null], $errors, errorKey: "data.items.$index.image");
$data['items'][$index] = [
'title' => $item['title'],
'text' => filled($item['text'] ?? null) ? $item['text'] : null,
'url' => filled($item['url'] ?? null) ? $item['url'] : null,
'image' => $itemRefs['image'],
];
}
return [$data, $refs];
}
public function resolve(array $widget, RenderContext $context): array
{
$items = [];
foreach ($widget['data']['items'] ?? [] as $item) {
if (! is_array($item) || ! filled($item['title'] ?? null)) {
continue;
}
$items[] = [
'title' => $item['title'],
'text' => $item['text'] ?? null,
'url' => SafeUrl::isSafe($item['url'] ?? null) ? $item['url'] : null,
'imageUrl' => PublicMedia::imageUrl($item),
];
}
return ['items' => $items];
}
public function mediaPaths(array $widget): array
{
$paths = [];
foreach ($widget['data']['items'] ?? [] as $item) {
if (is_array($item) && PublicMedia::isPublicPath($item['image'] ?? null)) {
$paths[] = $item['image'];
}
}
return $paths;
}
public function summary(array $widget): string
{
$titles = array_filter(array_map(fn ($item) => is_array($item) ? ($item['title'] ?? null) : null, $widget['data']['items'] ?? []));
return count($titles).' Karten: '.implode(', ', $titles);
}
}
@@ -0,0 +1,157 @@
<?php
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Catalog\Composition;
use App\Domain\Cms\Catalog\PublicCatalogReader;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
/**
* Kuratierte Programm- und Modulkarten.
*
* Gespeichert werden nur Verweise (refs.items: [{type: 'composition', id}]) und Darstellungswahl.
* Titel, Kurzbeschreibung und Inhaltsart kommen zur Laufzeit aus den Fachdaten (PublicCatalogReader).
* Eine Karte begründet keine Nutzungsberechtigung und ist kein Lizenzartikel.
*/
class CatalogCardsWidget extends WidgetType
{
public function key(): string
{
return 'catalog_cards';
}
public function label(): string
{
return 'Programm- und Modulkarten';
}
public function description(): string
{
return 'Ausgewählte Programme und Module; Titel und Beschreibung kommen automatisch aus den Fachdaten.';
}
public function icon(): string
{
return 'heroicon-o-rectangle-stack';
}
public function schematic(): array
{
return [[2, 4, 26, 28, 'line'], [32, 4, 26, 28, 'line'], [5, 7, 20, 9, 'image'], [35, 7, 20, 9, 'image'], [5, 19, 18, 3, 'ink'], [35, 19, 18, 3, 'ink'], [5, 25, 8, 3, 'accent'], [35, 25, 8, 3, 'accent']];
}
public function variants(): array
{
return [
'standard' => 'Karten mit Kurzbeschreibung',
'compact' => 'Kompakte Liste',
];
}
public function dataRules(): array
{
return [
'heading' => ['nullable', 'string', 'max:160'],
'intro' => ['nullable', 'string', 'max:400'],
];
}
public function refRules(): array
{
return [
'items' => ['required', 'array', 'min:1', 'max:12'],
'items.*.type' => ['required', 'string', 'in:composition'],
'items.*.id' => ['required', 'integer'],
];
}
public function dataFields(): array
{
return [
TextInput::make('heading')->label('Abschnittsüberschrift (optional)')->maxLength(160),
Textarea::make('intro')->label('Einleitung (optional)')->rows(2)->maxLength(400),
];
}
public function refFields(): array
{
return [
Repeater::make('items')
->label('Programme und Module')
->helperText('Nur zur Anzeige freigegebene Programme und Module sind wählbar. Öffentlich erscheinen derzeit nur Programme mit öffentlicher Programmseite; Module nur in der Redaktionsvorschau.')
->schema([
Hidden::make('type')->default('composition'),
Select::make('id')
->label('Programm oder Modul')
->required()
->live()
->searchable()
->getSearchResultsUsing(fn (?string $search): array => app(PublicCatalogReader::class)->search($search))
->getOptionLabelUsing(fn (mixed $value): ?string => app(PublicCatalogReader::class)->labelFor($value))
->options(fn (): array => app(PublicCatalogReader::class)->search(null, 10)),
])
->minItems(1)
->maxItems(12)
->reorderableWithButtons()
->itemLabel(fn (array $state): ?string => filled($state['id'] ?? null) ? app(PublicCatalogReader::class)->labelFor($state['id']) : null)
->addActionLabel('Programm oder Modul hinzufügen'),
];
}
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
$reader = app(PublicCatalogReader::class);
$items = [];
$seen = [];
foreach ($refs['items'] as $index => $item) {
$id = (int) $item['id'];
$composition = Composition::query()->with('editorialContentKind')->find($id);
if ($composition === null || ! $reader->isSelectable($composition)) {
$errors->add("refs.items.$index.id", 'Dieses Objekt ist kein zur Anzeige freigegebenes Programm oder Modul.');
continue;
}
if (isset($seen[$id])) {
continue;
}
$seen[$id] = true;
$items[] = ['type' => 'composition', 'id' => $id];
}
$refs['items'] = $items;
foreach (['heading', 'intro'] as $key) {
$data[$key] = filled($data[$key] ?? null) ? trim($data[$key]) : null;
}
return [$data, $refs];
}
public function resolve(array $widget, RenderContext $context): array
{
$refs = is_array($widget['refs']['items'] ?? null) ? array_values($widget['refs']['items']) : [];
return [
'entries' => app(PublicCatalogReader::class)->entries($refs, includeNonPublic: $context->preview),
];
}
public function summary(array $widget): string
{
$count = count($widget['refs']['items'] ?? []);
$heading = $widget['data']['heading'] ?? null;
return trim(($heading ? $heading.' · ' : '').($count === 1 ? '1 Verweis' : $count.' Verweise'));
}
}
@@ -0,0 +1,70 @@
<?php
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
class FaqWidget extends WidgetType
{
public function key(): string
{
return 'faq';
}
public function label(): string
{
return 'FAQ';
}
public function description(): string
{
return 'Häufige Fragen mit Antworten.';
}
public function icon(): string
{
return 'heroicon-o-question-mark-circle';
}
public function schematic(): array
{
return [[4, 5, 34, 3, 'ink'], [4, 10, 50, 3, 'line'], [4, 17, 30, 3, 'ink'], [4, 22, 46, 3, 'line'], [4, 29, 38, 3, 'ink']];
}
public function dataRules(): array
{
return [
'items' => ['required', 'array', 'min:1', 'max:20'],
'items.*.question' => ['required', 'string', 'max:300'],
'items.*.answer' => ['required', 'string', 'max:2000'],
];
}
public function dataFields(): array
{
return [
Repeater::make('items')
->label('Fragen')
->schema([
TextInput::make('question')->label('Frage')->required()->maxLength(300),
Textarea::make('answer')->label('Antwort')->rows(3)->required()->maxLength(2000),
])
->minItems(1)
->maxItems(20)
->reorderableWithButtons()
->collapsible()
->itemLabel(fn (array $state): ?string => $state['question'] ?? null)
->addActionLabel('Frage hinzufügen'),
];
}
public function summary(array $widget): string
{
$count = count($widget['data']['items'] ?? []);
return $count === 1 ? '1 Frage' : $count.' Fragen';
}
}
@@ -0,0 +1,61 @@
<?php
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
class HeadingWidget extends WidgetType
{
public function key(): string
{
return 'heading';
}
public function label(): string
{
return 'Überschrift und Einleitung';
}
public function description(): string
{
return 'Abschnittsüberschrift mit kurzem Einleitungstext.';
}
public function icon(): string
{
return 'heroicon-o-h1';
}
public function schematic(): array
{
return [[4, 8, 40, 6, 'ink'], [4, 19, 50, 3, 'line'], [4, 25, 36, 3, 'line']];
}
public function dataRules(): array
{
return [
'heading' => ['required', 'string', 'max:200'],
'intro' => ['nullable', 'string', 'max:1000'],
];
}
public function dataFields(): array
{
return [
TextInput::make('heading')->label('Überschrift')->required()->maxLength(200),
Textarea::make('intro')->label('Einleitung')->rows(3)->maxLength(1000),
];
}
public function summary(array $widget): string
{
return (string) ($widget['data']['heading'] ?? '');
}
public function pageTitle(array $widget): ?string
{
return $widget['data']['heading'] ?? null;
}
}
+149
View File
@@ -0,0 +1,149 @@
<?php
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\ImageRefFields;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Group;
class HeroWidget extends WidgetType
{
public function key(): string
{
return 'hero';
}
public function label(): string
{
return 'Einstieg (Hero)';
}
public function description(): string
{
return 'Großer Seiteneinstieg mit Überschrift, Beschreibung, optionalem Bild und optionaler Schaltfläche.';
}
public function icon(): string
{
return 'heroicon-o-sparkles';
}
public function schematic(): array
{
return [[2, 3, 56, 30, 'line'], [6, 8, 26, 6, 'ink'], [6, 17, 24, 3, 'line'], [6, 24, 12, 5, 'accent'], [36, 7, 18, 22, 'image']];
}
public function variants(): array
{
return [
'standard' => 'Standard (Bild neben dem Text)',
'highlight' => 'Hervorgehoben (Markenfläche)',
];
}
public function dataRules(): array
{
return [
'heading' => ['required', 'string', 'max:200'],
'text' => ['nullable', 'string', 'max:600'],
'cta_label' => ['nullable', 'string', 'max:80', 'required_with:data.cta_url'],
'cta_url' => ['nullable', 'string', 'max:500', 'required_with:data.cta_label'],
'alt' => ['nullable', 'string', 'max:300'],
];
}
public function refRules(): array
{
return ImageRefFields::rules();
}
public function dataFields(): array
{
return [
TextInput::make('heading')->label('Überschrift')->required()->maxLength(200),
Textarea::make('text')->label('Beschreibung')->rows(3)->maxLength(600),
Grid::make(2)->schema([
TextInput::make('cta_label')->label('Schaltfläche: Beschriftung (optional)')->maxLength(80),
TextInput::make('cta_url')
->label('Schaltfläche: Linkziel')
->maxLength(500)
->rule(SafeUrl::rule())
->requiredWith('cta_label'),
]),
TextInput::make('alt')
->label('Alternativtext des Bildes')
->maxLength(300)
->helperText('Pflicht, sobald ein Bild gewählt ist.'),
];
}
public function refFields(): array
{
return ImageRefFields::fields();
}
public function editorSchema(): array
{
[$heading, $text, $cta, $alt] = $this->dataFields();
return [
Group::make([$heading, $text, $cta])->statePath('data'),
Group::make($this->refFields())->statePath('refs'),
Group::make([$alt])->statePath('data'),
];
}
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
$refs = ImageRefFields::clean($refs, $errors);
foreach (['text', 'cta_label', 'cta_url', 'alt'] as $key) {
$data[$key] = filled($data[$key] ?? null) ? trim($data[$key]) : null;
}
if ($data['cta_url'] !== null && ! SafeUrl::isSafe($data['cta_url'])) {
$errors->add('data.cta_url', SafeUrl::message());
}
if ($refs['image'] !== null && $data['alt'] === null) {
$errors->add('data.alt', 'Bitte einen Alternativtext für das Bild angeben.');
}
return [$data, $refs];
}
public function resolve(array $widget, RenderContext $context): array
{
$data = $widget['data'];
$hasAction = filled($data['cta_label'] ?? null) && SafeUrl::isSafe($data['cta_url'] ?? null);
return [
'imageUrl' => PublicMedia::imageUrl($widget['refs']),
'action' => $hasAction ? ['label' => $data['cta_label'], 'url' => $data['cta_url']] : null,
];
}
public function mediaPaths(array $widget): array
{
$image = $widget['refs']['image'] ?? null;
return PublicMedia::isPublicPath($image) ? [$image] : [];
}
public function summary(array $widget): string
{
return (string) ($widget['data']['heading'] ?? '');
}
public function pageTitle(array $widget): ?string
{
return $widget['data']['heading'] ?? null;
}
}
@@ -0,0 +1,165 @@
<?php
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\ImageRefFields;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\Support\RichText;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Group;
/**
* Bild und Text.
*
* Version 1 (Bestand): data {image, alt, body} mit Klartext.
* Version 2: data {title, body (formatierter Text), alt}, refs {image}, Varianten Bild links/rechts.
*/
class ImageTextWidget extends WidgetType
{
public function key(): string
{
return 'image_text';
}
public function label(): string
{
return 'Bild und Text';
}
public function description(): string
{
return 'Bild neben formatiertem Text; Bild links oder rechts, auf dem Smartphone untereinander.';
}
public function version(): int
{
return 2;
}
public function icon(): string
{
return 'heroicon-o-photo';
}
public function schematic(): array
{
return [[4, 6, 22, 24, 'image'], [30, 7, 24, 4, 'ink'], [30, 15, 26, 3, 'line'], [30, 21, 22, 3, 'line']];
}
public function variants(): array
{
return [
'image_left' => 'Bild links',
'image_right' => 'Bild rechts',
];
}
public function upgrade(array $widget, int $from): array
{
if ($from !== 1) {
return parent::upgrade($widget, $from);
}
$data = $widget['data'];
$widget['data'] = [
'title' => null,
'body' => RichText::fromPlainText(is_string($data['body'] ?? null) ? $data['body'] : ''),
'alt' => $data['alt'] ?? null,
];
$widget['refs'] = [
'image' => PublicMedia::fromUploadState($data['image'] ?? null),
];
return $widget;
}
public function dataRules(): array
{
return [
'title' => ['nullable', 'string', 'max:160'],
'body' => ['required', 'string', 'max:40000'],
'alt' => ['nullable', 'string', 'max:300'],
];
}
public function refRules(): array
{
return ImageRefFields::rules();
}
public function dataFields(): array
{
return [
TextInput::make('title')->label('Titel (optional)')->maxLength(160),
RichEditor::make('body')
->label('Text')
->required()
->toolbarButtons(RichText::TOOLBAR),
TextInput::make('alt')
->label('Alternativtext des Bildes')
->maxLength(300)
->helperText('Beschreibt, was auf dem Bild zu sehen ist. Pflicht, sobald ein Bild gewählt ist.'),
];
}
public function refFields(): array
{
return ImageRefFields::fields();
}
public function editorSchema(): array
{
[$title, $body, $alt] = $this->dataFields();
return [
Group::make([$title, $body])->statePath('data'),
Group::make($this->refFields())->statePath('refs'),
Group::make([$alt])->statePath('data'),
];
}
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
$refs = ImageRefFields::clean($refs, $errors);
$data['body'] = RichText::sanitize($data['body'] ?? '');
$data['title'] = filled($data['title'] ?? null) ? trim($data['title']) : null;
$data['alt'] = filled($data['alt'] ?? null) ? trim($data['alt']) : null;
if (RichText::isBlank($data['body'])) {
$errors->add('data.body', 'Bitte einen Text eingeben.');
}
if ($refs['image'] !== null && $data['alt'] === null) {
$errors->add('data.alt', 'Bitte einen Alternativtext für das Bild angeben.');
}
return [$data, $refs];
}
public function resolve(array $widget, RenderContext $context): array
{
return [
'imageUrl' => PublicMedia::imageUrl($widget['refs']),
'body' => RichText::sanitize(is_string($widget['data']['body'] ?? null) ? $widget['data']['body'] : ''),
];
}
public function mediaPaths(array $widget): array
{
$image = $widget['refs']['image'] ?? null;
return PublicMedia::isPublicPath($image) ? [$image] : [];
}
public function summary(array $widget): string
{
$title = $widget['data']['title'] ?? null;
return filled($title) ? (string) $title : RichText::excerpt($widget['data']['body'] ?? '');
}
}
@@ -0,0 +1,54 @@
<?php
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Cms\Widgets\Support\RichText;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Textarea;
class ProseWidget extends WidgetType
{
public function key(): string
{
return 'prose';
}
public function label(): string
{
return 'Fließtext';
}
public function description(): string
{
return 'Längerer Text in Absätzen. Eine Leerzeile beginnt einen neuen Absatz.';
}
public function icon(): string
{
return 'heroicon-o-bars-3-bottom-left';
}
public function dataRules(): array
{
return [
'body' => ['required', 'string', 'max:20000'],
];
}
public function dataFields(): array
{
return [
Textarea::make('body')
->label('Text')
->rows(10)
->required()
->maxLength(20000)
->helperText('Eine Leerzeile beginnt einen neuen Absatz.'),
];
}
public function summary(array $widget): string
{
return RichText::excerpt(e((string) ($widget['data']['body'] ?? '')));
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Domain\Cms\Widgets;
/**
* Sammelt Prüfmeldungen einer Widget-Instanz mit Schlüsseln relativ zur Hülle (zum Beispiel 'data.url').
*/
class WidgetErrors
{
/** @var array<string, list<string>> */
private array $messages = [];
public function add(string $key, string $message): void
{
$this->messages[$key][] = $message;
}
public function isEmpty(): bool
{
return $this->messages === [];
}
/**
* @return array<string, list<string>>
*/
public function all(): array
{
return $this->messages;
}
}
+380
View File
@@ -0,0 +1,380 @@
<?php
namespace App\Domain\Cms\Widgets;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
/**
* Zentrales, codebasiertes Widget-Register (ADR-30).
*
* Lesepfad: upcast() hebt jeden gespeicherten Baustein (Altformat ohne Hülle oder Hülle älterer Version)
* auf die aktuelle Hülle an, ohne die gespeicherte Revision zu verändern.
* Schreibpfad: normalize() prüft und bereinigt Bausteine aus dem Editor und liefert Hüllen der aktuellen Version.
*/
class WidgetRegistry
{
/** @var array<string, WidgetType> */
private array $types = [];
/**
* @param iterable<WidgetType> $types
*/
public function __construct(iterable $types = [])
{
foreach ($types as $type) {
$this->register($type);
}
}
public function register(WidgetType $type): void
{
$key = $type->key();
if (preg_match('/^[a-z][a-z0-9_]{1,40}$/', $key) !== 1) {
throw new InvalidArgumentException("Ungültige Widget-Kennung „{$key}“.");
}
if (isset($this->types[$key])) {
throw new InvalidArgumentException("Die Widget-Kennung „{$key}“ ist bereits registriert.");
}
if ($type->version() < 1) {
throw new InvalidArgumentException("Widget „{$key}“ braucht eine Schemaversion ab 1.");
}
if ($type->variants() === []) {
throw new InvalidArgumentException("Widget „{$key}“ braucht mindestens eine Darstellungsvariante.");
}
foreach (array_keys($type->variants()) as $variant) {
if (preg_match('/^[a-z][a-z0-9_]*$/', (string) $variant) !== 1) {
throw new InvalidArgumentException("Widget „{$key}“ hat eine ungültige Variantenkennung.");
}
}
$this->types[$key] = $type;
}
public function has(mixed $key): bool
{
return is_string($key) && isset($this->types[$key]);
}
public function get(string $key): WidgetType
{
return $this->types[$key] ?? throw new InvalidArgumentException("Unbekannte Widget-Art „{$key}“.");
}
/**
* @return array<string, WidgetType>
*/
public function all(): array
{
return $this->types;
}
/**
* @return array<string, string>
*/
public function labels(): array
{
return array_map(fn (WidgetType $type): string => $type->label(), $this->types);
}
/**
* Hebt einen gespeicherten Baustein auf die aktuelle Hülle an. Unbekannte Arten liefern null.
*
* @param array<string, mixed> $block
* @return array{id: ?string, type: string, v: int, variant: string, settings: array<string, mixed>, data: array<string, mixed>, refs: array<string, mixed>}|null
*/
public function upcast(array $block): ?array
{
$key = $block['type'] ?? null;
if (! $this->has($key)) {
return null;
}
$type = $this->get($key);
if (array_key_exists('v', $block)) {
$widget = [
'id' => is_string($block['id'] ?? null) ? $block['id'] : null,
'type' => $key,
'v' => max(1, (int) $block['v']),
'variant' => is_string($block['variant'] ?? null) ? $block['variant'] : $type->defaultVariant(),
'settings' => is_array($block['settings'] ?? null) ? $block['settings'] : [],
'data' => is_array($block['data'] ?? null) ? $block['data'] : [],
'refs' => is_array($block['refs'] ?? null) ? $block['refs'] : [],
];
} else {
$legacy = $type->fromLegacy($block);
$widget = [
'id' => null,
'type' => $key,
'v' => 1,
'variant' => $legacy['variant'] ?? $type->defaultVariant(),
'settings' => [],
'data' => $legacy['data'],
'refs' => $legacy['refs'],
];
}
while ($widget['v'] < $type->version()) {
$from = $widget['v'];
$widget = $type->upgrade($widget, $from);
$widget['v'] = $from + 1;
}
if (! array_key_exists($widget['variant'], $type->variants())) {
$widget['variant'] = $type->defaultVariant();
}
return $widget;
}
/**
* Prüft und bereinigt Bausteine für eine neue Revision.
*
* @param array<int|string, mixed> $blocks
* @return list<array{id: string, type: string, v: int, variant: string, settings: array<string, mixed>, data: array<string, mixed>, refs: array<string, mixed>}>
*/
public function normalize(array $blocks): array
{
$normalized = [];
$seenIds = [];
foreach (array_values($blocks) as $index => $block) {
if (! is_array($block)) {
throw ValidationException::withMessages([
"blocks.$index" => 'Ein Baustein ist unvollständig.',
]);
}
if (! $this->has($block['type'] ?? null)) {
throw ValidationException::withMessages([
"blocks.$index.type" => 'Dieser Bausteintyp ist nicht freigegeben.',
]);
}
$type = $this->get($block['type']);
if (array_key_exists('v', $block) && (int) $block['v'] > $type->version()) {
throw ValidationException::withMessages([
"blocks.$index.v" => 'Dieser Baustein stammt aus einer neueren Programmfassung und kann hier nicht gespeichert werden.',
]);
}
$requested = $block['variant'] ?? null;
$isCurrent = array_key_exists('v', $block) && (int) $block['v'] === $type->version();
if ($isCurrent && is_string($requested) && $requested !== '' && ! array_key_exists($requested, $type->variants())) {
throw ValidationException::withMessages([
"blocks.$index.variant" => 'Diese Darstellungsvariante ist für den Baustein nicht freigegeben.',
]);
}
$widget = $this->upcast($block);
$normalized[] = $this->validateOne($type, $widget, $index, $seenIds);
}
return $normalized;
}
/**
* Gespeicherte Bausteine einer Revision als aktuelle Hüllen; unbekannte Arten entfallen.
*
* @param array<int|string, mixed>|null $blocks
* @return list<array<string, mixed>>
*/
public function read(?array $blocks): array
{
$widgets = [];
foreach (array_values($blocks ?? []) as $block) {
if (is_array($block) && ($widget = $this->upcast($block)) !== null) {
$widgets[] = $widget;
}
}
return $widgets;
}
/**
* @param array<int|string, mixed>|null $blocks
*/
public function pageTitle(?array $blocks): ?string
{
foreach ($this->read($blocks) as $widget) {
$title = $this->get($widget['type'])->pageTitle($widget);
if (is_string($title) && trim($title) !== '') {
return $title;
}
}
return null;
}
/**
* @param array<int|string, mixed>|null $blocks
* @return list<string>
*/
public function mediaPaths(?array $blocks): array
{
$paths = [];
foreach ($this->read($blocks) as $widget) {
foreach ($this->get($widget['type'])->mediaPaths($widget) as $path) {
$paths[] = $path;
}
}
return array_values(array_unique($paths));
}
/**
* @param array<string, mixed> $widget
* @param array<string, true> $seenIds
* @return array{id: string, type: string, v: int, variant: string, settings: array<string, mixed>, data: array<string, mixed>, refs: array<string, mixed>}
*/
private function validateOne(WidgetType $type, array $widget, int $index, array &$seenIds): array
{
$errors = new WidgetErrors;
$variant = $widget['variant'];
if (! array_key_exists($variant, $type->variants())) {
$errors->add('variant', 'Diese Darstellungsvariante ist für den Baustein nicht freigegeben.');
}
$settings = [];
$allowedSettings = $type->settings();
foreach ($widget['settings'] as $key => $value) {
if ($value === null || $value === '') {
continue;
}
if (! isset($allowedSettings[$key]) || ! is_string($value) || ! array_key_exists($value, $allowedSettings[$key])) {
$errors->add("settings.$key", 'Diese Einstellung ist für den Baustein nicht freigegeben.');
continue;
}
$settings[$key] = $value;
}
$rules = [];
foreach ($type->dataRules() as $key => $rule) {
$rules["data.$key"] = $rule;
}
foreach ($type->refRules() as $key => $rule) {
$rules["refs.$key"] = $rule;
}
$validator = Validator::make(['data' => $widget['data'], 'refs' => $widget['refs']], $rules);
foreach ($validator->errors()->messages() as $key => $messages) {
foreach ($messages as $message) {
$errors->add($key, $message);
}
}
$data = $this->onlyDeclared($widget['data'], $type->dataRules());
$refs = $this->onlyDeclared($widget['refs'], $type->refRules());
if ($errors->isEmpty()) {
[$data, $refs] = $type->clean($data, $refs, $errors);
}
if (! $errors->isEmpty()) {
$messages = [];
foreach ($errors->all() as $key => $list) {
$messages["blocks.$index.$key"] = $list;
}
throw ValidationException::withMessages($messages);
}
$id = $widget['id'];
if (! is_string($id) || preg_match('/^[A-Za-z0-9-]{1,64}$/', $id) !== 1 || isset($seenIds[$id])) {
$id = (string) Str::uuid();
}
$seenIds[$id] = true;
return [
'id' => $id,
'type' => $type->key(),
'v' => $type->version(),
'variant' => $variant,
'settings' => $settings,
'data' => $this->withoutTransient($data),
'refs' => $this->withoutTransient($refs),
];
}
/**
* Behält nur Schlüssel, für die Prüfregeln bestehen; Listen ('items.*.feld') werden je Eintrag gefiltert.
*
* @param array<string, mixed> $values
* @param array<string, mixed> $rules
* @return array<string, mixed>
*/
private function onlyDeclared(array $values, array $rules): array
{
$top = [];
$nested = [];
foreach (array_keys($rules) as $key) {
if (preg_match('/^([a-z_]+)\.\*\.([a-z_]+)$/', (string) $key, $match) === 1) {
$nested[$match[1]][] = $match[2];
} elseif (! str_contains((string) $key, '.')) {
$top[] = (string) $key;
}
}
$clean = [];
foreach ($top as $key) {
$value = $values[$key] ?? null;
if (isset($nested[$key])) {
$items = [];
foreach (array_values(is_array($value) ? $value : []) as $item) {
if (! is_array($item)) {
continue;
}
$entry = [];
foreach ($nested[$key] as $field) {
$entry[$field] = $item[$field] ?? null;
}
$items[] = $entry;
}
$value = $items;
}
$clean[$key] = $value;
}
return $clean;
}
/**
* Felder mit führendem Unterstrich (zum Beispiel '_upload') sind reine Editorhilfen und werden nicht gespeichert.
*
* @param array<string, mixed> $values
* @return array<string, mixed>
*/
private function withoutTransient(array $values): array
{
foreach (array_keys($values) as $key) {
if (str_starts_with((string) $key, '_')) {
unset($values[$key]);
}
}
return $values;
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace App\Domain\Cms\Widgets;
use Illuminate\Support\HtmlString;
/**
* Einziger Darstellungsweg für Widgets: öffentliche Seite, ganzseitige Vorschau und Blockvorschau im Editor
* verwenden dieselbe Blade-Ansicht je Widget-Art.
*/
class WidgetRenderer
{
public function __construct(private readonly WidgetRegistry $registry) {}
/**
* @param array<int|string, mixed>|null $blocks gespeicherte Bausteine (Altformat oder Hülle)
*/
public function renderAll(?array $blocks, RenderContext $context): HtmlString
{
$html = '';
$position = 0;
foreach (array_values($blocks ?? []) as $block) {
if (! is_array($block)) {
continue;
}
$widget = $this->registry->upcast($block);
if ($widget === null) {
if ($context->preview) {
$html .= '<section class="block widget-unknown"><p class="preview-note">Unbekannter Baustein „'.e((string) ($block['type'] ?? '')).'“ wird öffentlich nicht angezeigt.</p></section>';
}
continue;
}
$rendered = $this->renderWidget($widget, $context, $position === 0);
if ($rendered !== '') {
$html .= $rendered;
$position++;
}
}
return new HtmlString($html);
}
/**
* Rendert eine Instanz samt Abschnittshülle. Liefert '' wenn das Widget nichts darzustellen hat.
*
* @param array<string, mixed> $widget aktuelle Hülle
*/
public function renderWidget(array $widget, RenderContext $context, bool $first = false): string
{
$type = $this->registry->get($widget['type']);
$inner = trim(view($type->view(), [
'widget' => $widget,
'data' => $widget['data'],
'refs' => $widget['refs'],
'variant' => $widget['variant'],
'settings' => $widget['settings'],
'first' => $first,
'context' => $context,
] + $type->resolve($widget, $context))->render());
if ($inner === '') {
return '';
}
$id = is_string($widget['id'] ?? null) ? ' id="abschnitt-'.e($widget['id']).'"' : '';
return '<section class="block widget widget-'.e(str_replace('_', '-', $widget['type'])).' widget-variant-'.e(str_replace('_', '-', $widget['variant'])).'"'.$id.'>'
.$inner
.'</section>';
}
}
+217
View File
@@ -0,0 +1,217 @@
<?php
namespace App\Domain\Cms\Widgets;
use Filament\Forms\Components\Field;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Group;
/**
* Vertrag einer Widget-Art (Website-CMS-Zielarchitektur 5.3, ADR-30).
*
* Eine Instanz wird als Hülle gespeichert:
* {id, type, v, variant, settings, data, refs}
*
* - data: redaktionelle Inhalte dieser Instanz
* - refs: Verweise auf Fachobjekte oder Medien, nur Kennungen
* - settings: Aufzählungswerte aus settings(), keine freien Werte
*
* Eine neue Widget-Art ist eine Unterklasse und ein Eintrag in config/cms.php.
* Der Seiteneditor und die Darstellung brauchen keine Sonderbehandlung.
*/
abstract class WidgetType
{
/** Stabile Typkennung; ändert sich nie, weil sie in Revisionen gespeichert ist. */
abstract public function key(): string;
abstract public function label(): string;
abstract public function description(): string;
/** Aktuelle Schemaversion. Ältere Instanzen werden beim Lesen über upgrade() angehoben. */
public function version(): int
{
return 1;
}
/** Heroicon-Name für Auswahl und Liste im Editor. */
public function icon(): string
{
return 'heroicon-o-square-3-stack-3d';
}
/**
* Symbolische Vorschau für die Widget-Auswahl: Liste von Flächen [x, y, b, h, ton] in einem 60×36-Raster.
* Ton: 'ink', 'accent', 'line', 'image'. Kein redaktioneller Inhalt.
*
* @return list<array{0: int, 1: int, 2: int, 3: int, 4: string}>
*/
public function schematic(): array
{
return [[4, 6, 52, 4, 'ink'], [4, 14, 40, 3, 'line'], [4, 20, 44, 3, 'line'], [4, 26, 30, 3, 'line']];
}
/**
* Freigegebene Darstellungsvarianten: Kennung => Bezeichnung. Die erste ist die Vorgabe.
*
* @return array<string, string>
*/
public function variants(): array
{
return ['standard' => 'Standard'];
}
public function defaultVariant(): string
{
return (string) array_key_first($this->variants());
}
/**
* Zulässige Einstellungen: Schlüssel => [Wert => Bezeichnung]. Keine freien CSS-Klassen.
*
* @return array<string, array<string, string>>
*/
public function settings(): array
{
return [];
}
/**
* Prüfregeln für data. Schlüssel relativ zu data (zum Beispiel 'heading', 'items.*.title').
*
* @return array<string, mixed>
*/
abstract public function dataRules(): array;
/**
* Prüfregeln für refs, relativ zu refs.
*
* @return array<string, mixed>
*/
public function refRules(): array
{
return [];
}
/**
* Formularfelder für data. Sie werden im Editor unter dem Zustandspfad 'data' eingehängt.
*
* @return list<Component|Field>
*/
abstract public function dataFields(): array;
/**
* Formularfelder für refs, eingehängt unter 'refs'.
*
* @return list<Component|Field>
*/
public function refFields(): array
{
return [];
}
/**
* Anordnung der Felder im Bearbeitungsdialog. Vorgabe: Inhalte, dann Verweise.
* Eine Art kann die Reihenfolge ändern, solange Felder unter 'data' beziehungsweise 'refs' bleiben.
*
* @return list<Component>
*/
public function editorSchema(): array
{
$schema = [];
if ($this->dataFields() !== []) {
$schema[] = Group::make($this->dataFields())->statePath('data');
}
if ($this->refFields() !== []) {
$schema[] = Group::make($this->refFields())->statePath('refs');
}
return $schema;
}
/** Blade-Ansicht. Sie dient öffentlicher Seite, ganzseitiger Vorschau und Blockvorschau gleichermaßen. */
public function view(): string
{
return 'widgets.'.$this->key();
}
/**
* Übersetzt einen Altbaustein ohne Hülle (Bestand vor der Registry) in data/refs/variant der Version 1.
*
* @param array<string, mixed> $legacy
* @return array{data: array<string, mixed>, refs: array<string, mixed>, variant?: string}
*/
public function fromLegacy(array $legacy): array
{
unset($legacy['type']);
return ['data' => $legacy, 'refs' => []];
}
/**
* Hebt eine Instanz von Version $from auf $from + 1. Alte Revisionen bleiben gespeichert, wie sie sind.
*
* @param array<string, mixed> $widget
* @return array<string, mixed>
*/
public function upgrade(array $widget, int $from): array
{
throw new \LogicException(sprintf('Widget %s kennt keinen Schritt von Version %d.', $this->key(), $from));
}
/**
* Bereinigt geprüfte Inhalte vor dem Speichern (Adressen, formatierter Text, Bildauswahl).
*
* @param array<string, mixed> $data
* @param array<string, mixed> $refs
* @return array{0: array<string, mixed>, 1: array<string, mixed>}
*/
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
return [$data, $refs];
}
/**
* Löst Verweise für die Darstellung auf und liefert zusätzliche Ansichtsvariablen.
*
* @param array<string, mixed> $widget
* @return array<string, mixed>
*/
public function resolve(array $widget, RenderContext $context): array
{
return [];
}
/**
* Öffentliche Medienpfade dieser Instanz (für Veröffentlichung und Verwendungsnachweis).
*
* @param array<string, mixed> $widget
* @return list<string>
*/
public function mediaPaths(array $widget): array
{
return [];
}
/**
* Kurze Inhaltszusammenfassung für die Abschnittsliste im Editor.
*
* @param array<string, mixed> $widget
*/
public function summary(array $widget): string
{
return '';
}
/**
* Titel, den eine Seite aus diesem Widget übernehmen kann, wenn kein SEO-Titel gesetzt ist.
*
* @param array<string, mixed> $widget
*/
public function pageTitle(array $widget): ?string
{
return null;
}
}
@@ -4,14 +4,22 @@
use App\Domain\Cms\NavigationItem;
use App\Domain\Cms\Page;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Filament\Resources\NavigationItems\Pages\ManageNavigationItems;
use Closure;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Grouping\Group;
use Filament\Tables\Table;
class NavigationItemResource extends Resource
@@ -28,13 +36,21 @@ public static function form(Schema $schema): Schema
{
return $schema->components([
TextInput::make('label')->label('Beschriftung')->required()->maxLength(80),
Select::make('placement')
->label('Platz')
->options(NavigationItem::PLACEMENTS)
->default('header')
->required(),
Select::make('page_id')
->label('Seite')
->label('Interne Seite')
->options(fn (): array => Page::query()->orderBy('path')->pluck('path', 'id')->all())
->searchable(),
->searchable()
->helperText('Bevorzugt: eine CMS-Seite wählen. Dann folgt der Link automatisch einer Pfadänderung.'),
TextInput::make('url')
->label('Adresse')
->label('Oder Adresse')
->maxLength(500)
->helperText('Nur wenn keine Seite gewählt ist: Pfad wie /anmelden oder eine vollständige http(s)-Adresse.')
->rule(SafeUrl::rule())
->rule(function (Get $get): Closure {
return function (string $attribute, mixed $value, Closure $fail) use ($get): void {
if (blank($get('page_id')) && blank($value)) {
@@ -42,14 +58,16 @@ public static function form(Schema $schema): Schema
}
};
}),
Select::make('placement')
->label('Platz')
->options([
'header' => 'Kopfzeile',
'footer' => 'Fußzeile',
])
Toggle::make('is_visible')
->label('Auf der Website anzeigen')
->default(true),
TextInput::make('sort_order')
->label('Reihenfolge')
->numeric()
->minValue(0)
->default(fn (): int => (int) NavigationItem::query()->max('sort_order') + 1)
->helperText('Kleinere Zahlen stehen weiter vorn. In der Liste lässt sich die Reihenfolge auch per Ziehen ändern.')
->required(),
TextInput::make('sort_order')->label('Reihenfolge')->numeric()->required()->default(0),
]);
}
@@ -57,13 +75,43 @@ public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('label')->label('Beschriftung'),
TextColumn::make('page.path')->label('Seite'),
TextColumn::make('url')->label('Adresse'),
TextColumn::make('placement')->label('Platz'),
TextColumn::make('sort_order')->label('Reihenfolge')->sortable(),
TextColumn::make('label')->label('Beschriftung')->searchable(),
TextColumn::make('target')
->label('Ziel')
->state(fn (NavigationItem $record): string => $record->page?->path ?? (string) $record->url),
IconColumn::make('is_visible')
->label('Sichtbar')
->boolean(),
TextColumn::make('sort_order')->label('Reihenfolge'),
])
->defaultSort('sort_order');
->defaultGroup(
Group::make('placement')
->label('Platz')
->getTitleFromRecordUsing(fn (NavigationItem $record): string => NavigationItem::PLACEMENTS[$record->placement] ?? $record->placement)
->orderQueryUsing(fn ($query, string $direction) => $query->orderByRaw("CASE placement WHEN 'header' THEN 0 ELSE 1 END"))
->collapsible(),
)
->paginated([50, 100])
->defaultPaginationPageOption(50)
->filters([
SelectFilter::make('placement')->label('Platz')->options(NavigationItem::PLACEMENTS),
])
->reorderable('sort_order')
->reorderRecordsTriggerAction(fn (Action $action, bool $isReordering): Action => $action
->button()
->label($isReordering ? 'Sortieren beenden' : 'Reihenfolge ändern'))
->defaultSort('sort_order')
->recordActions([
Action::make('toggleVisibility')
->label(fn (NavigationItem $record): string => $record->is_visible ? 'Ausblenden' : 'Einblenden')
->icon(fn (NavigationItem $record): string => $record->is_visible ? 'heroicon-o-eye-slash' : 'heroicon-o-eye')
->color('gray')
->authorize(fn (NavigationItem $record): bool => auth()->user()?->can('update', $record) ?? false)
->action(fn (NavigationItem $record) => $record->update(['is_visible' => ! $record->is_visible])),
EditAction::make(),
DeleteAction::make()
->modalDescription('Der Eintrag wird aus der Navigation entfernt. Die verlinkte Seite bleibt bestehen.'),
]);
}
public static function getPages(): array
+31 -73
View File
@@ -3,20 +3,17 @@
namespace App\Filament\Resources\Pages;
use App\Domain\Catalog\Pillar;
use App\Domain\Cms\Blocks\BlockRegistry;
use App\Domain\Cms\Page;
use App\Filament\Resources\Pages\Pages\CreatePage;
use App\Filament\Resources\Pages\Pages\EditPage;
use App\Filament\Resources\Pages\Pages\ListPages;
use App\Filament\Resources\Pages\RelationManagers\RevisionsRelationManager;
use App\Filament\Support\WidgetEditor;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
@@ -35,76 +32,37 @@ class PageResource extends Resource
public static function form(Schema $schema): Schema
{
$labels = app(BlockRegistry::class)->labels();
return $schema->components([
TextInput::make('path')
->label('Pfad')
->required()
->maxLength(255)
->helperText('Zum Beispiel / oder /praevention'),
TextInput::make('seo_title')
->label('SEO-Titel')
->maxLength(255),
Textarea::make('seo_description')
->label('SEO-Beschreibung')
->maxLength(500)
->columnSpanFull(),
CheckboxList::make('pillars')
->label('Fachliche Säulen')
->options(fn (): array => Pillar::query()->orderBy('name')->pluck('name', 'id')->all())
->helperText('Eine veröffentlichte Seite erscheint auf den gewählten Themenbereichen der Website. Eine Seite kann mehreren Säulen zugeordnet sein.')
->columns(1),
Repeater::make('blocks')
->label('Bausteine')
->schema([
Select::make('type')
->label('Typ')
->options($labels)
->required()
->live(),
TextInput::make('heading')
->label('Überschrift')
->visible(fn (Get $get): bool => in_array($get('type'), ['heading', 'call_to_action'], true)),
Textarea::make('intro')
->label('Einleitung')
->visible(fn (Get $get): bool => $get('type') === 'heading'),
Textarea::make('body')
->label('Text')
->visible(fn (Get $get): bool => in_array($get('type'), ['prose', 'image_text'], true))
->columnSpanFull(),
FileUpload::make('image')
->label('Bild')
->disk('cms_incoming')
->directory('cms')
->image()
->visible(fn (Get $get): bool => $get('type') === 'image_text'),
TextInput::make('alt')
->label('Alternativtext')
->visible(fn (Get $get): bool => $get('type') === 'image_text'),
Textarea::make('text')
->label('Text')
->visible(fn (Get $get): bool => $get('type') === 'call_to_action'),
TextInput::make('label')
->label('Beschriftung der Aktion')
->visible(fn (Get $get): bool => $get('type') === 'call_to_action'),
TextInput::make('url')
->label('Adresse')
->visible(fn (Get $get): bool => $get('type') === 'call_to_action'),
Repeater::make('items')
->label('Einträge')
->visible(fn (Get $get): bool => in_array($get('type'), ['cards', 'faq'], true))
->schema([
TextInput::make('title')->label('Titel')->visible(fn (Get $get): bool => $get('../../type') === 'cards'),
Textarea::make('text')->label('Text')->visible(fn (Get $get): bool => $get('../../type') === 'cards'),
TextInput::make('url')->label('Adresse')->visible(fn (Get $get): bool => $get('../../type') === 'cards'),
TextInput::make('question')->label('Frage')->visible(fn (Get $get): bool => $get('../../type') === 'faq'),
Textarea::make('answer')->label('Antwort')->visible(fn (Get $get): bool => $get('../../type') === 'faq'),
]),
])
Section::make('Seite und Suchmaschinen')
->description('Adresse, Titel für Suchmaschinen und Zuordnung zu Themenbereichen.')
->collapsible()
->columns(2)
->columnSpanFull()
->reorderable()
->collapsed(),
->schema([
TextInput::make('path')
->label('Pfad')
->required()
->maxLength(255)
->helperText('Zum Beispiel / oder /praevention'),
TextInput::make('seo_title')
->label('SEO-Titel')
->maxLength(255),
Textarea::make('seo_description')
->label('SEO-Beschreibung')
->maxLength(500)
->columnSpanFull(),
CheckboxList::make('pillars')
->label('Fachliche Säulen')
->options(fn (): array => Pillar::query()->orderBy('name')->pluck('name', 'id')->all())
->helperText('Eine veröffentlichte Seite erscheint auf den gewählten Themenbereichen der Website. Eine Seite kann mehreren Säulen zugeordnet sein.')
->columns(1),
]),
Section::make('Inhalt der Seite')
->description('Abschnitte hinzufügen, per Klick auf die Vorschau bearbeiten, mit den Pfeilen sortieren. Speichern legt einen Entwurf an; veröffentlicht wird erst über „Veröffentlichen“.')
->columnSpanFull()
->schema([
WidgetEditor::builder('blocks'),
]),
]);
}
@@ -5,31 +5,51 @@
use App\Domain\Cms\Page;
use App\Domain\Cms\PageService;
use App\Filament\Resources\Pages\PageResource;
use App\Filament\Support\WidgetEditor;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class CreatePage extends CreateRecord
{
protected static string $resource = PageResource::class;
protected static bool $canCreateAnother = false;
/**
* @param array<string, mixed> $data
*/
protected function handleRecordCreation(array $data): Model
{
$service = app(PageService::class);
$page = Page::query()->create([
'path' => $service->normalizePath($data['path']),
]);
$blocks = WidgetEditor::fromBuilderState($data['blocks'] ?? []);
$service->saveRevision(
$page,
$data['blocks'] ?? [],
$data['seo_title'] ?? null,
$data['seo_description'] ?? null,
auth()->user(),
);
try {
return DB::transaction(function () use ($service, $data, $blocks): Page {
$page = Page::query()->create([
'path' => $service->availablePath($data['path']),
]);
return $page;
$service->saveRevision(
$page,
$blocks,
$data['seo_title'] ?? null,
$data['seo_description'] ?? null,
auth()->user(),
);
return $page;
});
} catch (ValidationException $exception) {
throw ValidationException::withMessages(
WidgetEditor::mapErrors($exception->errors(), array_keys($this->data['blocks'] ?? [])),
);
}
}
protected function getRedirectUrl(): string
{
return static::getResource()::getUrl('edit', ['record' => $this->getRecord()]);
}
}
+42 -11
View File
@@ -6,9 +6,12 @@
use App\Domain\Cms\Page;
use App\Domain\Cms\PageService;
use App\Filament\Resources\Pages\PageResource;
use App\Filament\Support\WidgetEditor;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\ValidationException;
class EditPage extends EditRecord
{
@@ -19,27 +22,52 @@ protected function getHeaderActions(): array
return [
Action::make('preview')
->label('Vorschau')
->icon('heroicon-o-device-phone-mobile')
->color('gray')
->tooltip('Zuletzt gespeicherten Entwurf in Smartphone-, Tablet- und Desktopbreite ansehen')
->url(function (): string {
$revision = $this->record->latestRevision;
return $revision === null
? '#'
: route('pages.preview', $revision);
: route('pages.preview.devices', $revision);
})
->openUrlInNewTab(),
Action::make('publish')
->label('Veröffentlichen')
->icon('heroicon-o-globe-alt')
->requiresConfirmation()
->modalHeading('Zuletzt gespeicherten Entwurf veröffentlichen?')
->modalDescription(fn (): string => 'Veröffentlicht wird Revision Nr. '.($this->record->latestRevision?->id ?? '–').'. Noch nicht gespeicherte Änderungen werden nicht veröffentlicht.')
->visible(fn (): bool => auth()->user()?->can('publish', $this->record) ?? false)
->action(function (PageService $service): void {
$revision = $this->record->latestRevision;
abort_if($revision === null, 404);
$service->publish($this->record, $revision);
$this->record->refresh();
Notification::make()->title('Seite veröffentlicht')->success()->send();
}),
Action::make('open')
->label('Live-Seite')
->icon('heroicon-o-arrow-top-right-on-square')
->color('gray')
->visible(fn (): bool => $this->record->isPublished())
->url(fn (): string => $this->record->publicUrl())
->openUrlInNewTab(),
];
}
protected function getSaveFormAction(): Action
{
return parent::getSaveFormAction()->label('Entwurf speichern');
}
protected function getSavedNotificationTitle(): ?string
{
return 'Entwurf gespeichert. Die Live-Seite bleibt unverändert, bis Sie veröffentlichen.';
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
@@ -47,7 +75,7 @@ protected function getHeaderActions(): array
protected function mutateFormDataBeforeFill(array $data): array
{
$revision = $this->record->latestRevision ?? $this->record->publishedRevision;
$data['blocks'] = $revision?->blocks ?? [];
$data['blocks'] = WidgetEditor::toBuilderState($revision?->blocks);
$data['seo_title'] = $revision?->seo_title;
$data['seo_description'] = $revision?->seo_description;
$data['pillars'] = $this->record->pillars()->pluck('pillars.id')->all();
@@ -62,19 +90,22 @@ protected function handleRecordUpdate(Model $record, array $data): Model
{
/** @var Page $record */
$service = app(PageService::class);
$blocks = WidgetEditor::fromBuilderState($data['blocks'] ?? []);
try {
$path = $service->availablePath($data['path'], $record);
$service->saveRevision($record, $blocks, $data['seo_title'] ?? null, $data['seo_description'] ?? null, auth()->user());
} catch (ValidationException $exception) {
throw ValidationException::withMessages(
WidgetEditor::mapErrors($exception->errors(), array_keys($this->data['blocks'] ?? [])),
);
}
$record->update([
'path' => $service->normalizePath($data['path']),
'path' => $path,
]);
app(PillarService::class)->assignPages($record, array_map(intval(...), $data['pillars'] ?? []));
$service->saveRevision(
$record,
$data['blocks'] ?? [],
$data['seo_title'] ?? null,
$data['seo_description'] ?? null,
auth()->user(),
);
return $record;
}
}
@@ -4,7 +4,9 @@
use App\Domain\Cms\PageRevision;
use App\Domain\Cms\PageService;
use App\Filament\Resources\Pages\PageResource;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
@@ -22,11 +24,22 @@ public function table(Table $table): Table
TextColumn::make('id')->label('Nr.'),
TextColumn::make('created_at')->label('Gespeichert')->dateTime('d.m.Y H:i'),
TextColumn::make('author.name')->label('Von'),
TextColumn::make('sections')
->label('Abschnitte')
->state(fn (PageRevision $record): int => count($record->widgets())),
TextColumn::make('published')
->label('Live')
->badge()
->color(fn (string $state): string => $state === 'Ja' ? 'success' : 'gray')
->state(fn (PageRevision $record): string => $record->id === $this->getOwnerRecord()->published_revision_id ? 'Ja' : 'Nein'),
])
->recordActions([
Action::make('preview')
->label('Vorschau')
->icon('heroicon-o-eye')
->color('gray')
->url(fn (PageRevision $record): string => route('pages.preview.devices', $record))
->openUrlInNewTab(),
Action::make('publish')
->label('Veröffentlichen')
->requiresConfirmation()
@@ -34,13 +47,16 @@ public function table(Table $table): Table
->action(function (PageRevision $record, PageService $service): void {
$service->publish($this->getOwnerRecord(), $record);
$this->getOwnerRecord()->refresh();
Notification::make()->title('Revision '.$record->id.' ist jetzt live.')->success()->send();
}),
Action::make('restore')
->label('Wiederherstellen')
->requiresConfirmation()
->modalDescription('Es entsteht eine neue Revision. Die Live-Seite bleibt unverändert, bis sie veröffentlicht wird.')
->modalDescription('Es entsteht eine neue Revision mit diesem Stand. Die Live-Seite bleibt unverändert, bis sie veröffentlicht wird.')
->action(function (PageRevision $record, PageService $service): void {
$service->restore($this->getOwnerRecord(), $record, auth()->user());
$restored = $service->restore($this->getOwnerRecord(), $record, auth()->user());
Notification::make()->title('Als neue Revision '.$restored->id.' wiederhergestellt.')->success()->send();
$this->redirect(PageResource::getUrl('edit', ['record' => $this->getOwnerRecord()]));
}),
])
->defaultSort('id', 'desc');
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Filament\Support;
use Filament\Forms\Components\Builder\Block;
use Illuminate\Contracts\View\View;
/**
* Builder-Block, dessen Vorschau den gemeinsamen Widget-Renderer verwendet.
*/
class WidgetBlock extends Block
{
/**
* @param array<string, mixed> $data
*/
public function renderPreview(array $data): View
{
return view('filament.cms.widget-preview', [
'html' => WidgetEditor::renderPreview($this->getName(), $data),
'stylesheets' => WidgetEditor::previewStylesheets(),
]);
}
}
+328
View File
@@ -0,0 +1,328 @@
<?php
namespace App\Filament\Support;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\WidgetRegistry;
use App\Domain\Cms\Widgets\WidgetRenderer;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\Builder\Block;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\RichEditor\RichContentRenderer;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\ToggleButtons;
use Filament\Schemas\Components\Group;
use Illuminate\Foundation\Vite;
use Illuminate\Support\HtmlString;
use Illuminate\Support\Str;
use Throwable;
/**
* Übersetzt das Widget-Register in den Filament-Builder des Seiteneditors.
*
* Der Editor kennt keine einzelne Widget-Art: Auswahl, Felder, Varianten, Zusammenfassung und
* Blockvorschau kommen vollständig aus dem Register. Zustand eines Builder-Eintrags:
* {type, data: {id, variant, settings, data, refs}}.
*/
class WidgetEditor
{
public const MAX_WIDGETS = 40;
public static function builder(string $name = 'blocks'): Builder
{
$registry = app(WidgetRegistry::class);
return Builder::make($name)
->label('Abschnitte')
->blocks(array_values(array_map(self::block(...), $registry->all())))
->blockPreviews()
->blockPickerColumns(['default' => 1, 'md' => 2])
->blockPickerWidth('3xl')
->addActionLabel('Abschnitt hinzufügen')
->addBetweenActionLabel('Hier einfügen')
->reorderableWithButtons()
->reorderableWithDragAndDrop()
->cloneable()
->deletable()
->maxItems(self::MAX_WIDGETS)
->addAction(fn ($action) => $action->modalHeading('Neuen Abschnitt einrichten')->modalWidth('4xl'))
->addBetweenAction(fn ($action) => $action->modalHeading('Neuen Abschnitt einrichten')->modalWidth('4xl'))
->editAction(fn ($action) => $action->modalHeading('Abschnitt bearbeiten')->modalWidth('4xl')->modalSubmitActionLabel('Übernehmen'))
->columnSpanFull();
}
public static function block(WidgetType $type): Block
{
$variants = $type->variants();
$schema = [Hidden::make('id')];
$schema[] = count($variants) > 1
? ToggleButtons::make('variant')
->label('Darstellung')
->options($variants)
->default($type->defaultVariant())
->inline()
->required()
: Hidden::make('variant')->default($type->defaultVariant());
if ($type->settings() !== []) {
$settings = [];
foreach ($type->settings() as $key => $options) {
$settings[] = Select::make($key)->label(Str::headline($key))->options($options);
}
$schema[] = Group::make($settings)->statePath('settings');
}
foreach ($type->editorSchema() as $component) {
$schema[] = $component;
}
return WidgetBlock::make($type->key())
->label(function (?array $state) use ($type): string|HtmlString {
if ($state === null) {
return self::pickerLabel($type);
}
return self::itemLabel($type, $state);
})
->icon($type->icon())
->schema($schema)
->preview('filament.cms.widget-preview');
}
/**
* Gespeicherte Bausteine (Altformat oder Hülle) als Builder-Zustand.
*
* @param array<int|string, mixed>|null $blocks
* @return list<array{type: string, data: array<string, mixed>}>
*/
public static function toBuilderState(?array $blocks): array
{
$state = [];
foreach (app(WidgetRegistry::class)->read($blocks) as $widget) {
$state[] = [
'type' => $widget['type'],
'data' => [
'id' => $widget['id'] ?? (string) Str::uuid(),
'variant' => $widget['variant'],
'settings' => $widget['settings'],
'data' => $widget['data'],
'refs' => $widget['refs'],
],
];
}
return $state;
}
/**
* Builder-Zustand als Hüllen für PageService::saveRevision().
*
* @param array<int|string, mixed>|null $state
* @return list<array<string, mixed>>
*/
public static function fromBuilderState(?array $state): array
{
$registry = app(WidgetRegistry::class);
$blocks = [];
foreach (array_values($state ?? []) as $item) {
$key = $item['type'] ?? null;
$data = is_array($item['data'] ?? null) ? $item['data'] : [];
$blocks[] = [
'id' => $data['id'] ?? null,
'type' => $key,
'v' => $registry->has($key) ? $registry->get($key)->version() : 1,
'variant' => $data['variant'] ?? null,
'settings' => is_array($data['settings'] ?? null) ? $data['settings'] : [],
'data' => self::listValues(is_array($data['data'] ?? null) ? $data['data'] : []),
'refs' => self::listValues(is_array($data['refs'] ?? null) ? $data['refs'] : []),
];
}
return $blocks;
}
/**
* Übersetzt Fehlerschlüssel des Registers ("blocks.3.data.url") in Formularpfade des Builders.
*
* @param array<string, mixed> $errors
* @param list<string> $itemKeys Builder-Schlüssel in Anzeigereihenfolge
* @return array<string, mixed>
*/
public static function mapErrors(array $errors, array $itemKeys, string $statePath = 'data.blocks'): array
{
$mapped = [];
foreach ($errors as $key => $messages) {
if (preg_match('/^blocks\.(\d+)(?:\.(.*))?$/', (string) $key, $match) === 1 && isset($itemKeys[(int) $match[1]])) {
// Verschachtelte Listen (items.2.url) tragen im Formular UUID-Schlüssel; die Meldung steht dann am Listenfeld.
$suffix = preg_replace('/\.\d+\..*$/', '', $match[2] ?? '');
$mapped[$statePath.'.'.$itemKeys[(int) $match[1]].'.data'.($suffix !== '' ? '.'.$suffix : '')] = $messages;
continue;
}
$mapped['data.'.$key] = $messages;
}
return $mapped;
}
/**
* Blockvorschau: dieselbe Widget-Ansicht wie öffentlich, aus dem ungespeicherten Zustand.
*
* @param array<string, mixed> $state roher Zustand eines Builder-Eintrags
*/
public static function renderPreview(string $type, array $state): string
{
$registry = app(WidgetRegistry::class);
if (! $registry->has($type)) {
return '';
}
$widget = $registry->upcast([
'id' => null,
'type' => $type,
'v' => $registry->get($type)->version(),
'variant' => $state['variant'] ?? null,
'settings' => is_array($state['settings'] ?? null) ? $state['settings'] : [],
'data' => self::plainState(is_array($state['data'] ?? null) ? $state['data'] : []),
'refs' => self::plainState(is_array($state['refs'] ?? null) ? $state['refs'] : []),
]);
try {
return app(WidgetRenderer::class)->renderWidget($widget, RenderContext::preview());
} catch (Throwable $exception) {
report($exception);
return '<p class="preview-note">Die Vorschau dieses Abschnitts ist noch unvollständig.</p>';
}
}
public static function previewStylesheets(): string
{
try {
return app(Vite::class)(['resources/css/app.css'])->toHtml();
} catch (Throwable) {
return '';
}
}
private static function pickerLabel(WidgetType $type): HtmlString
{
return new HtmlString(
'<span class="luf-widget-pick">'
.self::schematicSvg($type)
.'<span class="luf-widget-pick-text"><span class="luf-widget-pick-name">'.e($type->label()).'</span>'
.'<span class="luf-widget-pick-desc">'.e($type->description()).'</span></span></span>'
);
}
/**
* @param array<string, mixed> $state
*/
private static function itemLabel(WidgetType $type, array $state): string
{
$variant = $state['variant'] ?? $type->defaultVariant();
$variantLabel = $type->variants()[$variant] ?? null;
try {
$summary = $type->summary([
'type' => $type->key(),
'variant' => $variant,
'data' => self::plainState(is_array($state['data'] ?? null) ? $state['data'] : []),
'refs' => self::plainState(is_array($state['refs'] ?? null) ? $state['refs'] : []),
'settings' => [],
]);
} catch (Throwable) {
$summary = '';
}
$parts = [$type->label()];
if (count($type->variants()) > 1 && $variantLabel !== null) {
$parts[] = $variantLabel;
}
$label = implode(' · ', $parts);
return $summary !== '' ? $label.' – '.Str::limit($summary, 90) : $label;
}
private static function schematicSvg(WidgetType $type): string
{
$fills = ['ink' => '#1b2838', 'accent' => '#0f6e56', 'line' => '#c5d2cb', 'image' => '#9fb8ab'];
$rects = '';
foreach ($type->schematic() as [$x, $y, $w, $h, $tone]) {
$rects .= sprintf('<rect x="%d" y="%d" width="%d" height="%d" rx="1" fill="%s"/>', $x, $y, $w, $h, $fills[$tone] ?? $fills['line']);
}
return '<svg class="luf-widget-pick-schematic" viewBox="0 0 60 36" width="60" height="36" aria-hidden="true" focusable="false"><rect width="60" height="36" rx="2" fill="#f7faf8"/>'.$rects.'</svg>';
}
/**
* Roh-Zustand des Formulars (Repeater mit UUID-Schlüsseln, Texteditor als Dokument) in einfache Werte.
*
* @param array<int|string, mixed> $state
* @return array<int|string, mixed>
*/
private static function plainState(array $state): array
{
foreach ($state as $key => $value) {
if (is_array($value) && ($value['type'] ?? null) === 'doc') {
try {
$state[$key] = RichContentRenderer::make($value)->toHtml();
} catch (Throwable) {
$state[$key] = '';
}
continue;
}
if (is_array($value) && ! str_starts_with((string) $key, '_')) {
$state[$key] = self::plainState(array_is_list($value) || ! self::isUuidKeyed($value) ? $value : array_values($value));
}
}
return $state;
}
/**
* @param array<int|string, mixed> $values
* @return array<int|string, mixed>
*/
private static function listValues(array $values): array
{
foreach ($values as $key => $value) {
if (is_array($value) && ! str_starts_with((string) $key, '_')) {
$values[$key] = self::isUuidKeyed($value) ? array_values(array_map(fn ($item) => is_array($item) ? self::listValues($item) : $item, $value)) : self::listValues($value);
}
}
return $values;
}
/**
* @param array<int|string, mixed> $value
*/
private static function isUuidKeyed(array $value): bool
{
if ($value === []) {
return false;
}
foreach (array_keys($value) as $key) {
if (! is_string($key) || ! Str::isUuid($key)) {
return false;
}
}
return true;
}
}
+23 -3
View File
@@ -5,6 +5,9 @@
use App\Domain\Catalog\Pillar;
use App\Domain\Cms\Page;
use App\Domain\Cms\PageRevision;
use App\Domain\Cms\PageTemplates;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\WidgetRenderer;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Gate;
@@ -24,11 +27,26 @@ public function show(string $path): View
public function preview(PageRevision $revision): View
{
$page = $revision->page;
Gate::authorize('view', $page);
Gate::forUser(auth('staff')->user())->authorize('view', $page);
return $this->render($page, preview: true, revision: $revision);
}
/**
* Rahmen für die Vorschau einer Revision in den Breiten Smartphone, Tablet und Desktop.
*/
public function devices(PageRevision $revision): View
{
$page = $revision->page;
Gate::forUser(auth('staff')->user())->authorize('view', $page);
return view('public.preview-devices', [
'page' => $page,
'revision' => $revision,
'isLive' => $page->published_revision_id === $revision->id,
]);
}
public function sitemap(): Response
{
$pages = Page::query()->whereNotNull('published_revision_id')->orderBy('path')->get();
@@ -44,13 +62,15 @@ private function render(Page $page, bool $preview, ?PageRevision $revision = nul
$revision ??= $page->publishedRevision;
abort_if($revision === null, 404);
$heading = collect($revision->blocks)->firstWhere('type', 'heading');
$context = $preview ? RenderContext::preview() : RenderContext::publicPage();
return view('public.page', [
'page' => $page,
'revision' => $revision,
'preview' => $preview,
'documentTitle' => $revision->seo_title ?: ($heading['heading'] ?? config('app.name')),
'template' => app(PageTemplates::class)->viewFor($page),
'content' => app(WidgetRenderer::class)->renderAll($revision->blocks, $context),
'documentTitle' => $revision->seo_title ?: ($revision->contentTitle() ?? config('app.name')),
'documentDescription' => $revision->seo_description,
'themes' => $page->path === '/' ? Pillar::query()->published()->get() : collect(),
]);
@@ -3,30 +3,20 @@
namespace App\Http\Controllers;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionDisplayRelease;
use App\Domain\Catalog\CompositionStructureReader;
use App\Domain\Catalog\EditorialContentKind;
use App\Domain\Cms\Catalog\PublicCatalogReader;
use Illuminate\View\View;
class PublicCatalogController extends Controller
{
public function index(): View
public function index(PublicCatalogReader $catalog): View
{
$kind = EditorialContentKind::query()->where('slug', 'programm')->first();
$programs = Composition::query()
->when($kind !== null, fn ($query) => $query->where('editorial_content_kind_id', $kind->id))
->orderBy('designation')
->get()
->filter(fn (Composition $composition): bool => app(CompositionDisplayRelease::class)->highestReleasedVersion($composition) !== null);
return view('public.programs', ['programs' => $programs]);
return view('public.programs', ['programs' => $catalog->publicPrograms()]);
}
public function program(Composition $composition): View
public function program(Composition $composition, PublicCatalogReader $catalog): View
{
$kind = $composition->editorialContentKind;
abort_unless($kind?->slug === 'programm', 404);
$version = app(CompositionDisplayRelease::class)->highestReleasedVersion($composition);
$version = $catalog->shownVersion($composition);
abort_if($version === null, 404);
return view('public.program', [
+5 -1
View File
@@ -6,6 +6,7 @@
use App\Domain\Cms\NavigationItemPolicy;
use App\Domain\Cms\Page;
use App\Domain\Cms\PagePolicy;
use App\Domain\Cms\Widgets\WidgetRegistry;
use App\Domain\Media\FfmpegFilmTranscoder;
use App\Domain\Media\FilmTranscoder;
use App\Filament\Support\MediaUploadLimit;
@@ -22,6 +23,9 @@ class AppServiceProvider extends ServiceProvider
public function register(): void
{
$this->app->bind(FilmTranscoder::class, FfmpegFilmTranscoder::class);
$this->app->singleton(WidgetRegistry::class, fn ($app): WidgetRegistry => new WidgetRegistry(
array_map(fn (string $class) => $app->make($class), config('cms.widgets', [])),
));
}
public function boot(): void
@@ -38,7 +42,7 @@ public function boot(): void
View::composer('layouts.site', function ($view): void {
if (! array_key_exists('navigation', $view->getData())) {
$view->with('navigation', NavigationItem::query()->with('page')->orderBy('sort_order')->orderBy('id')->get());
$view->with('navigation', NavigationItem::query()->visible()->with('page')->orderBy('sort_order')->orderBy('id')->get());
}
});
}
@@ -67,6 +67,10 @@ public function panel(Panel $panel): Panel
->authMiddleware([
Authenticate::class,
])
->renderHook(
PanelsRenderHook::STYLES_AFTER,
fn (): string => view('filament.cms.styles')->render(),
)
->renderHook(
PanelsRenderHook::BODY_END,
fn (): string => app()->environment('testing') ? '' : Blade::render("@vite('resources/js/app.js')"),
+38
View File
@@ -0,0 +1,38 @@
<?php
use App\Domain\Cms\Widgets\Types\CallToActionWidget;
use App\Domain\Cms\Widgets\Types\CardsWidget;
use App\Domain\Cms\Widgets\Types\CatalogCardsWidget;
use App\Domain\Cms\Widgets\Types\FaqWidget;
use App\Domain\Cms\Widgets\Types\HeadingWidget;
use App\Domain\Cms\Widgets\Types\HeroWidget;
use App\Domain\Cms\Widgets\Types\ImageTextWidget;
use App\Domain\Cms\Widgets\Types\ProseWidget;
return [
/*
| Registrierte Widget-Arten (ADR-30). Die Reihenfolge bestimmt die Reihenfolge in der Widget-Auswahl.
| Eine neue Art: Klasse unter App\Domain\Cms\Widgets\Types anlegen, Ansicht unter
| resources/views/widgets/<kennung>.blade.php, hier eintragen. Siehe docs/architektur/cms-widget-registry.md.
| Eine einmal verwendete Kennung wird nie entfernt, solange Revisionen sie enthalten.
*/
'widgets' => [
HeroWidget::class,
HeadingWidget::class,
ProseWidget::class,
ImageTextWidget::class,
CardsWidget::class,
CatalogCardsWidget::class,
CallToActionWidget::class,
FaqWidget::class,
],
/*
| Seitenvorlagen. Für diesen Ausbau gibt es eine Vorlage; weitere werden hier ergänzt.
*/
'templates' => [
'standard' => 'site.templates.standard',
],
];
@@ -0,0 +1,25 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Ergänzend und abwärtskompatibel: bestehende Einträge bleiben sichtbar.
*/
return new class extends Migration
{
public function up(): void
{
Schema::table('navigation_items', function (Blueprint $table) {
$table->boolean('is_visible')->default(true);
});
}
public function down(): void
{
Schema::table('navigation_items', function (Blueprint $table) {
$table->dropColumn('is_visible');
});
}
};
+209 -2
View File
@@ -235,9 +235,21 @@ .image-text {
@media (min-width: 48rem) {
.image-text {
grid-template-columns: minmax(12rem, 16rem) 1fr;
grid-template-columns: minmax(12rem, 22rem) 1fr;
align-items: start;
}
.image-text-right {
grid-template-columns: 1fr minmax(12rem, 22rem);
}
.image-text-right > img {
order: 2;
}
.image-text-no-image {
grid-template-columns: 1fr;
}
}
.image-text img {
@@ -245,6 +257,184 @@ .image-text img {
height: auto;
}
.image-text-copy > :first-child {
margin-top: 0;
}
.prose ul,
.prose ol {
margin: 0 0 1rem;
padding-left: 1.4rem;
}
.prose li > p {
margin: 0;
}
/* Widgets: Einstieg (Hero). Varianten: standard, highlight. */
.hero {
display: grid;
gap: 1.5rem;
align-items: center;
}
.hero .lede {
font-size: 1.2rem;
}
.hero-image {
width: 100%;
height: auto;
display: block;
}
@media (min-width: 48rem) {
.hero-with-image {
grid-template-columns: 1.1fr 1fr;
}
}
.hero-highlight {
background: var(--color-ink);
color: #f4f7f5;
padding: clamp(1.5rem, 4vw, 3rem);
}
.hero-highlight h1,
.hero-highlight h2,
.hero-highlight .lede {
color: inherit;
}
.button {
display: inline-block;
margin-top: 0.5rem;
background: var(--color-pine);
color: #ffffff;
text-decoration: none;
padding: 0.65rem 1.05rem;
font-weight: 600;
}
.button:hover {
text-decoration: underline;
}
.hero-highlight .button {
background: #f4f7f5;
color: var(--color-ink);
}
/* Widgets: redaktionelle Karten. Varianten: Raster (cards-grid), kompakte Liste (cards-compact). */
.card-image {
display: block;
width: calc(100% + 2rem);
max-width: none;
height: auto;
aspect-ratio: 16 / 9;
object-fit: cover;
margin: -1rem -1rem 0.85rem;
}
.cards-compact {
grid-template-columns: 1fr;
gap: 0;
}
.cards-compact .card {
border-top: 0;
border-bottom: 1px solid var(--color-line);
background: transparent;
padding: 0.85rem 0;
}
.cards-compact .card-image {
display: none;
}
.cards-compact .card h3 {
font-size: 1.15rem;
}
/* Widgets: Programm- und Modulkarten. Inhalte kommen aus den Fachdaten. */
.catalog-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
gap: 1rem;
list-style: none;
padding: 0;
margin: 1rem 0 0;
}
.catalog-card {
background: white;
border: 1px solid var(--color-line);
display: flex;
flex-direction: column;
}
.catalog-card-visual {
background: var(--color-paper);
border-bottom: 3px solid var(--color-pine);
min-height: 6rem;
display: flex;
align-items: flex-end;
padding: 0.75rem 1rem;
}
.catalog-card-visual span {
font-family: var(--font-serif);
font-size: 1.1rem;
color: var(--color-pine);
}
.catalog-card-body {
padding: 0.9rem 1rem 1.1rem;
}
.catalog-card-body h3 {
font-family: var(--font-serif);
font-size: 1.35rem;
margin: 0 0 0.4rem;
}
.catalog-card-body p {
margin: 0 0 0.5rem;
}
.catalog-card-kind {
font-size: 0.85rem;
text-transform: uppercase;
letter-spacing: 0.06em;
color: #3f5248;
}
.catalog-cards-compact .catalog-list {
grid-template-columns: 1fr;
gap: 0;
}
.catalog-cards-compact .catalog-card {
border-width: 0 0 1px;
background: transparent;
}
.catalog-cards-compact .catalog-card-body {
padding: 0.75rem 0;
}
.catalog-card-internal {
border-style: dashed;
}
.preview-note {
background: #fff4d6;
color: #3d2e04;
font-size: 0.9rem;
padding: 0.5rem 0.75rem;
margin: 0.5rem 0 0;
}
.faq {
margin: 0;
}
@@ -382,9 +572,26 @@ .site-footer {
padding: 2rem 0 3rem;
}
.site-footer-inner {
display: flex;
flex-wrap: wrap;
gap: 1rem 2rem;
align-items: baseline;
justify-content: space-between;
}
.wordmark-compact {
padding-top: 0;
}
.wordmark-compact strong {
font-size: 1.5rem;
}
.site-footer nav {
display: flex;
gap: 1rem;
flex-wrap: wrap;
gap: 0.5rem 1rem;
}
.site-footer a {
@@ -0,0 +1,10 @@
{{--
Markenzeichen der Website. Solange keine freigegebene Wortmarke als Datei vorliegt
(docs/Brand-UI-Kit/README.md, Abschnitt Markenleitlinien Nr. 5), bleibt es die Textwortmarke.
Eine freigegebene Datei wird ausschließlich hier eingesetzt.
--}}
@props(['compact' => false])
<div {{ $attributes->class(['wordmark', 'wordmark-compact' => $compact]) }}>
<a href="{{ route('home') }}"><strong>Lara &amp; Felix</strong></a>
<span>Stark im Alltag</span>
</div>
@@ -0,0 +1,13 @@
@props(['navigation'])
<footer class="site-footer">
<div class="site-footer-inner">
<x-site.brand compact />
<nav aria-label="Rechtliches und Service">
@foreach ($navigation->where('placement', 'footer') as $item)
@if ($item->href())
<a href="{{ $item->href() }}">{{ $item->label }}</a>
@endif
@endforeach
</nav>
</div>
</footer>
@@ -0,0 +1,18 @@
@props(['navigation', 'page' => null])
<header class="masthead">
<div class="masthead-inner">
<x-site.brand />
<nav class="site-nav" aria-label="Hauptnavigation">
@foreach ($navigation->where('placement', 'header') as $item)
@if ($item->href())
<a href="{{ $item->href() }}" @if($page !== null && $item->page_id === $page->id) aria-current="page" @endif>{{ $item->label }}</a>
@endif
@endforeach
@auth('web')
<a href="{{ route('member.dashboard') }}">Mitgliederbereich</a>
@else
<a href="{{ route('register') }}">Registrieren</a>
@endauth
</nav>
</div>
</header>
@@ -0,0 +1,9 @@
<style>
.luf-widget-pick { display: flex; gap: .75rem; align-items: flex-start; text-align: start; white-space: normal; }
.luf-widget-pick-schematic { flex: none; border: 1px solid rgb(0 0 0 / 12%); border-radius: 3px; }
.luf-widget-pick-text { display: flex; flex-direction: column; gap: .15rem; }
.luf-widget-pick-name { font-weight: 600; }
.luf-widget-pick-desc { font-size: .8rem; line-height: 1.3; opacity: .8; }
.luf-widget-preview-frame { display: block; width: 100%; min-height: 4rem; border: 0; pointer-events: none; background: #f7faf8; }
.luf-widget-preview-empty { margin: 0; padding: 1rem; font-size: .875rem; opacity: .75; }
</style>
@@ -0,0 +1,22 @@
{{--
Blockvorschau im Seiteneditor. Das Widget wird mit derselben Ansicht wie auf der öffentlichen Seite gerendert
und in einem eigenen Dokument angezeigt, damit Website- und Verwaltungsstile sich nicht überlagern.
--}}
@php
$document = '<!DOCTYPE html><html lang="de"><head><meta charset="utf-8"><base target="_blank">'
.$stylesheets
.'<style>html{background:var(--color-sheet,#f7faf8)}body{margin:0;padding:1.25rem 1.5rem;min-height:0}main{display:block}</style>'
.'</head><body><main class="sheet-preview">'.$html.'</main></body></html>';
@endphp
@if (trim($html) === '')
<p class="luf-widget-preview-empty">Dieser Abschnitt zeigt öffentlich nichts an. Bitte Inhalte ergänzen.</p>
@else
<iframe
class="luf-widget-preview-frame"
title="Vorschau des Abschnitts"
tabindex="-1"
srcdoc="{{ $document }}"
loading="lazy"
onload="this.style.height = (this.contentDocument?.documentElement?.scrollHeight ?? 200) + 'px'"
></iframe>
@endif
+2 -31
View File
@@ -15,42 +15,13 @@
</head>
<body>
<a class="skip" href="#inhalt">Zum Inhalt</a>
<header class="masthead">
<div class="masthead-inner">
<div class="wordmark">
<a href="{{ route('home') }}"><strong>Lara &amp; Felix</strong></a>
<span>Stark im Alltag</span>
</div>
<nav class="site-nav" aria-label="Hauptnavigation">
@foreach (($navigation ?? collect())->where('placement', 'header') as $item)
@if ($item->href())
<a href="{{ $item->href() }}" @if(isset($page) && $item->page_id === $page->id) aria-current="page" @endif>{{ $item->label }}</a>
@endif
@endforeach
@auth
<a href="{{ route('member.dashboard') }}">Mitgliederbereich</a>
@else
<a href="{{ route('register') }}">Registrieren</a>
@endauth
</nav>
</div>
</header>
<x-site.header :navigation="$navigation ?? collect()" :page="$page ?? null" />
<main id="inhalt" class="sheet">
@if (session('status'))
<p class="status" role="status">{{ session('status') }}</p>
@endif
@yield('content')
</main>
<footer class="site-footer">
<div class="site-footer-inner">
<nav aria-label="Rechtliches und Service">
@foreach (($navigation ?? collect())->where('placement', 'footer') as $item)
@if ($item->href())
<a href="{{ $item->href() }}">{{ $item->label }}</a>
@endif
@endforeach
</nav>
</div>
</footer>
<x-site.footer :navigation="$navigation ?? collect()" />
</body>
</html>
@@ -1,7 +0,0 @@
<div class="cta">
<h2>{{ $block['heading'] }}</h2>
@if (filled($block['text'] ?? null))
<p>{{ $block['text'] }}</p>
@endif
<a href="{{ $block['url'] }}">{{ $block['label'] }}</a>
</div>
@@ -1,19 +0,0 @@
<ul class="cards">
@foreach ($block['items'] as $item)
<li class="card">
@if (filled($item['url'] ?? null))
<a href="{{ $item['url'] }}">
<h3>{{ $item['title'] }}</h3>
@if (filled($item['text'] ?? null))
<p>{{ $item['text'] }}</p>
@endif
</a>
@else
<h3>{{ $item['title'] }}</h3>
@if (filled($item['text'] ?? null))
<p>{{ $item['text'] }}</p>
@endif
@endif
</li>
@endforeach
</ul>
@@ -1,6 +0,0 @@
<dl class="faq">
@foreach ($block['items'] as $item)
<dt>{{ $item['question'] }}</dt>
<dd>{{ $item['answer'] }}</dd>
@endforeach
</dl>
@@ -1,8 +0,0 @@
@if (! empty($first))
<h1>{{ $block['heading'] }}</h1>
@else
<h2>{{ $block['heading'] }}</h2>
@endif
@if (filled($block['intro'] ?? null))
<p class="lede">{{ $block['intro'] }}</p>
@endif
@@ -1,10 +0,0 @@
<div class="image-text">
@if (filled($block['image'] ?? null))
<img src="{{ route('media.public', ['path' => $block['image']]) }}" alt="{{ $block['alt'] }}">
@endif
<div class="prose">
@foreach (preg_split("/\n\s*\n/", trim($block['body'])) as $paragraph)
<p>{{ $paragraph }}</p>
@endforeach
</div>
</div>
@@ -1,5 +0,0 @@
<div class="prose">
@foreach (preg_split("/\n\s*\n/", trim($block['body'])) as $paragraph)
<p>{{ $paragraph }}</p>
@endforeach
</div>
+1 -11
View File
@@ -8,15 +8,5 @@
@if ($preview)
<p class="preview-banner" role="status">Vorschau einer unveröffentlichten Revision. Die öffentliche Seite bleibt unverändert.</p>
@endif
@foreach ($revision->blocks as $block)
<section class="block">
@include('public.blocks.'.$block['type'], ['block' => $block, 'first' => $loop->first])
</section>
@endforeach
@if ($page->path === '/' && ($themes ?? collect())->isNotEmpty())
<section class="block">
<h2>Themenbereiche</h2>
@include('public.themes.list', ['themes' => $themes])
</section>
@endif
@include($template, ['content' => $content, 'page' => $page, 'themes' => $themes ?? collect()])
@endsection
@@ -0,0 +1,58 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>Vorschau {{ $page->path }} · Revision {{ $revision->id }}</title>
<style>
:root { color-scheme: light; --ink: #1b2838; --line: #c5d2cb; --pine: #0f6e56; }
* { box-sizing: border-box; }
body { margin: 0; font-family: 'Source Sans 3', 'Segoe UI', sans-serif; background: #dfe6e2; color: var(--ink); }
.bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; gap: .75rem 1.25rem; align-items: center; padding: .75rem 1rem; background: var(--ink); color: #f4f7f5; }
.bar strong { font-size: 1rem; }
.bar p { margin: 0; font-size: .9rem; }
.widths { display: flex; gap: .4rem; margin-left: auto; }
.widths button { font: inherit; border: 1px solid rgb(255 255 255 / 45%); background: transparent; color: inherit; padding: .35rem .8rem; border-radius: .25rem; cursor: pointer; }
.widths button[aria-pressed='true'] { background: #f4f7f5; color: var(--ink); }
.widths button:focus-visible, .bar a:focus-visible { outline: 3px solid #fcd10a; outline-offset: 2px; }
.bar a { color: inherit; }
.stage { overflow-x: auto; padding: 1.25rem 1rem 3rem; }
.device { margin-inline: auto; background: white; box-shadow: 0 1px 4px rgb(0 0 0 / 18%); transition: none; }
.device iframe { display: block; width: 100%; height: calc(100vh - 7rem); min-height: 36rem; border: 0; }
.size { text-align: center; font-size: .85rem; margin: 0 0 .5rem; }
</style>
</head>
<body>
<div class="bar">
<strong>Vorschau {{ $page->path }}</strong>
<p>Revision {{ $revision->id }} · {{ $isLive ? 'veröffentlicht' : 'nicht veröffentlicht' }}</p>
<div class="widths" role="group" aria-label="Ansichtsbreite">
<button type="button" data-width="390" aria-pressed="false">Smartphone 390 px</button>
<button type="button" data-width="768" aria-pressed="false">Tablet 768 px</button>
<button type="button" data-width="1440" aria-pressed="true">Desktop 1440 px</button>
</div>
<p><a href="{{ route('pages.preview', $revision) }}" target="_blank" rel="noopener">Ohne Rahmen öffnen</a></p>
</div>
<div class="stage">
<p class="size" id="preview-size" aria-live="polite">Desktop, 1440 px</p>
<div class="device" id="preview-device" style="width: 1440px">
<iframe src="{{ route('pages.preview', $revision) }}" title="Seitenvorschau {{ $page->path }}"></iframe>
</div>
</div>
<script>
(() => {
const names = { 390: 'Smartphone', 768: 'Tablet', 1440: 'Desktop' };
const device = document.getElementById('preview-device');
const size = document.getElementById('preview-size');
const buttons = document.querySelectorAll('[data-width]');
buttons.forEach((button) => button.addEventListener('click', () => {
const width = Number(button.dataset.width);
device.style.width = width + 'px';
size.textContent = names[width] + ', ' + width + ' px';
buttons.forEach((other) => other.setAttribute('aria-pressed', String(other === button)));
}));
})();
</script>
</body>
</html>
@@ -0,0 +1,10 @@
{{-- Seitenvorlage „standard“: Widgets in voller Inhaltsbreite untereinander. --}}
<div class="page-template page-template-standard">
{{ $content }}
@if ($page->path === '/' && $themes->isNotEmpty())
<section class="block">
<h2>Themenbereiche</h2>
@include('public.themes.list', ['themes' => $themes])
</section>
@endif
</div>
@@ -0,0 +1,9 @@
<div class="cta">
<h2>{{ $data['heading'] ?? '' }}</h2>
@if (filled($data['text'] ?? null))
<p>{{ $data['text'] }}</p>
@endif
@if (\App\Domain\Cms\Widgets\Support\SafeUrl::isSafe($data['url'] ?? null))
<a href="{{ $data['url'] }}">{{ $data['label'] ?? '' }}</a>
@endif
</div>
+27
View File
@@ -0,0 +1,27 @@
@if ($items !== [])
<ul class="cards cards-{{ $variant === 'compact' ? 'compact' : 'grid' }}">
@foreach ($items as $item)
<li class="card @if ($item['imageUrl']) card-with-image @endif">
@if ($item['url'])
<a href="{{ $item['url'] }}">
@if ($item['imageUrl'])
<img class="card-image" src="{{ $item['imageUrl'] }}" alt="" loading="lazy">
@endif
<h3>{{ $item['title'] }}</h3>
@if (filled($item['text']))
<p>{{ $item['text'] }}</p>
@endif
</a>
@else
@if ($item['imageUrl'])
<img class="card-image" src="{{ $item['imageUrl'] }}" alt="" loading="lazy">
@endif
<h3>{{ $item['title'] }}</h3>
@if (filled($item['text']))
<p>{{ $item['text'] }}</p>
@endif
@endif
</li>
@endforeach
</ul>
@endif
@@ -0,0 +1,39 @@
@if ($entries !== [] || $context->preview)
<div class="catalog-cards catalog-cards-{{ $variant === 'compact' ? 'compact' : 'standard' }}">
@if (filled($data['heading'] ?? null))
<h2>{{ $data['heading'] }}</h2>
@endif
@if (filled($data['intro'] ?? null))
<p class="lede">{{ $data['intro'] }}</p>
@endif
@if ($entries === [])
<p class="preview-note">Noch kein Programm oder Modul gewählt, oder keines ist öffentlich sichtbar. Öffentlich erscheint dieser Abschnitt nicht.</p>
@else
<ul class="catalog-list">
@foreach ($entries as $entry)
<li class="catalog-card @unless ($entry->public) catalog-card-internal @endunless">
@if ($variant !== 'compact')
<div class="catalog-card-visual" aria-hidden="true"><span>{{ $entry->kindLabel }}</span></div>
@endif
<div class="catalog-card-body">
<p class="catalog-card-kind">{{ $entry->kindLabel }}</p>
<h3>
@if ($entry->url)
<a href="{{ $entry->url }}">{{ $entry->title }}</a>
@else
{{ $entry->title }}
@endif
</h3>
@if ($variant !== 'compact' && filled($entry->summary))
<p>{{ $entry->summary }}</p>
@endif
@unless ($entry->public)
<p class="preview-note">Nur in der Redaktionsvorschau sichtbar: Für diese Inhaltsart gibt es noch keine öffentliche Freigabe (öffentliches Profil, ADR-29).</p>
@endunless
</div>
</li>
@endforeach
</ul>
@endif
</div>
@endif
+6
View File
@@ -0,0 +1,6 @@
<dl class="faq">
@foreach ($data['items'] ?? [] as $item)
<dt>{{ $item['question'] ?? '' }}</dt>
<dd>{{ $item['answer'] ?? '' }}</dd>
@endforeach
</dl>
@@ -0,0 +1,8 @@
@if (! empty($first))
<h1>{{ $data['heading'] ?? '' }}</h1>
@else
<h2>{{ $data['heading'] ?? '' }}</h2>
@endif
@if (filled($data['intro'] ?? null))
<p class="lede">{{ $data['intro'] }}</p>
@endif
+18
View File
@@ -0,0 +1,18 @@
<div class="hero hero-{{ $variant === 'highlight' ? 'highlight' : 'standard' }} @if ($imageUrl) hero-with-image @endif">
<div class="hero-copy">
@if (! empty($first))
<h1>{{ $data['heading'] ?? '' }}</h1>
@else
<h2>{{ $data['heading'] ?? '' }}</h2>
@endif
@if (filled($data['text'] ?? null))
<p class="lede">{{ $data['text'] }}</p>
@endif
@if ($action)
<a class="button" href="{{ $action['url'] }}">{{ $action['label'] }}</a>
@endif
</div>
@if ($imageUrl)
<img class="hero-image" src="{{ $imageUrl }}" alt="{{ $data['alt'] ?? '' }}">
@endif
</div>
@@ -0,0 +1,15 @@
<div class="image-text image-text-{{ $variant === 'image_right' ? 'right' : 'left' }} @unless ($imageUrl) image-text-no-image @endunless">
@if ($imageUrl)
<img src="{{ $imageUrl }}" alt="{{ $data['alt'] ?? '' }}" loading="lazy">
@endif
<div class="image-text-copy">
@if (filled($data['title'] ?? null))
@if (! empty($first))
<h1>{{ $data['title'] }}</h1>
@else
<h2>{{ $data['title'] }}</h2>
@endif
@endif
<div class="prose">{!! $body !!}</div>
</div>
</div>
+7
View File
@@ -0,0 +1,7 @@
@if (filled($data['body'] ?? null))
<div class="prose">
@foreach (preg_split("/\n\s*\n/", trim($data['body'])) as $paragraph)
<p>{{ $paragraph }}</p>
@endforeach
</div>
@endif
+8 -1
View File
@@ -36,6 +36,14 @@
Route::post('/abmelden', [SessionController::class, 'destroy'])->middleware('auth')->name('logout');
Route::get('/redaktion/vorschau/{revision}', [PageController::class, 'preview'])
->middleware('auth:staff')
->whereNumber('revision')
->name('pages.preview');
Route::get('/redaktion/vorschau/{revision}/geraete', [PageController::class, 'devices'])
->middleware('auth:staff')
->whereNumber('revision')
->name('pages.preview.devices');
Route::get('/redaktion/aufbau/{composition}/entwurf', [EditorialPreviewController::class, 'draft'])
->middleware('auth:staff')
->name('editorial.draft-preview');
@@ -69,7 +77,6 @@
Route::post('/email/erneut', [EmailVerificationController::class, 'send'])
->middleware('throttle:6,1')
->name('verification.send');
Route::get('/redaktion/vorschau/{revision}', [PageController::class, 'preview'])->name('pages.preview');
});
Route::middleware(['auth', 'verified'])->prefix('bereich')->name('member.')->group(function () {
+274
View File
@@ -0,0 +1,274 @@
<?php
namespace Tests\Feature;
use App\Domain\Cms\NavigationItem;
use App\Domain\Cms\Page;
use App\Filament\Resources\NavigationItems\Pages\ManageNavigationItems;
use App\Filament\Resources\Pages\Pages\CreatePage;
use App\Filament\Resources\Pages\Pages\EditPage;
use App\Filament\Support\WidgetEditor;
use App\Models\User;
use Filament\Actions\Testing\TestAction;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Livewire\Livewire;
use Tests\Support\BuildsCatalog;
use Tests\TestCase;
class CmsEditorTest extends TestCase
{
use BuildsCatalog;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Filament::setCurrentPanel(Filament::getPanel('verwaltung'));
}
public function test_editor_creates_a_page_from_registered_widgets_without_publishing_it(): void
{
$program = $this->composition('Programm Abstand', 'programm');
$editor = $this->editor();
Livewire::actingAs($editor, 'staff')
->test(CreatePage::class)
->fillForm([
'path' => '/themen-test',
'seo_title' => 'Themenseite',
'blocks' => $this->keyed([
['type' => 'hero', 'data' => ['variant' => 'highlight', 'data' => ['heading' => 'Stark im Alltag', 'text' => 'Einstieg']]],
['type' => 'image_text', 'data' => ['variant' => 'image_right', 'data' => ['title' => 'Worum es geht', 'body' => '<p>Text mit <strong>Betonung</strong></p>'], 'refs' => []]],
['type' => 'cards', 'data' => ['variant' => 'compact', 'data' => ['items' => $this->keyed([['title' => 'Prävention', 'url' => '/praevention']])]]],
['type' => 'catalog_cards', 'data' => ['variant' => 'standard', 'data' => ['heading' => 'Programme'], 'refs' => ['items' => $this->keyed([['type' => 'composition', 'id' => $program->composition_id]])]]],
]),
])
->call('create')
->assertHasNoFormErrors();
$page = Page::query()->where('path', '/themen-test')->firstOrFail();
$blocks = $page->latestRevision->blocks;
$this->assertNull($page->published_revision_id);
$this->assertSame(['hero', 'image_text', 'cards', 'catalog_cards'], array_column($blocks, 'type'));
$this->assertSame(['highlight', 'image_right', 'compact', 'standard'], array_column($blocks, 'variant'));
$this->assertSame([2], array_values(array_unique([$blocks[1]['v']])));
$this->assertStringContainsString('<strong>Betonung</strong>', $blocks[1]['data']['body']);
$this->assertSame([['title' => 'Prävention', 'text' => null, 'url' => '/praevention', 'image' => null]], $blocks[2]['data']['items']);
$this->assertSame([['type' => 'composition', 'id' => $program->composition_id]], $blocks[3]['refs']['items']);
$this->get('/themen-test')->assertNotFound();
}
public function test_existing_page_opens_in_the_editor_and_saves_without_changing_the_live_page(): void
{
$page = Page::query()->where('path', '/')->firstOrFail();
$live = $page->published_revision_id;
$before = $this->mainText($this->get('/')->getContent());
$component = Livewire::actingAs($this->editor(), 'staff')
->test(EditPage::class, ['record' => $page->id]);
$state = $component->get('data.blocks');
$this->assertSame(['heading', 'prose', 'cards', 'call_to_action'], array_column(array_values($state), 'type'));
$component->call('save')->assertHasNoFormErrors();
$page->refresh();
$this->assertSame($live, $page->published_revision_id);
$this->assertNotSame($live, $page->latestRevision->id);
$this->assertSame(['heading', 'prose', 'cards', 'call_to_action'], array_column($page->latestRevision->blocks, 'type'));
$this->assertSame($before, $this->mainText($this->get('/')->getContent()));
Livewire::actingAs($this->editor(), 'staff')
->test(EditPage::class, ['record' => $page->id])
->callAction('publish');
$this->assertSame(
trim(file_get_contents(base_path('tests/Fixtures/legacy-pages/home.txt'))),
$this->mainText($this->get('/')->getContent()),
'Nach dem Speichern im neuen Format zeigt die Seite denselben Text.',
);
}
public function test_editor_reorders_and_duplicates_sections(): void
{
$page = Page::query()->where('path', '/')->firstOrFail();
$component = Livewire::actingAs($this->editor(), 'staff')->test(EditPage::class, ['record' => $page->id]);
$state = $component->get('data.blocks');
$keys = array_keys($state);
$reordered = [$keys[3] => $state[$keys[3]], $keys[0] => $state[$keys[0]], $keys[1] => $state[$keys[1]], $keys[2] => $state[$keys[2]]];
$copy = $state[$keys[1]];
$reordered[(string) Str::uuid()] = $copy;
$component->set('data.blocks', $reordered)->call('save')->assertHasNoFormErrors();
$blocks = $page->fresh()->latestRevision->blocks;
$this->assertSame(['call_to_action', 'heading', 'prose', 'cards', 'prose'], array_column($blocks, 'type'));
$this->assertCount(5, array_unique(array_column($blocks, 'id')), 'Ein dupliziertes Widget erhält eine eigene Kennung.');
}
public function test_unsafe_link_is_reported_at_the_section_and_nothing_is_saved(): void
{
$page = Page::query()->where('path', '/')->firstOrFail();
$revisions = $page->revisions()->count();
$component = Livewire::actingAs($this->editor(), 'staff')->test(EditPage::class, ['record' => $page->id]);
$key = array_keys($component->get('data.blocks'))[3];
$component->set("data.blocks.$key.data.data.url", 'javascript:alert(1)')
->call('save')
->assertHasErrors(["data.blocks.$key.data.data.url"]);
$this->assertSame($revisions, $page->revisions()->count());
}
public function test_invalid_or_taken_paths_are_shown_at_the_path_field(): void
{
Livewire::actingAs($this->editor(), 'staff')
->test(CreatePage::class)
->fillForm(['path' => '/praevention', 'blocks' => []])
->call('create')
->assertHasErrors(['data.path']);
Livewire::actingAs($this->editor(), 'staff')
->test(CreatePage::class)
->fillForm(['path' => 'C:/Program Files/x', 'blocks' => []])
->call('create')
->assertHasErrors(['data.path']);
$this->assertSame(1, Page::query()->where('path', '/praevention')->count());
}
public function test_block_preview_uses_the_public_widget_view_with_unsaved_state(): void
{
$html = WidgetEditor::renderPreview('image_text', [
'variant' => 'image_right',
'data' => [
'title' => 'Ungespeichert',
'body' => ['type' => 'doc', 'content' => [['type' => 'paragraph', 'content' => [['type' => 'text', 'text' => 'Vorschautext']]]]],
],
'refs' => ['image' => null, '_upload' => []],
]);
$this->assertStringContainsString('image-text image-text-right', $html);
$this->assertStringContainsString('<h2>Ungespeichert</h2>', $html);
$this->assertStringContainsString('Vorschautext', $html);
$cards = WidgetEditor::renderPreview('cards', [
'variant' => 'standard',
'data' => ['items' => [(string) Str::uuid() => ['title' => 'Karte A'], (string) Str::uuid() => ['title' => 'Karte B']]],
]);
$this->assertStringContainsString('Karte A', $cards);
$this->assertStringContainsString('Karte B', $cards);
}
public function test_editor_offers_every_registered_widget_with_description(): void
{
$page = Page::query()->where('path', '/')->firstOrFail();
Livewire::actingAs($this->editor(), 'staff')
->test(EditPage::class, ['record' => $page->id])
->assertSee('Einstieg (Hero)')
->assertSee('Programm- und Modulkarten')
->assertSee('Titel und Beschreibung kommen automatisch aus den Fachdaten')
->assertSee('Entwurf speichern');
}
public function test_preview_with_device_widths_is_only_available_to_staff(): void
{
$revision = Page::query()->where('path', '/')->firstOrFail()->latestRevision;
$this->get(route('pages.preview.devices', $revision))->assertRedirect();
$this->actingAs(User::factory()->create())->get(route('pages.preview', $revision))->assertRedirect();
$this->actingAs(User::factory()->create(), 'staff')->get(route('pages.preview', $revision))->assertForbidden();
auth('web')->logout();
$this->actingAs($this->editor(), 'staff')
->get(route('pages.preview.devices', $revision))
->assertOk()
->assertSee('data-width="390"', false)
->assertSee('data-width="768"', false)
->assertSee('data-width="1440"', false)
->assertSee(route('pages.preview', $revision), false);
$this->actingAs($this->editor(), 'staff')
->get(route('pages.preview', $revision))
->assertOk()
->assertSee('Vorschau einer unveröffentlichten Revision')
->assertSee('Registrieren')
->assertDontSee('Mitgliederbereich</a>', false);
}
public function test_navigation_items_can_be_edited_hidden_reordered_and_removed(): void
{
$editor = $this->editor();
$start = NavigationItem::query()->where('label', 'Start')->firstOrFail();
$about = NavigationItem::query()->where('label', 'Über das Projekt')->firstOrFail();
Livewire::actingAs($editor, 'staff')
->test(ManageNavigationItems::class)
->assertCanSeeTableRecords([$start, $about])
->callAction(TestAction::make('edit')->table($about), ['label' => 'Über uns'])
->assertHasNoFormErrors()
->callAction(TestAction::make('toggleVisibility')->table($start));
$this->assertSame('Über uns', $about->fresh()->label);
$this->assertFalse($start->fresh()->is_visible);
$this->get('/praevention')->assertSee('Über uns')->assertDontSee('>Start<', false);
$order = NavigationItem::query()->orderByDesc('sort_order')->pluck('id')->map(fn ($id) => (string) $id)->all();
Livewire::actingAs($editor, 'staff')->test(ManageNavigationItems::class)->call('reorderTable', $order);
$this->assertSame((int) $order[0], NavigationItem::query()->orderBy('sort_order')->first()->id);
Livewire::actingAs($editor, 'staff')
->test(ManageNavigationItems::class)
->callAction(TestAction::make('delete')->table($about));
$this->assertNull($about->fresh());
$this->assertNotNull(Page::query()->where('path', '/ueber')->first(), 'Die Seite bleibt bestehen.');
}
public function test_navigation_rejects_script_addresses(): void
{
Livewire::actingAs($this->editor(), 'staff')
->test(ManageNavigationItems::class)
->callAction('create', ['label' => 'Böse', 'placement' => 'header', 'url' => 'javascript:alert(1)', 'sort_order' => 9, 'is_visible' => true])
->assertHasFormErrors(['url']);
NavigationItem::query()->create(['label' => 'Alt', 'url' => 'javascript:alert(1)', 'placement' => 'footer', 'sort_order' => 99]);
$this->get('/praevention')->assertDontSee('javascript:alert(1)', false);
}
private function editor(): User
{
$editor = User::factory()->redakteur()->create();
$editor->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP');
return $editor;
}
/**
* @param list<array<string, mixed>> $items
* @return array<string, array<string, mixed>>
*/
private function keyed(array $items): array
{
$keyed = [];
foreach ($items as $item) {
$keyed[(string) Str::uuid()] = $item;
}
return $keyed;
}
private function mainText(string $html): string
{
preg_match('#<main[^>]*>(.*)</main>#s', $html, $match);
$text = html_entity_decode(strip_tags(str_replace('<', ' <', $match[1] ?? '')), ENT_QUOTES | ENT_HTML5, 'UTF-8');
return trim(preg_replace('/\s+/u', ' ', $text));
}
}
+237
View File
@@ -0,0 +1,237 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\CompositionDisplayRelease;
use App\Domain\Cms\Page;
use App\Domain\Cms\PageService;
use App\Jobs\PublishPublicMedia;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Illuminate\Validation\ValidationException;
use Tests\Support\BuildsCatalog;
use Tests\TestCase;
class CmsWidgetRenderingTest extends TestCase
{
use BuildsCatalog;
use RefreshDatabase;
/**
* Die Textfolge jeder Bestandsseite entspricht der Darstellung vor Einführung der Registry
* (tests/Fixtures/legacy-pages, erzeugt aus dem Stand develop@cfdd6de).
*/
public function test_existing_pages_render_the_same_text_as_before_the_registry(): void
{
$pages = ['/' => 'home', '/praevention' => 'praevention', '/materialien' => 'materialien', '/angebote' => 'angebote', '/trainer' => 'trainer', '/ueber' => 'ueber', '/impressum' => 'impressum', '/datenschutz' => 'datenschutz'];
foreach ($pages as $path => $fixture) {
$html = $this->get($path)->assertOk()->getContent();
$this->assertSame(
trim(file_get_contents(base_path("tests/Fixtures/legacy-pages/$fixture.txt"))),
$this->mainText($html),
"Abweichung auf $path",
);
}
}
public function test_legacy_revisions_stored_in_the_flat_format_still_render(): void
{
$page = Page::query()->create(['path' => '/alt']);
$revision = $page->revisions()->create([
'blocks' => [
['type' => 'heading', 'heading' => 'Alte Seite', 'intro' => 'Einleitung'],
['type' => 'image_text', 'image' => 'cms/alt.jpg', 'alt' => 'Altes Bild', 'body' => "Absatz eins.\n\nAbsatz <zwei>."],
['type' => 'faq', 'items' => [['question' => 'Frage?', 'answer' => 'Antwort.']]],
['type' => 'cards', 'items' => [['title' => 'Karte', 'text' => 'Text', 'url' => '/praevention']]],
['type' => 'call_to_action', 'heading' => 'Los', 'text' => null, 'label' => 'Anmelden', 'url' => '/anmelden'],
],
]);
app(PageService::class)->publish($page, $revision);
$this->get('/alt')
->assertOk()
->assertSee('<title>Alte Seite</title>', false)
->assertSee('<h1>Alte Seite</h1>', false)
->assertSee('alt="Altes Bild"', false)
->assertSee('<p>Absatz eins.</p><p>Absatz &lt;zwei&gt;.</p>', false)
->assertSee('<dt>Frage?</dt>', false)
->assertSee('href="/praevention"', false)
->assertSee('href="/anmelden"', false);
$this->assertSame('heading', $revision->fresh()->blocks[0]['type']);
$this->assertArrayNotHasKey('v', $revision->fresh()->blocks[0], 'Die gespeicherte Altrevision bleibt unverändert.');
}
public function test_restoring_a_legacy_revision_keeps_its_stored_blocks(): void
{
$page = Page::query()->where('path', '/')->firstOrFail();
$legacy = $page->publishedRevision;
$service = app(PageService::class);
$service->saveRevision($page, [['type' => 'heading', 'v' => 1, 'data' => ['heading' => 'Neu']]], null, null, null);
$restored = $service->restore($page, $legacy, null);
$this->assertSame($legacy->blocks, $restored->blocks);
}
public function test_new_revisions_are_stored_as_widget_envelopes(): void
{
$page = Page::query()->create(['path' => '/neu']);
$revision = app(PageService::class)->saveRevision($page, [
['type' => 'prose', 'body' => 'Altes Eingabeformat'],
['type' => 'hero', 'v' => 1, 'variant' => 'highlight', 'data' => ['heading' => 'Einstieg']],
], null, null, null);
$this->assertSame(['id', 'type', 'v', 'variant', 'settings', 'data', 'refs'], array_keys($revision->blocks[0]));
$this->assertSame('prose', $revision->blocks[0]['type']);
$this->assertSame(['body' => 'Altes Eingabeformat'], $revision->blocks[0]['data']);
$this->assertSame('highlight', $revision->blocks[1]['variant']);
$this->assertNull($page->fresh()->published_revision_id, 'Speichern veröffentlicht nicht.');
}
public function test_reference_widgets_render_their_variants(): void
{
$page = Page::query()->create(['path' => '/varianten']);
$revision = app(PageService::class)->saveRevision($page, [
['type' => 'hero', 'v' => 1, 'variant' => 'highlight', 'data' => ['heading' => 'Stark im Alltag', 'text' => 'Einstieg', 'cta_label' => 'Mehr', 'cta_url' => '/praevention']],
['type' => 'image_text', 'v' => 2, 'variant' => 'image_right', 'data' => ['title' => 'Bild rechts', 'body' => '<p>Text <em>betont</em></p>', 'alt' => 'Beschreibung'], 'refs' => ['image' => 'cms/beispiel.jpg']],
['type' => 'cards', 'v' => 1, 'variant' => 'compact', 'data' => ['items' => [['title' => 'Eins', 'url' => '/a'], ['title' => 'Zwei']]]],
], null, null, null);
app(PageService::class)->publish($page, $revision);
$this->get('/varianten')
->assertOk()
->assertSee('hero hero-highlight', false)
->assertSee('<h1>Stark im Alltag</h1>', false)
->assertSee('class="button" href="/praevention"', false)
->assertSee('image-text image-text-right', false)
->assertSee('<h2>Bild rechts</h2>', false)
->assertSee('<em>betont</em>', false)
->assertSee(route('media.public', ['path' => 'cms/beispiel.jpg']), false)
->assertSee('cards cards-compact', false);
}
public function test_media_of_any_widget_are_published_through_the_queue(): void
{
Queue::fake();
$page = Page::query()->create(['path' => '/medien']);
app(PageService::class)->saveRevision($page, [
['type' => 'hero', 'v' => 1, 'data' => ['heading' => 'A', 'alt' => 'Bild'], 'refs' => ['image' => 'cms/hero.jpg']],
['type' => 'cards', 'v' => 1, 'data' => ['items' => [['title' => 'K', 'image' => 'cms/karte.jpg']]]],
], null, null, null);
Queue::assertPushed(PublishPublicMedia::class, fn ($job) => $job->path === 'cms/hero.jpg');
Queue::assertPushed(PublishPublicMedia::class, fn ($job) => $job->path === 'cms/karte.jpg');
}
public function test_catalog_cards_show_released_programs_from_the_master_data_only(): void
{
$program = $this->composition('Programm Abstand', 'programm', summary: 'Kurzbeschreibung aus den Fachdaten');
$module = $this->composition('Modul Nein sagen', 'modul');
$page = Page::query()->create(['path' => '/thema']);
$revision = app(PageService::class)->saveRevision($page, [[
'type' => 'catalog_cards',
'v' => 1,
'data' => ['heading' => 'Passende Angebote'],
'refs' => ['items' => [
['type' => 'composition', 'id' => $module->composition_id],
['type' => 'composition', 'id' => $program->composition_id],
]],
]], null, null, null);
app(PageService::class)->publish($page, $revision);
$this->assertSame(
['items' => [['type' => 'composition', 'id' => $module->composition_id], ['type' => 'composition', 'id' => $program->composition_id]]],
$revision->blocks[0]['refs'],
);
$this->assertStringNotContainsString('Programm Abstand', json_encode($revision->blocks), 'Keine Stammdaten im CMS.');
$this->get('/thema')
->assertOk()
->assertSee('Passende Angebote')
->assertSee('Programm Abstand')
->assertSee('Kurzbeschreibung aus den Fachdaten')
->assertSee(route('public.program', $program->composition_id), false)
->assertDontSee('Modul Nein sagen')
->assertDontSee('Redaktionsvorschau');
$program->composition->update(['display_title' => 'Programm „Abstand halten“']);
$this->get('/thema')->assertSee('Programm „Abstand halten“');
}
public function test_catalog_cards_show_modules_only_in_the_protected_preview(): void
{
$module = $this->composition('Modul Nein sagen', 'modul');
$page = Page::query()->create(['path' => '/modulseite']);
$revision = app(PageService::class)->saveRevision($page, [
['type' => 'heading', 'v' => 1, 'data' => ['heading' => 'Module']],
['type' => 'catalog_cards', 'v' => 1, 'data' => [], 'refs' => ['items' => [['type' => 'composition', 'id' => $module->composition_id]]]],
], null, null, null);
app(PageService::class)->publish($page, $revision);
$this->get('/modulseite')->assertOk()->assertDontSee('Modul Nein sagen')->assertDontSee('catalog-cards');
$editor = User::factory()->redakteur()->create();
$this->actingAs($editor, 'staff')
->get(route('pages.preview', $revision))
->assertOk()
->assertSee('Modul Nein sagen')
->assertSee('Nur in der Redaktionsvorschau sichtbar');
}
public function test_revoking_the_display_release_removes_the_card_without_editing_the_page(): void
{
$program = $this->composition('Programm Rückzug', 'programm');
$page = Page::query()->create(['path' => '/rueckzug']);
$revision = app(PageService::class)->saveRevision($page, [
['type' => 'heading', 'v' => 1, 'data' => ['heading' => 'Rückzug']],
['type' => 'catalog_cards', 'v' => 1, 'refs' => ['items' => [['type' => 'composition', 'id' => $program->composition_id]]]],
], null, null, null);
app(PageService::class)->publish($page, $revision);
$this->get('/rueckzug')->assertSee('Programm Rückzug');
$program->displayEvents()->update(['occurred_at' => now()->subMinute()]);
app(CompositionDisplayRelease::class)->revoke($program, User::factory()->create());
$this->get('/rueckzug')->assertOk()->assertDontSee('Programm Rückzug');
}
public function test_unreleased_or_foreign_objects_cannot_be_referenced(): void
{
$draft = $this->composition('Programm Entwurf', 'programm', released: false);
$page = Page::query()->create(['path' => '/entwurf']);
$this->expectException(ValidationException::class);
app(PageService::class)->saveRevision($page, [
['type' => 'catalog_cards', 'v' => 1, 'refs' => ['items' => [['type' => 'composition', 'id' => $draft->composition_id]]]],
], null, null, null);
}
public function test_public_program_list_uses_the_same_public_rule(): void
{
$this->composition('Programm Öffentlich', 'programm');
$this->composition('Programm Intern', 'programm', released: false);
$this->composition('Modul Freigegeben', 'modul');
$this->get('/programme')
->assertOk()
->assertSee('Programm Öffentlich')
->assertDontSee('Programm Intern')
->assertDontSee('Modul Freigegeben');
}
private function mainText(string $html): string
{
preg_match('#<main[^>]*>(.*)</main>#s', $html, $match);
$text = html_entity_decode(strip_tags(str_replace('<', ' <', $match[1] ?? '')), ENT_QUOTES | ENT_HTML5, 'UTF-8');
return trim(preg_replace('/\s+/u', ' ', $text));
}
}
+1
View File
@@ -0,0 +1 @@
Angebote Umfang, Rechte und Preise eines Angebots kommen aus dem Katalog. Sie werden hier nicht als freier Text ersetzt. Es sind noch keine Angebote veröffentlicht. Sobald ein Angebot aktiv ist, zeigt diese Seite seinen Umfang aus dem gespeicherten Stand.
@@ -0,0 +1 @@
Datenschutz Die Datenschutzerklärung wird hier gepflegt und ist noch nicht eingesetzt. Profilangaben sind standardmäßig nicht öffentlich. Geschützte Medien werden nicht über einen öffentlichen Dateipfad ausgeliefert.
+1
View File
@@ -0,0 +1 @@
Stark im Alltag Lara & Felix ist eine Plattform für Gewaltprävention, Selbstbehauptung und gewaltpräventive Bildungsarbeit. Sie unterstützt Erwachsene, die solche Angebote vorbereiten und durchführen. Die Lerninhalte richten sich unter anderem an Kinder. Kinder sind keine Benutzerinnen und Benutzer der Plattform und brauchen kein eigenes Konto. Die Filme „Lara & Felix“ sind die erste Produktreihe. Übungen, Programme und weitere Materialien lassen sich in derselben Struktur verwalten, ohne die Plattform auf eine einzelne Episode festzulegen. Prävention Worum es in der Bildungsarbeit geht. Materialien Filme und Begleitmaterial, sobald sie veröffentlicht sind. Für Trainer und Einrichtungen Wer die Plattform nutzt. Mitgliederbereich Nach der Anmeldung sehen Sie die Materialien, für die eine Berechtigung vorliegt. Anmelden
@@ -0,0 +1 @@
Impressum Die gesetzlich erforderlichen Angaben werden hier veröffentlicht, sobald sie feststehen. Diese Seite ist redaktionell pflegbar. Sie enthält noch keine Angaben zu einer verantwortlichen Stelle.
@@ -0,0 +1 @@
Filme und Lernmaterialien Hier erscheinen veröffentlichte Inhalte aus dem Katalog. Die Seite kopiert keine Produkttexte und nennt keine Preise. Solange noch kein Lizenzartikel veröffentlicht ist, bleibt diese Übersicht leer. Dieselbe Stelle zeigt später Filme, Übungen und Begleitmaterial aus den maßgeblichen Datensätzen.
@@ -0,0 +1 @@
Prävention im Alltag Die Plattform stellt Materialien bereit, mit denen Trainerinnen, Trainer und pädagogische Fachkräfte Präventionsangebote durchführen. Es geht um Selbstbehauptung, das Erkennen von Grenzverletzungen und um Handlungsfähigkeit in konkreten Situationen. Die Durchführung bleibt bei den Erwachsenen vor Ort. Eine Entscheidungspause in einem Film ist eine Markierung für den Präsenzkurs. Daraus wird kein digitales Quiz und keine eigenständige Lernanwendung für Kinder.
+1
View File
@@ -0,0 +1 @@
Für Trainer und Einrichtungen Die Plattform ist für Erwachsene, die geeignete Präventionsangebote durchführen. Dazu gehören Gewaltschutztrainer, Trainer und Übungsleiter, pädagogische Fachkräfte sowie Vereine und Bildungseinrichtungen. Ein Konto allein öffnet keine Materialien. Sichtbar wird, was eine konkrete Berechtigung erlaubt. Organisationen können später eigene Lizenzen halten. Eine persönliche Freischaltung ist keine Organisationslizenz.
+1
View File
@@ -0,0 +1 @@
Über das Projekt Lara & Felix – Stark im Alltag ist eine eigenständige Plattform für Gewaltprävention, Selbstbehauptung und gewaltpräventive Bildungsarbeit. Die erste Produktreihe sind die vorhandenen Filme. Das Fachmodell bleibt offen für weitere Medienarten, Übungen und Programme.
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace Tests\Support;
use App\Domain\Catalog\CompositionDisplayRelease;
use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\EditorialContentKind;
use App\Models\User;
trait BuildsCatalog
{
/**
* Legt eine bereitgestellte Komposition mit Inhaltsart an und gibt sie auf Wunsch zur Anzeige frei.
*/
protected function composition(string $designation, string $kind, bool $released = true, ?string $summary = null): CompositionVersion
{
$content = app(ContentService::class);
$kindId = EditorialContentKind::query()->where('slug', $kind)->firstOrFail()->id;
$version = $content->publishComposition(
tap($content->createComposition($designation), function ($composition) use ($kindId, $summary): void {
$composition->editorial_content_kind_id = $kindId;
$composition->summary = $summary;
$composition->save();
}),
[['role' => 'Text', 'target' => $content->publishElementVersion($content->createElement('text', 'text', $designation.' Blatt'), 'Inhalt')]],
);
if ($released) {
app(CompositionDisplayRelease::class)->release($version, User::factory()->create());
}
return $version;
}
}
-33
View File
@@ -1,33 +0,0 @@
<?php
namespace Tests\Unit;
use App\Domain\Cms\Blocks\BlockRegistry;
use Illuminate\Validation\ValidationException;
use Tests\TestCase;
class BlockRegistryTest extends TestCase
{
public function test_image_text_requires_an_alternative_text(): void
{
$this->expectException(ValidationException::class);
app(BlockRegistry::class)->normalize([
['type' => 'image_text', 'body' => 'Text', 'image' => 'cms/bild.jpg'],
]);
}
public function test_action_links_reject_script_urls(): void
{
$this->expectException(ValidationException::class);
app(BlockRegistry::class)->normalize([
[
'type' => 'call_to_action',
'heading' => 'Weiter',
'label' => 'Öffnen',
'url' => 'javascript:alert(1)',
],
]);
}
}
+318
View File
@@ -0,0 +1,318 @@
<?php
namespace Tests\Unit;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\RichText;
use App\Domain\Cms\Widgets\WidgetRegistry;
use App\Domain\Cms\Widgets\WidgetRenderer;
use App\Domain\Cms\Widgets\WidgetType;
use App\Filament\Support\WidgetEditor;
use Filament\Forms\Components\TextInput;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use Tests\TestCase;
class WidgetRegistryTest extends TestCase
{
private function registry(): WidgetRegistry
{
return app(WidgetRegistry::class);
}
public function test_all_configured_widgets_are_registered_with_complete_contract(): void
{
$types = $this->registry()->all();
$this->assertSame(
['hero', 'heading', 'prose', 'image_text', 'cards', 'catalog_cards', 'call_to_action', 'faq'],
array_keys($types),
);
foreach ($types as $key => $type) {
$this->assertSame($key, $type->key());
$this->assertNotSame('', $type->label());
$this->assertNotSame('', $type->description());
$this->assertGreaterThanOrEqual(1, $type->version());
$this->assertNotEmpty($type->variants());
$this->assertArrayHasKey($type->defaultVariant(), $type->variants());
$this->assertNotEmpty($type->dataRules());
$this->assertNotEmpty($type->editorSchema());
$this->assertTrue(view()->exists($type->view()), "Ansicht für $key fehlt");
}
}
public function test_reference_widgets_offer_at_least_two_variants(): void
{
foreach (['hero', 'image_text', 'cards', 'catalog_cards'] as $key) {
$this->assertGreaterThanOrEqual(2, count($this->registry()->get($key)->variants()), $key);
}
$this->assertSame(['image_left', 'image_right'], array_keys($this->registry()->get('image_text')->variants()));
}
public function test_registration_rejects_duplicate_and_invalid_keys(): void
{
$registry = new WidgetRegistry([$this->customWidget('teaser')]);
$this->expectException(InvalidArgumentException::class);
$registry->register($this->customWidget('teaser'));
}
public function test_registration_rejects_keys_that_are_not_stable_identifiers(): void
{
$this->expectException(InvalidArgumentException::class);
new WidgetRegistry([$this->customWidget('Teaser Box')]);
}
public function test_a_new_widget_type_works_through_the_contract_alone(): void
{
$registry = new WidgetRegistry([$this->customWidget('teaser')]);
$this->app->instance(WidgetRegistry::class, $registry);
$stored = $registry->normalize([
['type' => 'teaser', 'v' => 1, 'variant' => 'wide', 'data' => ['heading' => 'Neu']],
]);
$this->assertSame('teaser', $stored[0]['type']);
$this->assertSame('wide', $stored[0]['variant']);
$this->assertSame(['heading' => 'Neu'], $stored[0]['data']);
$html = app(WidgetRenderer::class)->renderAll($stored, RenderContext::publicPage())->toHtml();
$this->assertStringContainsString('<h1>Neu</h1>', $html);
$this->assertStringContainsString('widget-variant-wide', $html);
$block = WidgetEditor::block($registry->get('teaser'));
$this->assertSame('teaser', $block->getName());
$this->assertSame('Teaser · Breit – Neu', (string) $block->getLabel(['variant' => 'wide', 'data' => ['heading' => 'Neu']]));
}
public function test_unknown_type_and_unregistered_variant_are_rejected(): void
{
try {
$this->registry()->normalize([['type' => 'html', 'v' => 1, 'data' => ['markup' => '<script></script>']]]);
$this->fail('Unbekannte Art wurde angenommen.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('blocks.0.type', $exception->errors());
}
try {
$this->registry()->normalize([['type' => 'hero', 'v' => 1, 'variant' => 'gross-und-bunt', 'data' => ['heading' => 'X']]]);
$this->fail('Unbekannte Variante wurde angenommen.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('blocks.0.variant', $exception->errors());
}
}
public function test_free_settings_are_rejected(): void
{
$this->expectException(ValidationException::class);
$this->registry()->normalize([
['type' => 'heading', 'v' => 1, 'settings' => ['class' => 'bg-red-500'], 'data' => ['heading' => 'X']],
]);
}
public function test_image_text_requires_an_alternative_text_when_an_image_is_set(): void
{
try {
$this->registry()->normalize([
['type' => 'image_text', 'v' => 2, 'data' => ['body' => '<p>Text</p>'], 'refs' => ['image' => 'cms/bild.jpg']],
]);
$this->fail('Bild ohne Alternativtext wurde angenommen.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('blocks.0.data.alt', $exception->errors());
}
$stored = $this->registry()->normalize([
['type' => 'image_text', 'v' => 2, 'data' => ['body' => '<p>Ohne Bild</p>'], 'refs' => []],
]);
$this->assertNull($stored[0]['refs']['image']);
}
public function test_links_reject_script_urls_in_every_widget(): void
{
$cases = [
['type' => 'call_to_action', 'heading' => 'Weiter', 'label' => 'Öffnen', 'url' => 'javascript:alert(1)'],
['type' => 'cards', 'v' => 1, 'data' => ['items' => [['title' => 'A', 'url' => 'javascript:alert(1)']]]],
['type' => 'hero', 'v' => 1, 'data' => ['heading' => 'A', 'cta_label' => 'Los', 'cta_url' => '//fremd.example/x']],
];
foreach ($cases as $case) {
try {
$this->registry()->normalize([$case]);
$this->fail('Unsichere Adresse wurde angenommen: '.$case['type']);
} catch (ValidationException) {
$this->addToAssertionCount(1);
}
}
}
public function test_images_must_come_from_the_public_website_area(): void
{
$this->expectException(ValidationException::class);
$this->registry()->normalize([
['type' => 'hero', 'v' => 1, 'data' => ['heading' => 'A', 'alt' => 'Bild'], 'refs' => ['image' => 'bibliothek/geschuetzt.jpg']],
]);
}
public function test_formatted_text_is_sanitized_when_saved(): void
{
$stored = $this->registry()->normalize([[
'type' => 'image_text',
'v' => 2,
'data' => ['body' => '<p onclick="x()">Hallo <strong>Welt</strong><script>alert(1)</script> <a href="javascript:alert(1)">böse</a> <a href="/praevention">gut</a></p><iframe src="x"></iframe>'],
]]);
$body = $stored[0]['data']['body'];
$this->assertStringNotContainsString('script', $body);
$this->assertStringNotContainsString('onclick', $body);
$this->assertStringNotContainsString('javascript:', $body);
$this->assertStringNotContainsString('iframe', $body);
$this->assertStringContainsString('<strong>Welt</strong>', $body);
$this->assertStringContainsString('href="/praevention"', $body);
}
public function test_legacy_blocks_are_read_as_version_one_envelopes(): void
{
$widget = $this->registry()->upcast(['type' => 'heading', 'heading' => 'Alt', 'intro' => 'Einleitung']);
$this->assertSame([
'id' => null,
'type' => 'heading',
'v' => 1,
'variant' => 'standard',
'settings' => [],
'data' => ['heading' => 'Alt', 'intro' => 'Einleitung'],
'refs' => [],
], $widget);
}
public function test_legacy_image_text_is_upgraded_to_version_two_on_read(): void
{
$legacy = ['type' => 'image_text', 'image' => 'cms/alt.jpg', 'alt' => 'Kinder im Kreis', 'body' => "Erster Absatz & mehr.\n\nZweiter <Absatz>."];
$widget = $this->registry()->upcast($legacy);
$this->assertSame(2, $widget['v']);
$this->assertSame('image_left', $widget['variant']);
$this->assertSame(['image' => 'cms/alt.jpg'], $widget['refs']);
$this->assertSame('Kinder im Kreis', $widget['data']['alt']);
$this->assertNull($widget['data']['title']);
$this->assertSame('<p>Erster Absatz &amp; mehr.</p><p>Zweiter &lt;Absatz&gt;.</p>', $widget['data']['body']);
}
public function test_stored_version_one_envelope_is_upgraded_as_well(): void
{
$widget = $this->registry()->upcast([
'id' => 'abc', 'type' => 'image_text', 'v' => 1, 'variant' => 'standard',
'data' => ['image' => null, 'alt' => 'x', 'body' => 'Nur Text'], 'refs' => [],
]);
$this->assertSame(2, $widget['v']);
$this->assertSame('abc', $widget['id']);
$this->assertSame('image_left', $widget['variant']);
$this->assertSame('<p>Nur Text</p>', $widget['data']['body']);
}
public function test_widgets_from_a_newer_schema_cannot_be_saved(): void
{
$this->expectException(ValidationException::class);
$this->registry()->normalize([['type' => 'heading', 'v' => 99, 'data' => ['heading' => 'Zukunft']]]);
}
public function test_read_skips_unknown_types_without_failing(): void
{
$widgets = $this->registry()->read([
['type' => 'gibt_es_nicht', 'v' => 1],
['type' => 'prose', 'body' => 'Bleibt lesbar'],
]);
$this->assertCount(1, $widgets);
$this->assertSame('prose', $widgets[0]['type']);
}
public function test_ids_are_kept_and_duplicates_get_new_ids(): void
{
$stored = $this->registry()->normalize([
['id' => 'erster', 'type' => 'heading', 'v' => 1, 'data' => ['heading' => 'A']],
['id' => 'erster', 'type' => 'heading', 'v' => 1, 'data' => ['heading' => 'Kopie']],
['type' => 'prose', 'body' => 'Ohne Kennung'],
]);
$this->assertSame('erster', $stored[0]['id']);
$this->assertNotSame('erster', $stored[1]['id']);
$this->assertNotEmpty($stored[2]['id']);
$this->assertNotSame($stored[1]['id'], $stored[2]['id']);
}
public function test_only_declared_fields_are_stored(): void
{
$stored = $this->registry()->normalize([[
'type' => 'cards',
'v' => 1,
'data' => ['items' => [['title' => 'A', 'price' => '99 €', 'url' => '/a']], 'license' => 'alle'],
'refs' => ['offer' => 7],
]]);
$this->assertSame(['items' => [['title' => 'A', 'text' => null, 'url' => '/a', 'image' => null]]], $stored[0]['data']);
$this->assertSame([], $stored[0]['refs']);
}
public function test_rich_text_from_plain_text_escapes_markup(): void
{
$this->assertSame('<p>&lt;b&gt;fett&lt;/b&gt;</p>', RichText::fromPlainText('<b>fett</b>'));
$this->assertSame('', RichText::fromPlainText(" \n "));
}
private function customWidget(string $key): WidgetType
{
return new class($key) extends WidgetType
{
public function __construct(private readonly string $widgetKey) {}
public function key(): string
{
return $this->widgetKey;
}
public function label(): string
{
return 'Teaser';
}
public function description(): string
{
return 'Testwidget';
}
public function variants(): array
{
return ['standard' => 'Standard', 'wide' => 'Breit'];
}
public function dataRules(): array
{
return ['heading' => ['required', 'string', 'max:50']];
}
public function dataFields(): array
{
return [TextInput::make('heading')];
}
public function view(): string
{
return 'widgets.heading';
}
public function summary(array $widget): string
{
return (string) ($widget['data']['heading'] ?? '');
}
};
}
}