Führe Abschnitte mit Raster, gemeinsames Designsystem und globales Website-Gerüst ein.
CI Feature / test (push) Failing after 20s
CI Feature / test (push) Failing after 20s
- Seite → Abschnitte → Plätze → Widgets: sechs Raster mit höchstens vier Einheiten, Hintergrund, Breite, Abstand und Trenner als Aufzählungswerte; je Platz ein Widget aus dem bestehenden Register. Neue Spalte page_revisions.sections (ergänzend); blocks erhält weiterhin alle Widgets in Lesereihenfolge als Rollback-Fassung. - Widgets erhalten Mindest- und Vorzugsbreite; Darstellung über Container-Abfragen. - Editor: Abschnitts-Repeater mit grafischer Rasterauswahl, Plätzen im Rasterverhältnis, breiter Arbeitsfläche, kompakten Vorschauen ohne Bildlaufleiste, Meldungen mit Abschnitt und Platz; Rasterwechsel entfernt nie ein Widget. Seite duplizieren. - Designsystem: Marken- und Bedeutungs-Tokens (vorläufig), gemeinsame Grundkomponenten, Nunito/Source Sans 3 lokal; Mitgliederbereich nutzt dieselben Tokens und die Wortmarke. - Kopfzeile, mobile Navigation, Untermenü (parent_id, ergänzend), Fußbereichsgruppen, vorbereiteter Warenkorbzugang (abgeschaltet). Öffentliche Seiten gleich für alle Besucher. - cms:revert-published als Wiederherstellungsweg vor einem Code-Rollback. Die Editor-Tests der ersten Iteration sind bewusst auf den neuen Formularzustand (sections statt blocks) umgestellt; ihre Prüfungen gelten unverändert für die Widgets. Der Vorschautest erwartet keine anmeldeabhängige Kopfzeile mehr (ADR-32). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
db4bd30319
commit
480d55989b
57 files changed
+4730
-818
No files matched your search
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Domain\Cms\Page;
|
||||
use App\Domain\Cms\PageRevision;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Console\Command;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Wiederherstellungsweg vor einem Code-Rollback (docs/architektur/cms-widget-registry.md, Abschnitt Rollback).
|
||||
*
|
||||
* Setzt die veröffentlichte Revision jeder Seite auf die letzte Revision, die vor dem angegebenen Zeitpunkt
|
||||
* gespeichert wurde. Revisionen werden weder geändert noch gelöscht; nur der Veröffentlichungszeiger wechselt.
|
||||
* Ohne --apply wird nur angezeigt, was geschähe.
|
||||
*/
|
||||
class RevertPublishedPages extends Command
|
||||
{
|
||||
protected $signature = 'cms:revert-published
|
||||
{--before= : Zeitpunkt des Deployments, zum Beispiel "2026-11-17 18:00" (Zeitzone der Anwendung)}
|
||||
{--apply : Änderung tatsächlich ausführen}';
|
||||
|
||||
protected $description = 'Setzt veröffentlichte Seiten auf ihren Stand vor einem Zeitpunkt zurück (nur Veröffentlichungszeiger).';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
try {
|
||||
$before = blank($this->option('before')) ? null : CarbonImmutable::parse((string) $this->option('before'));
|
||||
} catch (Throwable) {
|
||||
$before = null;
|
||||
}
|
||||
|
||||
if ($before === null) {
|
||||
$this->error('Bitte --before mit einem gültigen Zeitpunkt angeben.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$apply = (bool) $this->option('apply');
|
||||
$rows = [];
|
||||
|
||||
foreach (Page::query()->whereNotNull('published_revision_id')->with('publishedRevision')->orderBy('path')->get() as $page) {
|
||||
$current = $page->publishedRevision;
|
||||
|
||||
if ($current === null || $current->created_at < $before) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$previous = PageRevision::query()
|
||||
->where('page_id', $page->id)
|
||||
->where('created_at', '<', $before)
|
||||
->latest('id')
|
||||
->first();
|
||||
|
||||
if ($previous === null) {
|
||||
$rows[] = [$page->path, $current->id, '–', 'keine ältere Revision: Seite wird zurückgezogen'];
|
||||
if ($apply) {
|
||||
$page->published_revision_id = null;
|
||||
$page->save();
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$rows[] = [$page->path, $current->id, $previous->id, $apply ? 'zurückgesetzt' : 'würde zurückgesetzt'];
|
||||
if ($apply) {
|
||||
$page->published_revision_id = $previous->id;
|
||||
$page->save();
|
||||
}
|
||||
}
|
||||
|
||||
if ($rows === []) {
|
||||
$this->info('Keine veröffentlichte Seite stammt aus der Zeit ab '.$before->format('d.m.Y H:i').'.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$this->table(['Pfad', 'veröffentlicht', 'neu veröffentlicht', 'Ergebnis'], $rows);
|
||||
|
||||
if (! $apply) {
|
||||
$this->warn('Probelauf. Mit --apply ausführen.');
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,25 @@
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class NavigationItem extends Model
|
||||
{
|
||||
/**
|
||||
* Plätze im globalen Website-Gerüst. Die drei Fußbereichsgruppen ersetzen eine eigene Footer-Verwaltung.
|
||||
*/
|
||||
public const PLACEMENTS = [
|
||||
'header' => 'Kopfzeile',
|
||||
'footer' => 'Fußzeile',
|
||||
'header' => 'Kopfzeile (Hauptnavigation)',
|
||||
'footer' => 'Fußbereich: Service',
|
||||
'footer_contact' => 'Fußbereich: Kontakt',
|
||||
'footer_legal' => 'Fußbereich: Rechtliches',
|
||||
];
|
||||
|
||||
/** Spaltenüberschriften im Fußbereich. */
|
||||
public const FOOTER_GROUPS = [
|
||||
'footer' => 'Service',
|
||||
'footer_contact' => 'Kontakt',
|
||||
'footer_legal' => 'Rechtliches',
|
||||
];
|
||||
|
||||
protected $fillable = [
|
||||
@@ -21,8 +34,19 @@ class NavigationItem extends Model
|
||||
'placement',
|
||||
'sort_order',
|
||||
'is_visible',
|
||||
'parent_id',
|
||||
];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
// Untermenüs gibt es nur in der Hauptnavigation.
|
||||
static::saving(function (NavigationItem $item): void {
|
||||
if ($item->placement !== 'header' && $item->getAttribute('parent_id') !== null) {
|
||||
$item->parent_id = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
@@ -35,6 +59,16 @@ public function page(): BelongsTo
|
||||
return $this->belongsTo(Page::class);
|
||||
}
|
||||
|
||||
public function parent(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(self::class, 'parent_id');
|
||||
}
|
||||
|
||||
public function children(): HasMany
|
||||
{
|
||||
return $this->hasMany(self::class, 'parent_id')->orderBy('sort_order')->orderBy('id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<NavigationItem> $query
|
||||
*/
|
||||
@@ -59,4 +93,22 @@ public function href(): ?string
|
||||
|
||||
return $this->url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pfad des Ziels innerhalb der Website (für die Kennzeichnung des aktiven Eintrags); null bei externen Zielen.
|
||||
*/
|
||||
public function targetPath(): ?string
|
||||
{
|
||||
if ($this->page !== null) {
|
||||
return $this->page->path;
|
||||
}
|
||||
|
||||
if (is_string($this->url) && str_starts_with($this->url, '/') && ! str_starts_with($this->url, '//')) {
|
||||
$path = parse_url($this->url, PHP_URL_PATH);
|
||||
|
||||
return is_string($path) ? '/'.trim($path, '/') : null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace App\Domain\Cms;
|
||||
|
||||
use App\Domain\Cms\Widgets\WidgetRegistry;
|
||||
use App\Domain\Cms\Sections\PageSections;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
@@ -14,6 +14,7 @@ class PageRevision extends Model
|
||||
protected $fillable = [
|
||||
'page_id',
|
||||
'blocks',
|
||||
'sections',
|
||||
'seo_title',
|
||||
'seo_description',
|
||||
'created_by',
|
||||
@@ -23,6 +24,7 @@ protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'blocks' => 'array',
|
||||
'sections' => 'array',
|
||||
'created_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
@@ -38,13 +40,24 @@ public function author(): BelongsTo
|
||||
}
|
||||
|
||||
/**
|
||||
* Bausteine als aktuelle Widget-Hüllen. Die gespeicherten Daten bleiben unverändert.
|
||||
* Abschnitte als aktuelle Hüllen. Revisionen ohne Abschnitte (vor Einführung des Rasters) werden als
|
||||
* einspaltige Abschnitte gelesen. Die gespeicherten Daten bleiben unverändert.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function sections(): array
|
||||
{
|
||||
return app(PageSections::class)->read($this->sections, $this->blocks);
|
||||
}
|
||||
|
||||
/**
|
||||
* Widgets in Lesereihenfolge als aktuelle Hüllen.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function widgets(): array
|
||||
{
|
||||
return app(WidgetRegistry::class)->read($this->blocks);
|
||||
return app(PageSections::class)->flatten($this->sections());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -52,6 +65,6 @@ public function widgets(): array
|
||||
*/
|
||||
public function contentTitle(): ?string
|
||||
{
|
||||
return app(WidgetRegistry::class)->pageTitle($this->blocks);
|
||||
return app(PageSections::class)->pageTitle($this->sections());
|
||||
}
|
||||
}
|
||||
@@ -2,23 +2,27 @@
|
||||
|
||||
namespace App\Domain\Cms;
|
||||
|
||||
use App\Domain\Cms\Widgets\WidgetRegistry;
|
||||
use App\Domain\Cms\Sections\PageSections;
|
||||
use App\Jobs\PublishPublicMedia;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class PageService
|
||||
{
|
||||
public function __construct(private readonly WidgetRegistry $widgets) {}
|
||||
public function __construct(private readonly PageSections $sections) {}
|
||||
|
||||
/**
|
||||
* Speichert einen Entwurf als neue Revision. Veröffentlicht nichts.
|
||||
*
|
||||
* @param array<int|string, mixed> $blocks Bausteine im Altformat oder als Widget-Hülle
|
||||
* @param array<int|string, mixed> $content Abschnitte mit Slots; flache Widgets (Altformat oder Hülle)
|
||||
* werden als einspaltige Abschnitte übernommen
|
||||
*/
|
||||
public function saveRevision(Page $page, array $blocks, ?string $seoTitle, ?string $seoDescription, ?User $author): PageRevision
|
||||
public function saveRevision(Page $page, array $content, ?string $seoTitle, ?string $seoDescription, ?User $author): PageRevision
|
||||
{
|
||||
return $this->storeRevision($page, $this->widgets->normalize($blocks), $seoTitle, $seoDescription, $author);
|
||||
$sections = $this->sections->normalize($content);
|
||||
|
||||
return $this->storeRevision($page, $this->sections->flatten($sections), $sections, $seoTitle, $seoDescription, $author);
|
||||
}
|
||||
|
||||
public function publish(Page $page, PageRevision $revision): void
|
||||
@@ -34,7 +38,7 @@ public function publish(Page $page, PageRevision $revision): void
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt den Stand einer früheren Revision unverändert als neue Revision an. Die gespeicherten Bausteine
|
||||
* Legt den Stand einer früheren Revision unverändert als neue Revision an. Abschnitte und Bausteine
|
||||
* werden nicht umgeschrieben; ältere Formate werden erst beim Lesen angehoben.
|
||||
*/
|
||||
public function restore(Page $page, PageRevision $source, ?User $author): PageRevision
|
||||
@@ -48,12 +52,33 @@ public function restore(Page $page, PageRevision $source, ?User $author): PageRe
|
||||
return $this->storeRevision(
|
||||
$page,
|
||||
$source->blocks ?? [],
|
||||
$source->sections,
|
||||
$source->seo_title,
|
||||
$source->seo_description,
|
||||
$author,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt eine neue, unveröffentlichte Seite mit dem zuletzt gespeicherten Stand einer vorhandenen Seite an.
|
||||
* Die Vorlage bleibt unverändert; spätere Änderungen wirken nicht auf die Kopie.
|
||||
*/
|
||||
public function duplicate(Page $source, string $path, ?User $author): Page
|
||||
{
|
||||
$revision = $source->latestRevision ?? $source->publishedRevision;
|
||||
$page = Page::query()->create(['path' => $this->availablePath($path)]);
|
||||
|
||||
$this->saveRevision(
|
||||
$page,
|
||||
$revision?->sections() ?? [],
|
||||
$revision?->seo_title,
|
||||
$revision?->seo_description,
|
||||
$author,
|
||||
);
|
||||
|
||||
return $page;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalisiert den Pfad und prüft, dass keine andere Seite ihn verwendet.
|
||||
*/
|
||||
@@ -95,18 +120,27 @@ public function normalizePath(string $path): string
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int|string, mixed> $blocks
|
||||
* @param array<int|string, mixed> $blocks flache Widget-Liste (Rollback-Fassung)
|
||||
* @param array<int|string, mixed>|null $sections Abschnitte; null bei Revisionen aus der Zeit vor dem Raster
|
||||
*/
|
||||
private function storeRevision(Page $page, array $blocks, ?string $seoTitle, ?string $seoDescription, ?User $author): PageRevision
|
||||
private function storeRevision(Page $page, array $blocks, ?array $sections, ?string $seoTitle, ?string $seoDescription, ?User $author): PageRevision
|
||||
{
|
||||
$revision = $page->revisions()->create([
|
||||
$attributes = [
|
||||
'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) {
|
||||
// Die Erstbefüllung der Website läuft innerhalb einer frühen Migration, bevor die Spalte existiert.
|
||||
// Solche Revisionen haben keine Abschnitte und werden beim Lesen als einspaltige Abschnitte gelesen.
|
||||
if ($sections !== null && Schema::hasColumn('page_revisions', 'sections')) {
|
||||
$attributes['sections'] = array_values($sections);
|
||||
}
|
||||
|
||||
$revision = $page->revisions()->create($attributes);
|
||||
|
||||
foreach ($this->sections->mediaPaths($revision->sections()) as $path) {
|
||||
PublishPublicMedia::dispatch($path);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Sections;
|
||||
|
||||
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
||||
use App\Domain\Cms\Widgets\WidgetRegistry;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* Abschnitts- und Slotmodell einer Seite: Seite → Abschnitte → Slots → Widget-Instanzen.
|
||||
*
|
||||
* Gespeicherte Hülle eines Abschnitts (Version 1):
|
||||
* {id, v, layout, style: {background, image, focus, overlay, width, spacing, divider}, slots: [Widget-Hülle|null, …]}
|
||||
*
|
||||
* Jeder Slot enthält höchstens ein Widget aus dem zentralen Widget-Register. Abschnitte sind nicht verschachtelbar.
|
||||
* Revisionen ohne Abschnitte (Bestand vor dieser Fassung) werden beim Lesen als einspaltige Abschnitte gelesen.
|
||||
*/
|
||||
class PageSections
|
||||
{
|
||||
public const VERSION = 1;
|
||||
|
||||
public const MAX_SECTIONS = 30;
|
||||
|
||||
public const MAX_WIDGETS = 60;
|
||||
|
||||
public function __construct(private readonly WidgetRegistry $widgets) {}
|
||||
|
||||
/**
|
||||
* Lesepfad. Unbekannte Werte fallen auf Vorgaben zurück, unbekannte Widget-Arten entfallen.
|
||||
*
|
||||
* @param array<int|string, mixed>|null $sections gespeicherte Abschnitte (Spalte sections)
|
||||
* @param array<int|string, mixed>|null $blocks flache Bausteinliste (Spalte blocks), nur ohne Abschnitte verwendet
|
||||
* @return list<array{id: ?string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
|
||||
*/
|
||||
public function read(?array $sections, ?array $blocks = null): array
|
||||
{
|
||||
if ($sections === null) {
|
||||
return $this->wrapWidgets($blocks ?? []);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
|
||||
foreach (array_values($sections) as $section) {
|
||||
if (is_array($section)) {
|
||||
$result[] = $this->upcastSection($section);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schreibpfad: prüft und bereinigt Abschnitte für eine neue Revision. Flache Widgets (ohne „slots“) werden
|
||||
* als einspaltige Abschnitte übernommen. Alle Fehler der Seite werden gesammelt gemeldet; Schlüssel:
|
||||
* „sections.N.layout“, „sections.N.style.image“, „sections.N.slots“, „sections.N.slots.M.data.feld“.
|
||||
*
|
||||
* @param array<int|string, mixed> $content
|
||||
* @return list<array{id: string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
|
||||
*/
|
||||
public function normalize(array $content): array
|
||||
{
|
||||
$items = array_values($content);
|
||||
|
||||
if (count($items) > self::MAX_SECTIONS) {
|
||||
throw ValidationException::withMessages([
|
||||
'sections' => 'Eine Seite hat höchstens '.self::MAX_SECTIONS.' Abschnitte.',
|
||||
]);
|
||||
}
|
||||
|
||||
$errors = [];
|
||||
$sections = [];
|
||||
$seenSectionIds = [];
|
||||
$seenWidgetIds = [];
|
||||
$widgetCount = 0;
|
||||
|
||||
foreach ($items as $index => $item) {
|
||||
if (! is_array($item)) {
|
||||
$errors["sections.$index"] = ['Ein Abschnitt ist unvollständig.'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! array_key_exists('slots', $item)) {
|
||||
$item = ['id' => null, 'layout' => SectionLayouts::DEFAULT, 'style' => [], 'slots' => [$item]];
|
||||
}
|
||||
|
||||
$sections[] = $this->normalizeSection($item, $index, $errors, $seenSectionIds, $seenWidgetIds, $widgetCount);
|
||||
}
|
||||
|
||||
if ($widgetCount > self::MAX_WIDGETS) {
|
||||
$errors['sections'] = ['Eine Seite enthält höchstens '.self::MAX_WIDGETS.' Widgets.'];
|
||||
}
|
||||
|
||||
if ($errors !== []) {
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
|
||||
return $sections;
|
||||
}
|
||||
|
||||
/**
|
||||
* Widgets in Lesereihenfolge (Abschnitt für Abschnitt, Slot für Slot). Wird zusätzlich als flache
|
||||
* Bausteinliste gespeichert, damit ein Code-Rollback auf die Fassung vor den Abschnitten die Inhalte
|
||||
* weiterhin untereinander darstellt.
|
||||
*
|
||||
* @param list<array<string, mixed>> $sections
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function flatten(array $sections): array
|
||||
{
|
||||
$widgets = [];
|
||||
|
||||
foreach ($sections as $section) {
|
||||
$count = SectionLayouts::slotCount($section['layout']);
|
||||
|
||||
foreach (array_slice($section['slots'], 0, $count) as $widget) {
|
||||
if (is_array($widget)) {
|
||||
$widgets[] = $widget;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $widgets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Öffentliche Medien der Seite: Widget-Bilder und Hintergrundbilder der Abschnitte.
|
||||
*
|
||||
* @param list<array<string, mixed>> $sections
|
||||
* @return list<string>
|
||||
*/
|
||||
public function mediaPaths(array $sections): array
|
||||
{
|
||||
$paths = [];
|
||||
|
||||
foreach ($sections as $section) {
|
||||
$style = SectionStyle::fromStored($section['style'] ?? []);
|
||||
if ($style['image'] !== null && PublicMedia::isPublicPath($style['image'])) {
|
||||
$paths[] = $style['image'];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($this->widgets->mediaPaths($this->flatten($sections)) as $path) {
|
||||
$paths[] = $path;
|
||||
}
|
||||
|
||||
return array_values(array_unique($paths));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $sections
|
||||
*/
|
||||
public function pageTitle(array $sections): ?string
|
||||
{
|
||||
return $this->widgets->pageTitle($this->flatten($sections));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int|string, mixed> $blocks
|
||||
* @return list<array{id: ?string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
|
||||
*/
|
||||
private function wrapWidgets(array $blocks): array
|
||||
{
|
||||
$sections = [];
|
||||
|
||||
foreach ($this->widgets->read($blocks) as $widget) {
|
||||
$sections[] = [
|
||||
'id' => null,
|
||||
'v' => self::VERSION,
|
||||
'layout' => SectionLayouts::DEFAULT,
|
||||
// Bestand vor dem Raster stand in einem durchgehenden Blatt: kompakte Abstände kommen dem am nächsten.
|
||||
'style' => ['spacing' => 'compact'] + SectionStyle::DEFAULTS,
|
||||
'slots' => [$widget],
|
||||
];
|
||||
}
|
||||
|
||||
return $sections;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $section
|
||||
* @return array{id: ?string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
|
||||
*/
|
||||
private function upcastSection(array $section): array
|
||||
{
|
||||
$layout = SectionLayouts::has($section['layout'] ?? null) ? $section['layout'] : SectionLayouts::DEFAULT;
|
||||
$slots = [];
|
||||
|
||||
foreach (array_values(is_array($section['slots'] ?? null) ? $section['slots'] : []) as $slot) {
|
||||
$slots[] = is_array($slot) ? $this->widgets->upcast($slot) : null;
|
||||
}
|
||||
|
||||
while (count($slots) < SectionLayouts::slotCount($layout)) {
|
||||
$slots[] = null;
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => is_string($section['id'] ?? null) ? $section['id'] : null,
|
||||
'v' => self::VERSION,
|
||||
'layout' => $layout,
|
||||
'style' => SectionStyle::fromStored($section['style'] ?? []),
|
||||
'slots' => $slots,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $section
|
||||
* @param array<string, list<string>> $errors
|
||||
* @param array<string, true> $seenSectionIds
|
||||
* @param array<string, true> $seenWidgetIds
|
||||
* @return array{id: string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
|
||||
*/
|
||||
private function normalizeSection(array $section, int $index, array &$errors, array &$seenSectionIds, array &$seenWidgetIds, int &$widgetCount): array
|
||||
{
|
||||
$prefix = "sections.$index";
|
||||
|
||||
$layout = $section['layout'] ?? SectionLayouts::DEFAULT;
|
||||
if (! SectionLayouts::has($layout)) {
|
||||
$errors["$prefix.layout"] = ['Dieses Abschnittsraster ist nicht freigegeben.'];
|
||||
$layout = SectionLayouts::DEFAULT;
|
||||
}
|
||||
|
||||
$style = $this->normalizeStyle(is_array($section['style'] ?? null) ? $section['style'] : [], $prefix, $errors);
|
||||
|
||||
$units = SectionLayouts::units($layout);
|
||||
$rawSlots = array_values(is_array($section['slots'] ?? null) ? $section['slots'] : []);
|
||||
$filled = count(array_filter($rawSlots, fn ($slot): bool => is_array($slot)));
|
||||
|
||||
if ($filled > count($units)) {
|
||||
$errors["$prefix.slots"] = [sprintf(
|
||||
'Das Raster „%s“ hat %d %s, der Abschnitt enthält aber %d Widgets. Entfernen Sie ein Widget oder wählen Sie ein Raster mit mehr Plätzen.',
|
||||
SectionLayouts::short($layout),
|
||||
count($units),
|
||||
count($units) === 1 ? 'Platz' : 'Plätze',
|
||||
$filled,
|
||||
)];
|
||||
} elseif (count($rawSlots) > count($units)) {
|
||||
// Überzählige Plätze sind leer: Widgets rücken in Reihenfolge nach vorn, leere Plätze entfallen.
|
||||
$rawSlots = array_values(array_filter($rawSlots, fn ($slot): bool => is_array($slot)));
|
||||
}
|
||||
|
||||
$slots = [];
|
||||
foreach ($units as $position => $slotUnits) {
|
||||
$block = $rawSlots[$position] ?? null;
|
||||
|
||||
if (! is_array($block)) {
|
||||
$slots[] = null;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$widgetCount++;
|
||||
|
||||
try {
|
||||
$widget = $this->widgets->normalizeWidget($block, "$prefix.slots.$position", $seenWidgetIds);
|
||||
} catch (ValidationException $exception) {
|
||||
foreach ($exception->errors() as $key => $messages) {
|
||||
$errors[$key] = $messages;
|
||||
}
|
||||
$slots[] = null;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$type = $this->widgets->get($widget['type']);
|
||||
if ($slotUnits < $type->minUnits()) {
|
||||
$errors["$prefix.slots.$position.units"] = [sprintf(
|
||||
'„%s“ braucht mindestens %d Rastereinheiten; dieser Platz hat %d. Wählen Sie ein breiteres Raster oder einen breiteren Platz.',
|
||||
$type->label(),
|
||||
$type->minUnits(),
|
||||
$slotUnits,
|
||||
)];
|
||||
}
|
||||
|
||||
$slots[] = $widget;
|
||||
}
|
||||
|
||||
$id = $section['id'] ?? null;
|
||||
if (! is_string($id) || preg_match('/^[A-Za-z0-9-]{1,64}$/', $id) !== 1 || isset($seenSectionIds[$id])) {
|
||||
$id = (string) Str::uuid();
|
||||
}
|
||||
$seenSectionIds[$id] = true;
|
||||
|
||||
return [
|
||||
'id' => $id,
|
||||
'v' => self::VERSION,
|
||||
'layout' => $layout,
|
||||
'style' => $style,
|
||||
'slots' => $slots,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $style
|
||||
* @param array<string, list<string>> $errors
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function normalizeStyle(array $style, string $prefix, array &$errors): array
|
||||
{
|
||||
$result = SectionStyle::DEFAULTS;
|
||||
$enums = SectionStyle::enums();
|
||||
|
||||
foreach ($style as $key => $value) {
|
||||
if ($key === 'image' || str_starts_with((string) $key, '_')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! isset($enums[$key])) {
|
||||
$errors["$prefix.style.$key"] = ['Diese Gestaltungsoption ist nicht freigegeben.'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($value === null || $value === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! is_string($value) || ! array_key_exists($value, $enums[$key])) {
|
||||
$errors["$prefix.style.$key"] = ['Dieser Gestaltungswert ist nicht freigegeben.'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$result[$key] = $value;
|
||||
}
|
||||
|
||||
$upload = PublicMedia::fromUploadState($style['_upload'] ?? null);
|
||||
$image = $upload ?? PublicMedia::fromUploadState($style['image'] ?? null);
|
||||
|
||||
if ($result['background'] === 'image') {
|
||||
if ($image === null) {
|
||||
$errors["$prefix.style.image"] = ['Bitte ein Hintergrundbild wählen oder hochladen.'];
|
||||
} elseif (! PublicMedia::isPublicPath($image)) {
|
||||
$errors["$prefix.style.image"] = ['Das Hintergrundbild liegt nicht im öffentlichen Medienbereich.'];
|
||||
}
|
||||
|
||||
$result['image'] = $image;
|
||||
} else {
|
||||
$result['image'] = null;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Sections;
|
||||
|
||||
/**
|
||||
* Freigegebene Abschnittsraster. Ein Raster teilt die Abschnittsbreite in höchstens vier logische Einheiten.
|
||||
* Die Kennungen sind gespeichert und ändern sich nie; neue Raster werden ergänzt, nicht umbenannt.
|
||||
*
|
||||
* Die Einheiten werden nicht als eigenes CSS-Grundraster umgesetzt, sondern als Spaltenverhältnis (fr)
|
||||
* des Abschnittsrasters. Leere Slots entfallen auf der veröffentlichten Seite; die übrigen Slots teilen
|
||||
* sich die Breite im Verhältnis ihrer Einheiten.
|
||||
*/
|
||||
final class SectionLayouts
|
||||
{
|
||||
public const DEFAULT = 'u4';
|
||||
|
||||
/** @var array<string, list<int>> */
|
||||
public const UNITS = [
|
||||
'u4' => [4],
|
||||
'u2_2' => [2, 2],
|
||||
'u1_3' => [1, 3],
|
||||
'u3_1' => [3, 1],
|
||||
'u1_2_1' => [1, 2, 1],
|
||||
'u1_1_1_1' => [1, 1, 1, 1],
|
||||
];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const LABELS = [
|
||||
'u4' => 'Volle Breite',
|
||||
'u2_2' => 'Zwei gleich breit',
|
||||
'u1_3' => 'Schmal und breit',
|
||||
'u3_1' => 'Breit und schmal',
|
||||
'u1_2_1' => 'Mitte betont',
|
||||
'u1_1_1_1' => 'Vier gleich breit',
|
||||
];
|
||||
|
||||
public static function has(mixed $key): bool
|
||||
{
|
||||
return is_string($key) && isset(self::UNITS[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<int>
|
||||
*/
|
||||
public static function units(string $key): array
|
||||
{
|
||||
return self::UNITS[$key] ?? self::UNITS[self::DEFAULT];
|
||||
}
|
||||
|
||||
public static function slotCount(string $key): int
|
||||
{
|
||||
return count(self::units($key));
|
||||
}
|
||||
|
||||
/** Kurzform wie „1 + 3“. */
|
||||
public static function short(string $key): string
|
||||
{
|
||||
return implode(' + ', self::units($key));
|
||||
}
|
||||
|
||||
public static function label(string $key): string
|
||||
{
|
||||
return (self::LABELS[$key] ?? self::LABELS[self::DEFAULT]).' ('.self::short($key).')';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function options(): array
|
||||
{
|
||||
$options = [];
|
||||
foreach (array_keys(self::UNITS) as $key) {
|
||||
$options[$key] = self::label($key);
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spaltenvorlagen für die Slots, die tatsächlich etwas darstellen.
|
||||
*
|
||||
* - Desktop (Abschnitt ab 60rem): Verhältnis der Einheiten.
|
||||
* - Tablet (ab 40rem): gleich breite Slots bleiben nebeneinander (zwei oder drei Spalten, vier Slots als 2 × 2);
|
||||
* ungleiche Raster stapeln, damit kein Slot unter etwa 13rem fällt.
|
||||
* - Smartphone: immer eine Spalte. Die Lese- und Fokusreihenfolge bleibt die Reihenfolge der Slots.
|
||||
*
|
||||
* @param list<int> $units
|
||||
* @return array{lg: string, md: string}
|
||||
*/
|
||||
public static function columns(array $units): array
|
||||
{
|
||||
$units = array_values(array_filter($units, fn ($unit): bool => is_int($unit) && $unit > 0));
|
||||
$count = count($units);
|
||||
|
||||
if ($count <= 1) {
|
||||
return ['lg' => 'minmax(0, 1fr)', 'md' => 'minmax(0, 1fr)'];
|
||||
}
|
||||
|
||||
$lg = implode(' ', array_map(fn (int $unit): string => "minmax(0, {$unit}fr)", $units));
|
||||
$equal = count(array_unique($units)) === 1;
|
||||
|
||||
$md = match (true) {
|
||||
! $equal => 'minmax(0, 1fr)',
|
||||
$count === 3 => 'repeat(3, minmax(0, 1fr))',
|
||||
default => 'repeat(2, minmax(0, 1fr))',
|
||||
};
|
||||
|
||||
return ['lg' => $lg, 'md' => $md];
|
||||
}
|
||||
|
||||
/**
|
||||
* Symbolbild des Rasters für die grafische Auswahl im Editor (rein dekorativ).
|
||||
*/
|
||||
public static function schematicSvg(string $key): string
|
||||
{
|
||||
$units = self::units($key);
|
||||
$gap = 2;
|
||||
$width = 56 - $gap * (count($units) - 1);
|
||||
$x = 2;
|
||||
$rects = '';
|
||||
|
||||
foreach ($units as $unit) {
|
||||
$w = (int) round($width * $unit / 4);
|
||||
$rects .= sprintf('<rect x="%d" y="4" width="%d" height="20" rx="1.5"/>', $x, $w);
|
||||
$x += $w + $gap;
|
||||
}
|
||||
|
||||
return '<svg class="luf-layout-schematic" viewBox="0 0 60 28" width="60" height="28" aria-hidden="true" focusable="false">'.$rects.'</svg>';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Sections;
|
||||
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
||||
use App\Domain\Cms\Widgets\WidgetRenderer;
|
||||
use Illuminate\Support\HtmlString;
|
||||
|
||||
/**
|
||||
* Einziger Darstellungsweg für Abschnitte: öffentliche Seite und Seitenvorschau rufen denselben Renderer auf.
|
||||
*
|
||||
* Regeln:
|
||||
* - Leere Slots erzeugen keine Leerfläche; die übrigen Slots teilen sich die Breite im Verhältnis ihrer Einheiten.
|
||||
* - Ein Abschnitt ohne darstellbares Widget entfällt samt Hintergrund und Trenner.
|
||||
* - Das erste dargestellte Widget der Seite ist der Seiteneinstieg (Überschrift erster Ordnung).
|
||||
* - Trenner stehen zwischen Abschnitten, nie nach dem letzten.
|
||||
*/
|
||||
class SectionRenderer
|
||||
{
|
||||
public function __construct(private readonly WidgetRenderer $widgets) {}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $sections gelesene Abschnitte (PageSections::read)
|
||||
*/
|
||||
public function renderAll(array $sections, RenderContext $context): HtmlString
|
||||
{
|
||||
$rendered = [];
|
||||
$first = true;
|
||||
|
||||
foreach ($sections as $section) {
|
||||
$cells = [];
|
||||
$units = SectionLayouts::units($section['layout']);
|
||||
|
||||
foreach ($units as $position => $slotUnits) {
|
||||
$widget = $section['slots'][$position] ?? null;
|
||||
|
||||
if (! is_array($widget)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$html = $this->widgets->renderWidget($widget, $context, $first);
|
||||
|
||||
if ($html !== '') {
|
||||
$first = false;
|
||||
$cells[] = ['units' => $slotUnits, 'html' => $html];
|
||||
}
|
||||
}
|
||||
|
||||
if ($cells !== []) {
|
||||
$rendered[] = ['section' => $section, 'cells' => $cells];
|
||||
}
|
||||
}
|
||||
|
||||
$html = '';
|
||||
$last = count($rendered) - 1;
|
||||
|
||||
foreach ($rendered as $index => $item) {
|
||||
$html .= $this->renderSection($item['section'], $item['cells'], $index);
|
||||
|
||||
$divider = $item['section']['style']['divider'] ?? 'none';
|
||||
if ($index < $last && in_array($divider, ['line', 'accent'], true)) {
|
||||
$html .= '<div class="section-divider section-divider-'.$divider.'" aria-hidden="true"><span></span></div>';
|
||||
}
|
||||
}
|
||||
|
||||
return new HtmlString($html);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $section
|
||||
* @param list<array{units: int, html: string}> $cells
|
||||
*/
|
||||
private function renderSection(array $section, array $cells, int $index): string
|
||||
{
|
||||
$style = SectionStyle::fromStored($section['style'] ?? []);
|
||||
$columns = SectionLayouts::columns(array_column($cells, 'units'));
|
||||
$hasImage = $style['background'] === 'image' && $style['image'] !== null && PublicMedia::isPublicPath($style['image']);
|
||||
|
||||
$classes = [
|
||||
'page-section',
|
||||
'section-bg-'.($hasImage ? 'image' : ($style['background'] === 'image' ? 'default' : $style['background'])),
|
||||
'section-width-'.$style['width'],
|
||||
'section-space-'.$style['spacing'],
|
||||
'section-layout-'.str_replace('_', '-', $section['layout']),
|
||||
];
|
||||
|
||||
if ($hasImage) {
|
||||
$classes[] = 'section-overlay-'.$style['overlay'];
|
||||
}
|
||||
|
||||
// Bedeutungswerte der Fläche (tokens.css): helle Schrift auf dunklen Flächen, gelber Fokus.
|
||||
$scope = match (true) {
|
||||
$hasImage && $style['overlay'] === 'dark' => 'scope-dark',
|
||||
$hasImage => 'scope-light',
|
||||
$style['background'] === 'dark' => 'scope-dark',
|
||||
$style['background'] === 'accent' => 'scope-accent',
|
||||
default => null,
|
||||
};
|
||||
if ($scope !== null) {
|
||||
$classes[] = $scope;
|
||||
}
|
||||
|
||||
if ($style['divider'] === 'space') {
|
||||
$classes[] = 'section-divider-space';
|
||||
}
|
||||
|
||||
$id = is_string($section['id'] ?? null) ? ' id="bereich-'.e($section['id']).'"' : '';
|
||||
$html = '<div class="'.e(implode(' ', $classes)).'"'.$id.'>';
|
||||
|
||||
if ($hasImage) {
|
||||
// Das Bild des ersten Abschnitts ist meist das größte sichtbare Element und wird nicht verzögert geladen.
|
||||
$loading = $index === 0 ? 'loading="eager" fetchpriority="high"' : 'loading="lazy"';
|
||||
$html .= '<img class="page-section-image" src="'.e(PublicMedia::url($style['image'])).'" alt="" '.$loading.' decoding="async"'
|
||||
.' style="object-position: '.e(SectionStyle::FOCUS_POSITIONS[$style['focus']]).'">';
|
||||
}
|
||||
|
||||
$html .= '<div class="page-section-inner"><div class="section-grid" data-slots="'.count($cells).'"'
|
||||
.' style="--section-cols-lg: '.e($columns['lg']).'; --section-cols-md: '.e($columns['md']).'">';
|
||||
|
||||
foreach ($cells as $cell) {
|
||||
$html .= '<div class="section-slot" data-units="'.$cell['units'].'">'.$cell['html'].'</div>';
|
||||
}
|
||||
|
||||
return $html.'</div></div></div>';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Sections;
|
||||
|
||||
/**
|
||||
* Semantische Abschnittsgestaltung. Jeder Wert ist eine Aufzählung, die auf zentrale Design-Tokens
|
||||
* abgebildet wird (resources/css/app.css, Abschnitt „Abschnitte“). Keine freie CSS- oder Farbangabe.
|
||||
*/
|
||||
final class SectionStyle
|
||||
{
|
||||
/** @var array<string, string> */
|
||||
public const BACKGROUNDS = [
|
||||
'default' => 'Standard (ohne eigene Fläche)',
|
||||
'light' => 'Helle Markenfläche',
|
||||
'dark' => 'Dunkle Markenfläche',
|
||||
'accent' => 'Markenakzent',
|
||||
'image' => 'Hintergrundbild',
|
||||
];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const WIDTHS = [
|
||||
'narrow' => 'Schmal (Lesebreite)',
|
||||
'standard' => 'Standard',
|
||||
'wide' => 'Breit',
|
||||
'full' => 'Volle Breite',
|
||||
];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const SPACINGS = [
|
||||
'compact' => 'Kompakt',
|
||||
'normal' => 'Normal',
|
||||
'large' => 'Großzügig',
|
||||
];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const DIVIDERS = [
|
||||
'none' => 'Kein Trenner',
|
||||
'space' => 'Zusätzlicher Abstand',
|
||||
'line' => 'Dezente Linie',
|
||||
'accent' => 'Markenakzent',
|
||||
];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const OVERLAYS = [
|
||||
'light' => 'Helle Überlagerung (dunkle Schrift)',
|
||||
'dark' => 'Dunkle Überlagerung (helle Schrift)',
|
||||
'none' => 'Keine Überlagerung',
|
||||
];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const FOCUS = [
|
||||
'center' => 'Mitte',
|
||||
'top' => 'Oben',
|
||||
'bottom' => 'Unten',
|
||||
'left' => 'Links',
|
||||
'right' => 'Rechts',
|
||||
'top_left' => 'Oben links',
|
||||
'top_right' => 'Oben rechts',
|
||||
'bottom_left' => 'Unten links',
|
||||
'bottom_right' => 'Unten rechts',
|
||||
];
|
||||
|
||||
/** Fokuspunkt als Objektposition des Bildes; bestimmt den Zuschnitt auf schmalen Bildschirmen. */
|
||||
public const FOCUS_POSITIONS = [
|
||||
'center' => '50% 50%',
|
||||
'top' => '50% 0%',
|
||||
'bottom' => '50% 100%',
|
||||
'left' => '0% 50%',
|
||||
'right' => '100% 50%',
|
||||
'top_left' => '0% 0%',
|
||||
'top_right' => '100% 0%',
|
||||
'bottom_left' => '0% 100%',
|
||||
'bottom_right' => '100% 100%',
|
||||
];
|
||||
|
||||
public const DEFAULTS = [
|
||||
'background' => 'default',
|
||||
'image' => null,
|
||||
'focus' => 'center',
|
||||
'overlay' => 'light',
|
||||
'width' => 'standard',
|
||||
'spacing' => 'normal',
|
||||
'divider' => 'none',
|
||||
];
|
||||
|
||||
/**
|
||||
* Aufzählungsfelder und ihre zulässigen Werte.
|
||||
*
|
||||
* @return array<string, array<string, string>>
|
||||
*/
|
||||
public static function enums(): array
|
||||
{
|
||||
return [
|
||||
'background' => self::BACKGROUNDS,
|
||||
'focus' => self::FOCUS,
|
||||
'overlay' => self::OVERLAYS,
|
||||
'width' => self::WIDTHS,
|
||||
'spacing' => self::SPACINGS,
|
||||
'divider' => self::DIVIDERS,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Lesepfad: gespeicherte Werte; Unbekanntes fällt auf die Vorgabe zurück, damit alte oder fremde Daten
|
||||
* nie eine Seite brechen.
|
||||
*
|
||||
* @return array{background: string, image: ?string, focus: string, overlay: string, width: string, spacing: string, divider: string}
|
||||
*/
|
||||
public static function fromStored(mixed $style): array
|
||||
{
|
||||
$style = is_array($style) ? $style : [];
|
||||
$result = self::DEFAULTS;
|
||||
|
||||
foreach (self::enums() as $key => $options) {
|
||||
$value = $style[$key] ?? null;
|
||||
if (is_string($value) && array_key_exists($value, $options)) {
|
||||
$result[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$result['image'] = $result['background'] === 'image' && is_string($style['image'] ?? null) ? $style['image'] : null;
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kurzbeschreibung für die Abschnittsliste im Editor.
|
||||
*
|
||||
* @param array<string, mixed> $style
|
||||
*/
|
||||
public static function summary(array $style): string
|
||||
{
|
||||
$style = self::fromStored($style);
|
||||
$parts = [self::BACKGROUNDS[$style['background']]];
|
||||
|
||||
if ($style['width'] !== 'standard') {
|
||||
$parts[] = self::WIDTHS[$style['width']];
|
||||
}
|
||||
|
||||
if ($style['spacing'] !== 'normal') {
|
||||
$parts[] = 'Abstand '.mb_strtolower(self::SPACINGS[$style['spacing']]);
|
||||
}
|
||||
|
||||
if ($style['divider'] !== 'none') {
|
||||
$parts[] = 'Trenner: '.self::DIVIDERS[$style['divider']];
|
||||
}
|
||||
|
||||
return implode(' · ', $parts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Baut Kopf- und Fußnavigation aus dem CMS-Navigationsmodell. Keine fest codierten Menüpunkte.
|
||||
*
|
||||
* Die Ausgabe hängt nur von der Navigation und dem angefragten Pfad ab, nie vom Anmeldestatus,
|
||||
* damit öffentliche Seiten für alle Besucher gleich ausgeliefert werden können (ADR-32).
|
||||
*/
|
||||
final class SiteNavigation
|
||||
{
|
||||
/**
|
||||
* @param Collection<int, NavigationItem> $items sichtbare Einträge, sortiert
|
||||
*/
|
||||
public function __construct(private readonly Collection $items, private readonly string $currentPath) {}
|
||||
|
||||
/**
|
||||
* @param Collection<int, NavigationItem> $items
|
||||
*/
|
||||
public static function forPath(Collection $items, string $path): self
|
||||
{
|
||||
return new self($items, '/'.trim($path, '/'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Hauptnavigation mit einer Ebene Untermenü. Untereinträge eines ausgeblendeten Eintrags sind ebenfalls verborgen.
|
||||
*
|
||||
* @return list<array{id: int, label: string, href: ?string, current: bool, activeTrail: bool, children: list<array{id: int, label: string, href: string, current: bool}>}>
|
||||
*/
|
||||
public function header(): array
|
||||
{
|
||||
$topLevel = $this->items->where('placement', 'header')->whereNull('parent_id');
|
||||
$entries = [];
|
||||
|
||||
foreach ($topLevel as $item) {
|
||||
$children = [];
|
||||
|
||||
foreach ($this->items->where('parent_id', $item->id) as $child) {
|
||||
$href = $child->href();
|
||||
if ($href !== null) {
|
||||
$children[] = [
|
||||
'id' => $child->id,
|
||||
'label' => $child->label,
|
||||
'href' => $href,
|
||||
'current' => $this->isCurrent($child),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$href = $item->href();
|
||||
if ($href === null && $children === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$current = $href !== null && $this->isCurrent($item);
|
||||
|
||||
$entries[] = [
|
||||
'id' => $item->id,
|
||||
'label' => $item->label,
|
||||
'href' => $href,
|
||||
'current' => $current,
|
||||
'activeTrail' => $current || in_array(true, array_column($children, 'current'), true),
|
||||
'children' => $children,
|
||||
];
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spalten des Fußbereichs in fester Reihenfolge; Gruppen ohne Einträge entfallen.
|
||||
*
|
||||
* @return list<array{key: string, heading: string, links: list<array{label: string, href: string, current: bool}>}>
|
||||
*/
|
||||
public function footerGroups(): array
|
||||
{
|
||||
$groups = [];
|
||||
|
||||
foreach (NavigationItem::FOOTER_GROUPS as $placement => $heading) {
|
||||
$links = [];
|
||||
|
||||
foreach ($this->items->where('placement', $placement) as $item) {
|
||||
$href = $item->href();
|
||||
if ($href !== null) {
|
||||
$links[] = ['label' => $item->label, 'href' => $href, 'current' => $this->isCurrent($item)];
|
||||
}
|
||||
}
|
||||
|
||||
if ($links !== []) {
|
||||
$groups[] = ['key' => $placement, 'heading' => $heading, 'links' => $links];
|
||||
}
|
||||
}
|
||||
|
||||
return $groups;
|
||||
}
|
||||
|
||||
private function isCurrent(NavigationItem $item): bool
|
||||
{
|
||||
return $item->targetPath() === $this->currentPath;
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,23 @@ public function description(): string
|
||||
return 'Hervorgehobene Fläche mit Überschrift, Text und einer Schaltfläche.';
|
||||
}
|
||||
|
||||
public function minUnits(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
{
|
||||
return [
|
||||
'fluid' => 'Text und Schaltfläche untereinander, Schaltfläche volle Breite unter 20rem',
|
||||
];
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
{
|
||||
return 'heroicon-o-megaphone';
|
||||
|
||||
@@ -35,6 +35,24 @@ public function description(): string
|
||||
return 'Mehrere Karten mit Titel, Text, Linkziel und optionalem Bild. Als Raster oder kompakte Liste.';
|
||||
}
|
||||
|
||||
public function minUnits(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
{
|
||||
return [
|
||||
'narrow' => 'eine Karte je Zeile',
|
||||
'wide' => 'so viele Karten nebeneinander, wie bei mindestens 14rem Kartenbreite passen',
|
||||
];
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
{
|
||||
return 'heroicon-o-squares-2x2';
|
||||
|
||||
@@ -37,6 +37,24 @@ public function description(): string
|
||||
return 'Ausgewählte Programme und Module; Titel und Beschreibung kommen automatisch aus den Fachdaten.';
|
||||
}
|
||||
|
||||
public function minUnits(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
{
|
||||
return [
|
||||
'narrow' => 'eine Karte je Zeile, Symbolfläche über dem Text',
|
||||
'wide' => 'mehrere Karten nebeneinander ab 16rem Kartenbreite',
|
||||
];
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
{
|
||||
return 'heroicon-o-rectangle-stack';
|
||||
|
||||
@@ -24,6 +24,23 @@ public function description(): string
|
||||
return 'Häufige Fragen mit Antworten.';
|
||||
}
|
||||
|
||||
public function minUnits(): int
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
{
|
||||
return [
|
||||
'fluid' => 'Fragen untereinander; Antwortlänge auf Lesebreite begrenzt',
|
||||
];
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
{
|
||||
return 'heroicon-o-question-mark-circle';
|
||||
|
||||
@@ -23,6 +23,23 @@ public function description(): string
|
||||
return 'Abschnittsüberschrift mit kurzem Einleitungstext.';
|
||||
}
|
||||
|
||||
public function minUnits(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
{
|
||||
return [
|
||||
'fluid' => 'Überschriftgröße folgt der Slotbreite',
|
||||
];
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
{
|
||||
return 'heroicon-o-h1';
|
||||
|
||||
@@ -30,6 +30,24 @@ public function description(): string
|
||||
return 'Großer Seiteneinstieg mit Überschrift, Beschreibung, optionalem Bild und optionaler Schaltfläche.';
|
||||
}
|
||||
|
||||
public function minUnits(): int
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
{
|
||||
return [
|
||||
'narrow' => 'unter 48rem Slotbreite: Bild unter dem Text',
|
||||
'wide' => 'ab 48rem: Bild neben dem Text, größere Überschrift',
|
||||
];
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
{
|
||||
return 'heroicon-o-sparkles';
|
||||
|
||||
@@ -35,6 +35,24 @@ public function description(): string
|
||||
return 'Bild neben formatiertem Text; Bild links oder rechts, auf dem Smartphone untereinander.';
|
||||
}
|
||||
|
||||
public function minUnits(): int
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
{
|
||||
return [
|
||||
'narrow' => 'unter 36rem Slotbreite: Bild über dem Text',
|
||||
'wide' => 'ab 36rem: Bild links oder rechts neben dem Text',
|
||||
];
|
||||
}
|
||||
|
||||
public function version(): int
|
||||
{
|
||||
return 2;
|
||||
|
||||
@@ -23,6 +23,23 @@ public function description(): string
|
||||
return 'Längerer Text in Absätzen. Eine Leerzeile beginnt einen neuen Absatz.';
|
||||
}
|
||||
|
||||
public function minUnits(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
{
|
||||
return [
|
||||
'fluid' => 'Zeilenlänge höchstens etwa 70 Zeichen',
|
||||
];
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
{
|
||||
return 'heroicon-o-bars-3-bottom-left';
|
||||
|
||||
@@ -45,6 +45,10 @@ public function register(WidgetType $type): void
|
||||
throw new InvalidArgumentException("Widget „{$key}“ braucht eine Schemaversion ab 1.");
|
||||
}
|
||||
|
||||
if ($type->minUnits() < 1 || $type->minUnits() > 4 || $type->preferredUnits() < $type->minUnits() || $type->preferredUnits() > 4) {
|
||||
throw new InvalidArgumentException("Widget „{$key}“ braucht eine Mindest- und Vorzugsbreite zwischen 1 und 4 Rastereinheiten.");
|
||||
}
|
||||
|
||||
if ($type->variants() === []) {
|
||||
throw new InvalidArgumentException("Widget „{$key}“ braucht mindestens eine Darstellungsvariante.");
|
||||
}
|
||||
@@ -137,7 +141,7 @@ public function upcast(array $block): ?array
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft und bereinigt Bausteine für eine neue Revision.
|
||||
* Prüft und bereinigt eine flache Bausteinliste (Fehlerschlüssel "blocks.N…").
|
||||
*
|
||||
* @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>}>
|
||||
@@ -148,42 +152,53 @@ public function normalize(array $blocks): array
|
||||
$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);
|
||||
$normalized[] = $this->normalizeWidget($block, "blocks.$index", $seenIds);
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft und bereinigt einen einzelnen Baustein für eine neue Revision. Der Aufrufer führt die Menge
|
||||
* bereits vergebener Kennungen über die ganze Seite, damit kopierte Widgets neue Kennungen erhalten.
|
||||
*
|
||||
* @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>}
|
||||
*/
|
||||
public function normalizeWidget(mixed $block, string $errorPrefix, array &$seenIds): array
|
||||
{
|
||||
if (! is_array($block)) {
|
||||
throw ValidationException::withMessages([
|
||||
$errorPrefix => 'Ein Baustein ist unvollständig.',
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $this->has($block['type'] ?? null)) {
|
||||
throw ValidationException::withMessages([
|
||||
"$errorPrefix.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([
|
||||
"$errorPrefix.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([
|
||||
"$errorPrefix.variant" => 'Diese Darstellungsvariante ist für den Baustein nicht freigegeben.',
|
||||
]);
|
||||
}
|
||||
|
||||
return $this->validateOne($type, $this->upcast($block), $errorPrefix, $seenIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gespeicherte Bausteine einer Revision als aktuelle Hüllen; unbekannte Arten entfallen.
|
||||
*
|
||||
@@ -241,7 +256,7 @@ public function mediaPaths(?array $blocks): array
|
||||
* @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
|
||||
private function validateOne(WidgetType $type, array $widget, string $errorPrefix, array &$seenIds): array
|
||||
{
|
||||
$errors = new WidgetErrors;
|
||||
|
||||
@@ -292,7 +307,7 @@ private function validateOne(WidgetType $type, array $widget, int $index, array
|
||||
if (! $errors->isEmpty()) {
|
||||
$messages = [];
|
||||
foreach ($errors->all() as $key => $list) {
|
||||
$messages["blocks.$index.$key"] = $list;
|
||||
$messages["$errorPrefix.$key"] = $list;
|
||||
}
|
||||
|
||||
throw ValidationException::withMessages($messages);
|
||||
|
||||
@@ -34,6 +34,32 @@ public function version(): int
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kleinste Slotbreite in logischen Rastereinheiten (1 bis 4), in der das Widget auf dem Desktop lesbar bleibt.
|
||||
* Ein schmalerer Slot wird beim Speichern abgewiesen. Auf Tablet und Smartphone stapeln die Slots ohnehin.
|
||||
*/
|
||||
public function minUnits(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
/** Empfohlene Slotbreite in Rastereinheiten; Hinweis in der Widget-Auswahl. */
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
/**
|
||||
* Darstellungsstufen nach verfügbarer Breite (Container-Abfragen in der Widget-Ansicht): Kennung => Beschreibung.
|
||||
* Dokumentiert, wie sich das Widget an schmale und breite Slots anpasst.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function stages(): array
|
||||
{
|
||||
return ['fluid' => 'passt sich fließend an jede Slotbreite an'];
|
||||
}
|
||||
|
||||
/** Heroicon-Name für Auswahl und Liste im Editor. */
|
||||
public function icon(): string
|
||||
{
|
||||
|
||||
@@ -40,7 +40,31 @@ public static function form(Schema $schema): Schema
|
||||
->label('Platz')
|
||||
->options(NavigationItem::PLACEMENTS)
|
||||
->default('header')
|
||||
->required(),
|
||||
->required()
|
||||
->live()
|
||||
->helperText('Kopfzeile: Hauptnavigation. Fußbereich: drei Spalten „Service“, „Kontakt“ und „Rechtliches“.'),
|
||||
Select::make('parent_id')
|
||||
->label('Untermenü von')
|
||||
->placeholder('Oberste Ebene')
|
||||
->options(fn (?NavigationItem $record): array => NavigationItem::query()
|
||||
->where('placement', 'header')
|
||||
->whereNull('parent_id')
|
||||
->when($record !== null, fn ($query) => $query->whereKeyNot($record->getKey()))
|
||||
->orderBy('sort_order')
|
||||
->pluck('label', 'id')
|
||||
->all())
|
||||
->visible(fn (Get $get): bool => $get('placement') === 'header')
|
||||
->disabled(fn (?NavigationItem $record): bool => $record !== null && $record->children()->exists())
|
||||
->helperText('Eine Ebene Untermenü in der Hauptnavigation. Ein Eintrag mit eigenen Untereinträgen bleibt oberste Ebene.')
|
||||
->rule(fn (?NavigationItem $record): Closure => function (string $attribute, mixed $value, Closure $fail) use ($record): void {
|
||||
if (blank($value)) {
|
||||
return;
|
||||
}
|
||||
$parent = NavigationItem::query()->find($value);
|
||||
if ($parent === null || $parent->placement !== 'header' || $parent->parent_id !== null || ($record !== null && $parent->is($record))) {
|
||||
$fail('Untermenüs sind nur unter einem Eintrag der obersten Ebene der Hauptnavigation möglich.');
|
||||
}
|
||||
}),
|
||||
Select::make('page_id')
|
||||
->label('Interne Seite')
|
||||
->options(fn (): array => Page::query()->orderBy('path')->pluck('path', 'id')->all())
|
||||
@@ -51,9 +75,10 @@ public static function form(Schema $schema): Schema
|
||||
->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)) {
|
||||
->rule(function (Get $get, ?NavigationItem $record): Closure {
|
||||
return function (string $attribute, mixed $value, Closure $fail) use ($get, $record): void {
|
||||
// Ein Eintrag mit Untereinträgen darf ohne eigenes Ziel nur das Untermenü öffnen.
|
||||
if (blank($get('page_id')) && blank($value) && ! ($record?->children()->exists() ?? false)) {
|
||||
$fail('Wählen Sie eine Seite oder eine Adresse.');
|
||||
}
|
||||
};
|
||||
@@ -75,7 +100,11 @@ public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('label')->label('Beschriftung')->searchable(),
|
||||
TextColumn::make('label')
|
||||
->label('Beschriftung')
|
||||
->searchable()
|
||||
->formatStateUsing(fn (string $state, NavigationItem $record): string => $record->parent_id !== null ? '↳ '.$state : $state)
|
||||
->description(fn (NavigationItem $record): ?string => $record->parent !== null ? 'Untermenü von „'.$record->parent->label.'“' : null),
|
||||
TextColumn::make('target')
|
||||
->label('Ziel')
|
||||
->state(fn (NavigationItem $record): string => $record->page?->path ?? (string) $record->url),
|
||||
@@ -88,7 +117,7 @@ public static function table(Table $table): Table
|
||||
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"))
|
||||
->orderQueryUsing(fn ($query, string $direction) => $query->orderByRaw("CASE placement WHEN 'header' THEN 0 WHEN 'footer' THEN 1 WHEN 'footer_contact' THEN 2 WHEN 'footer_legal' THEN 3 ELSE 4 END"))
|
||||
->collapsible(),
|
||||
)
|
||||
->paginated([50, 100])
|
||||
@@ -110,7 +139,7 @@ public static function table(Table $table): Table
|
||||
->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.'),
|
||||
->modalDescription('Der Eintrag wird aus der Navigation entfernt. Die verlinkte Seite bleibt bestehen; Untereinträge rücken in die oberste Ebene.'),
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,11 +4,13 @@
|
||||
|
||||
use App\Domain\Catalog\Pillar;
|
||||
use App\Domain\Cms\Page;
|
||||
use App\Domain\Cms\PageService;
|
||||
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 App\Filament\Support\SectionEditor;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\CheckboxList;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
@@ -17,6 +19,7 @@
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class PageResource extends Resource
|
||||
{
|
||||
@@ -36,6 +39,8 @@ public static function form(Schema $schema): Schema
|
||||
Section::make('Seite und Suchmaschinen')
|
||||
->description('Adresse, Titel für Suchmaschinen und Zuordnung zu Themenbereichen.')
|
||||
->collapsible()
|
||||
->collapsed(fn (string $operation): bool => $operation === 'edit')
|
||||
->persistCollapsed()
|
||||
->columns(2)
|
||||
->columnSpanFull()
|
||||
->schema([
|
||||
@@ -55,13 +60,14 @@ public static function form(Schema $schema): Schema
|
||||
->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),
|
||||
->columns(['default' => 1, 'lg' => 2]),
|
||||
]),
|
||||
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“.')
|
||||
->description('Abschnitt hinzufügen, Raster wählen, Widgets in die Plätze einsetzen. Ein Klick auf die Vorschau eines Widgets öffnet seinen Dialog; Hintergrund, Breite, Abstand und Trenner stehen unter „Gestaltung des Abschnitts“. Speichern legt einen Entwurf an; veröffentlicht wird erst über „Veröffentlichen“.')
|
||||
->columnSpanFull()
|
||||
->extraAttributes(['class' => 'luf-page-content'])
|
||||
->schema([
|
||||
WidgetEditor::builder('blocks'),
|
||||
SectionEditor::repeater('sections'),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
@@ -76,7 +82,34 @@ public static function table(Table $table): Table
|
||||
->formatStateUsing(fn ($state): string => $state ? 'Ja' : 'Entwurf'),
|
||||
TextColumn::make('updated_at')->label('Geändert')->dateTime('d.m.Y H:i'),
|
||||
])
|
||||
->recordUrl(fn (Page $record): string => static::getUrl('edit', ['record' => $record]));
|
||||
->recordUrl(fn (Page $record): string => static::getUrl('edit', ['record' => $record]))
|
||||
->recordActions([
|
||||
Action::make('duplicate')
|
||||
->label('Duplizieren')
|
||||
->icon('heroicon-o-document-duplicate')
|
||||
->color('gray')
|
||||
->tooltip('Neue, unveröffentlichte Seite mit dem zuletzt gespeicherten Stand dieser Seite anlegen')
|
||||
->authorize(fn (): bool => auth()->user()?->can('create', Page::class) ?? false)
|
||||
->modalHeading(fn (Page $record): string => 'Seite '.$record->path.' duplizieren')
|
||||
->modalDescription('Die Kopie ist ein Entwurf unter neuer Adresse. Die Vorlage bleibt unverändert.')
|
||||
->schema([
|
||||
TextInput::make('path')
|
||||
->label('Pfad der neuen Seite')
|
||||
->required()
|
||||
->maxLength(255)
|
||||
->helperText('Zum Beispiel /neue-landingpage'),
|
||||
])
|
||||
->modalSubmitActionLabel('Duplizieren')
|
||||
->action(function (Page $record, array $data, PageService $service) {
|
||||
try {
|
||||
$copy = $service->duplicate($record, $data['path'], auth()->user());
|
||||
} catch (ValidationException $exception) {
|
||||
throw ValidationException::withMessages(['mountedActions.0.data.path' => $exception->errors()['path'] ?? $exception->errors()]);
|
||||
}
|
||||
|
||||
return redirect(static::getUrl('edit', ['record' => $copy]));
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
|
||||
@@ -6,16 +6,23 @@
|
||||
use App\Domain\Cms\Page;
|
||||
use App\Domain\Cms\PageService;
|
||||
use App\Filament\Resources\Pages\PageResource;
|
||||
use App\Filament\Support\WidgetEditor;
|
||||
use App\Filament\Support\ReportsSectionErrors;
|
||||
use App\Filament\Support\SectionEditor;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class CreatePage extends CreateRecord
|
||||
{
|
||||
use ReportsSectionErrors;
|
||||
|
||||
protected static string $resource = PageResource::class;
|
||||
|
||||
/** Breite Arbeitsfläche, damit mehrspaltige Raster im Editor erkennbar bleiben. */
|
||||
protected Width|string|null $maxContentWidth = Width::Full;
|
||||
|
||||
protected static bool $canCreateAnother = false;
|
||||
|
||||
/**
|
||||
@@ -24,17 +31,17 @@ class CreatePage extends CreateRecord
|
||||
protected function handleRecordCreation(array $data): Model
|
||||
{
|
||||
$service = app(PageService::class);
|
||||
$blocks = WidgetEditor::fromBuilderState($data['blocks'] ?? []);
|
||||
$content = SectionEditor::fromEditorState($data['sections'] ?? []);
|
||||
|
||||
try {
|
||||
return DB::transaction(function () use ($service, $data, $blocks): Page {
|
||||
return DB::transaction(function () use ($service, $data, $content): Page {
|
||||
$page = Page::query()->create([
|
||||
'path' => $service->availablePath($data['path']),
|
||||
]);
|
||||
|
||||
$service->saveRevision(
|
||||
$page,
|
||||
$blocks,
|
||||
$content,
|
||||
$data['seo_title'] ?? null,
|
||||
$data['seo_description'] ?? null,
|
||||
auth()->user(),
|
||||
@@ -45,10 +52,10 @@ protected function handleRecordCreation(array $data): Model
|
||||
return $page;
|
||||
});
|
||||
} catch (ValidationException $exception) {
|
||||
WidgetEditor::notifyErrors($exception->errors(), $blocks);
|
||||
SectionEditor::notifyErrors($exception->errors(), $this->data['sections'] ?? []);
|
||||
|
||||
throw ValidationException::withMessages(
|
||||
WidgetEditor::mapErrors($exception->errors(), array_keys($this->data['blocks'] ?? [])),
|
||||
SectionEditor::mapErrors($exception->errors(), $this->data['sections'] ?? []),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,17 +6,24 @@
|
||||
use App\Domain\Cms\Page;
|
||||
use App\Domain\Cms\PageService;
|
||||
use App\Filament\Resources\Pages\PageResource;
|
||||
use App\Filament\Support\WidgetEditor;
|
||||
use App\Filament\Support\ReportsSectionErrors;
|
||||
use App\Filament\Support\SectionEditor;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class EditPage extends EditRecord
|
||||
{
|
||||
use ReportsSectionErrors;
|
||||
|
||||
protected static string $resource = PageResource::class;
|
||||
|
||||
/** Breite Arbeitsfläche, damit mehrspaltige Raster im Editor erkennbar bleiben. */
|
||||
protected Width|string|null $maxContentWidth = Width::Full;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
@@ -85,7 +92,7 @@ protected function afterSave(): void
|
||||
protected function mutateFormDataBeforeFill(array $data): array
|
||||
{
|
||||
$revision = $this->record->latestRevision ?? $this->record->publishedRevision;
|
||||
$data['blocks'] = WidgetEditor::toBuilderState($revision?->blocks);
|
||||
$data['sections'] = SectionEditor::toEditorState($revision?->sections() ?? []);
|
||||
$data['seo_title'] = $revision?->seo_title;
|
||||
$data['seo_description'] = $revision?->seo_description;
|
||||
$data['pillars'] = $this->record->pillars()->pluck('pillars.id')->all();
|
||||
@@ -100,16 +107,16 @@ protected function handleRecordUpdate(Model $record, array $data): Model
|
||||
{
|
||||
/** @var Page $record */
|
||||
$service = app(PageService::class);
|
||||
$blocks = WidgetEditor::fromBuilderState($data['blocks'] ?? []);
|
||||
$content = SectionEditor::fromEditorState($data['sections'] ?? []);
|
||||
|
||||
try {
|
||||
$path = $service->availablePath($data['path'], $record);
|
||||
$service->saveRevision($record, $blocks, $data['seo_title'] ?? null, $data['seo_description'] ?? null, auth()->user());
|
||||
$service->saveRevision($record, $content, $data['seo_title'] ?? null, $data['seo_description'] ?? null, auth()->user());
|
||||
} catch (ValidationException $exception) {
|
||||
WidgetEditor::notifyErrors($exception->errors(), $blocks);
|
||||
SectionEditor::notifyErrors($exception->errors(), $this->data['sections'] ?? []);
|
||||
|
||||
throw ValidationException::withMessages(
|
||||
WidgetEditor::mapErrors($exception->errors(), array_keys($this->data['blocks'] ?? [])),
|
||||
SectionEditor::mapErrors($exception->errors(), $this->data['sections'] ?? []),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -24,8 +24,11 @@ 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')
|
||||
TextColumn::make('section_count')
|
||||
->label('Abschnitte')
|
||||
->state(fn (PageRevision $record): int => count($record->sections())),
|
||||
TextColumn::make('widget_count')
|
||||
->label('Widgets')
|
||||
->state(fn (PageRevision $record): int => count($record->widgets())),
|
||||
TextColumn::make('published')
|
||||
->label('Live')
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* Macht Feldfehler aus Widget-Dialogen am Abschnitt sichtbar. Die Felder eines Widgets liegen in seinem Dialog;
|
||||
* schlägt die Formularprüfung beim Speichern fehl, erscheint eine Meldung mit Abschnitt, Platz und Widget-Art,
|
||||
* und das Platzraster des Abschnitts trägt eine Zusammenfassung.
|
||||
*/
|
||||
trait ReportsSectionErrors
|
||||
{
|
||||
protected function onValidationError(ValidationException $exception): void
|
||||
{
|
||||
parent::onValidationError($exception);
|
||||
|
||||
$state = is_array($this->data['sections'] ?? null) ? $this->data['sections'] : [];
|
||||
$sectionErrors = SectionEditor::sectionErrorsFromForm($exception->errors(), $state);
|
||||
|
||||
if ($sectionErrors === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
SectionEditor::notifyErrors($sectionErrors, $state);
|
||||
|
||||
foreach (SectionEditor::mapErrors($sectionErrors, $state) as $key => $messages) {
|
||||
if (str_ends_with($key, '.slots')) {
|
||||
foreach ((array) $messages as $message) {
|
||||
$exception->validator->errors()->add($key, $message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use App\Domain\Cms\Sections\PageSections;
|
||||
use App\Domain\Cms\Sections\SectionLayouts;
|
||||
use App\Domain\Cms\Sections\SectionStyle;
|
||||
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
||||
use App\Domain\Cms\Widgets\WidgetRegistry;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\FileUpload;
|
||||
use Filament\Forms\Components\Hidden;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\ToggleButtons;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Components\Utilities\Set;
|
||||
use Illuminate\Support\HtmlString;
|
||||
use Illuminate\Support\Str;
|
||||
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
|
||||
|
||||
/**
|
||||
* Seiteneditor für Abschnitte und Slots.
|
||||
*
|
||||
* Aufbau: Abschnitte (Repeater) → Raster (grafische Auswahl) → Gestaltung (eingeklappt) → Plätze (Repeater im
|
||||
* Rasterverhältnis) → je Platz ein Widget (Builder mit höchstens einem Eintrag, Auswahl aus dem Widget-Register).
|
||||
* Abschnittseinstellungen stehen im Abschnitt, Widget-Einstellungen im Widget-Dialog: eine Dialogebene.
|
||||
*
|
||||
* Formularzustand eines Abschnitts: {id, layout, style: {...}, slots: {uuid: {widget: {uuid: Builder-Eintrag}}}}.
|
||||
*/
|
||||
class SectionEditor
|
||||
{
|
||||
public static function repeater(string $name = 'sections'): Repeater
|
||||
{
|
||||
return Repeater::make($name)
|
||||
->label('Abschnitte')
|
||||
->hiddenLabel()
|
||||
->schema(self::sectionSchema())
|
||||
->itemLabel(fn (array $state, ?int $index): string => self::sectionLabel($state, $index))
|
||||
->addActionLabel('Abschnitt hinzufügen')
|
||||
->addBetweenActionLabel('Abschnitt hier einfügen')
|
||||
->defaultItems(0)
|
||||
->reorderableWithButtons()
|
||||
->reorderableWithDragAndDrop()
|
||||
->cloneable()
|
||||
->collapsible()
|
||||
->deletable()
|
||||
->maxItems(PageSections::MAX_SECTIONS)
|
||||
->cloneAction(fn (Action $action): Action => $action->tooltip('Abschnitt duplizieren'))
|
||||
->deleteAction(fn (Action $action): Action => $action
|
||||
->tooltip('Abschnitt löschen')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Abschnitt löschen?')
|
||||
->modalDescription('Der Abschnitt und die Widgets darin werden aus dem Entwurf entfernt. Bereits gespeicherte Revisionen bleiben erhalten.')
|
||||
->modalSubmitActionLabel('Löschen'))
|
||||
->moveUpAction(fn (Action $action): Action => $action->tooltip('Abschnitt nach oben'))
|
||||
->moveDownAction(fn (Action $action): Action => $action->tooltip('Abschnitt nach unten'))
|
||||
->reorderAction(fn (Action $action): Action => $action->tooltip('Abschnitt ziehen'))
|
||||
->collapseAction(fn (Action $action): Action => $action->tooltip('Abschnitt einklappen'))
|
||||
->expandAction(fn (Action $action): Action => $action->tooltip('Abschnitt aufklappen'))
|
||||
->extraAttributes(['class' => 'luf-sections'])
|
||||
->columnSpanFull();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<mixed>
|
||||
*/
|
||||
private static function sectionSchema(): array
|
||||
{
|
||||
return [
|
||||
Hidden::make('id'),
|
||||
ToggleButtons::make('layout')
|
||||
->label('Raster')
|
||||
->options(self::layoutOptions())
|
||||
->default(SectionLayouts::DEFAULT)
|
||||
->required()
|
||||
->inline()
|
||||
->live()
|
||||
->disableOptionWhen(fn (string $value, Get $get): bool => self::filledCount($get('slots')) > SectionLayouts::slotCount($value))
|
||||
->helperText(fn (Get $get): ?string => self::filledCount($get('slots')) > 1
|
||||
? 'Raster mit weniger Plätzen als eingesetzten Widgets sind gesperrt. Entfernen oder verschieben Sie zuerst ein Widget; beim Wechsel geht kein Widget verloren.'
|
||||
: null)
|
||||
->afterStateUpdated(function (?string $state, Get $get, Set $set): void {
|
||||
$set('slots', self::arrangeSlots($get('slots'), $state ?? SectionLayouts::DEFAULT));
|
||||
})
|
||||
->extraAttributes(['class' => 'luf-layout-picker']),
|
||||
Section::make('Gestaltung des Abschnitts')
|
||||
->description(fn (Get $get): string => SectionStyle::summary(is_array($get('style')) ? $get('style') : []))
|
||||
->icon('heroicon-o-swatch')
|
||||
->collapsible()
|
||||
->collapsed()
|
||||
->compact()
|
||||
->schema([
|
||||
Group::make(self::styleFields())
|
||||
->statePath('style')
|
||||
->columns(['default' => 1, 'md' => 2, 'xl' => 4]),
|
||||
]),
|
||||
Repeater::make('slots')
|
||||
->label('Plätze im Raster')
|
||||
->hiddenLabel()
|
||||
->schema([
|
||||
WidgetEditor::slotBuilder('widget'),
|
||||
])
|
||||
->addable(false)
|
||||
->deletable(false)
|
||||
->reorderableWithDragAndDrop()
|
||||
->reorderableWithButtons(false)
|
||||
->reorderAction(fn (Action $action): Action => $action->tooltip('Widget auf einen anderen Platz ziehen'))
|
||||
->itemLabel(fn (array $state, ?int $index, Get $get): string => self::slotLabel($state, $index, $get('layout')))
|
||||
->default(fn (): array => self::arrangeSlots([], SectionLayouts::DEFAULT))
|
||||
->extraAttributes(fn (Get $get): array => [
|
||||
'class' => 'luf-slots',
|
||||
'style' => '--luf-slot-cols: '.self::editorColumns($get('layout')),
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<mixed>
|
||||
*/
|
||||
private static function styleFields(): array
|
||||
{
|
||||
return [
|
||||
Select::make('background')
|
||||
->label('Hintergrund')
|
||||
->options(SectionStyle::BACKGROUNDS)
|
||||
->default('default')
|
||||
->selectablePlaceholder(false)
|
||||
->live(),
|
||||
Select::make('width')
|
||||
->label('Breite')
|
||||
->options(SectionStyle::WIDTHS)
|
||||
->default('standard')
|
||||
->selectablePlaceholder(false)
|
||||
->helperText('Ein Hintergrund reicht immer über die ganze Bildschirmbreite.'),
|
||||
Select::make('spacing')
|
||||
->label('Abstand oben und unten')
|
||||
->options(SectionStyle::SPACINGS)
|
||||
->default('normal')
|
||||
->selectablePlaceholder(false),
|
||||
Select::make('divider')
|
||||
->label('Trenner zum nächsten Abschnitt')
|
||||
->options(SectionStyle::DIVIDERS)
|
||||
->default('none')
|
||||
->selectablePlaceholder(false),
|
||||
Select::make('image')
|
||||
->label('Hintergrundbild: vorhandenes Bild')
|
||||
->options(fn (): array => PublicMedia::imageOptions())
|
||||
->searchable()
|
||||
->placeholder('Bitte wählen')
|
||||
->helperText('Nur Bilder aus dem öffentlichen Website-Bereich. Geschützte Filmbilder sind hier nicht wählbar.')
|
||||
->visible(fn (Get $get): bool => $get('background') === 'image')
|
||||
->columnSpan(['default' => 1, 'md' => 2]),
|
||||
FileUpload::make('_upload')
|
||||
->label('Hintergrundbild: 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('Ersetzt die Auswahl links. Nur Bilder mit geklärter Veröffentlichungsfreigabe hochladen.')
|
||||
->visible(fn (Get $get): bool => $get('background') === 'image')
|
||||
->columnSpan(['default' => 1, 'md' => 2]),
|
||||
Select::make('focus')
|
||||
->label('Bildausschnitt (Fokuspunkt)')
|
||||
->options(SectionStyle::FOCUS)
|
||||
->default('center')
|
||||
->selectablePlaceholder(false)
|
||||
->helperText('Dieser Bereich bleibt auf schmalen Bildschirmen sichtbar.')
|
||||
->visible(fn (Get $get): bool => $get('background') === 'image'),
|
||||
Select::make('overlay')
|
||||
->label('Überlagerung')
|
||||
->options(SectionStyle::OVERLAYS)
|
||||
->default('light')
|
||||
->selectablePlaceholder(false)
|
||||
->helperText('Sorgt für lesbaren Text auf dem Bild.')
|
||||
->visible(fn (Get $get): bool => $get('background') === 'image'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gespeicherte Abschnitte (PageSections::read) als Formularzustand.
|
||||
*
|
||||
* @param list<array<string, mixed>> $sections
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public static function toEditorState(array $sections): array
|
||||
{
|
||||
$state = [];
|
||||
|
||||
foreach ($sections as $section) {
|
||||
$slots = [];
|
||||
|
||||
foreach ($section['slots'] as $widget) {
|
||||
$slots[(string) Str::uuid()] = [
|
||||
'widget' => is_array($widget) ? self::keyed(WidgetEditor::toBuilderState([$widget])) : [],
|
||||
];
|
||||
}
|
||||
|
||||
$state[] = [
|
||||
'id' => $section['id'] ?? (string) Str::uuid(),
|
||||
'layout' => $section['layout'],
|
||||
'style' => SectionStyle::fromStored($section['style'] ?? []),
|
||||
'slots' => $slots,
|
||||
];
|
||||
}
|
||||
|
||||
return $state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formularzustand als Abschnitte für PageService::saveRevision().
|
||||
*
|
||||
* @param array<int|string, mixed>|null $state
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public static function fromEditorState(?array $state): array
|
||||
{
|
||||
$sections = [];
|
||||
|
||||
foreach (array_values($state ?? []) as $section) {
|
||||
if (! is_array($section)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$slots = [];
|
||||
foreach (array_values(is_array($section['slots'] ?? null) ? $section['slots'] : []) as $slot) {
|
||||
$items = is_array($slot['widget'] ?? null) ? $slot['widget'] : [];
|
||||
$slots[] = $items === [] ? null : (WidgetEditor::fromBuilderState($items)[0] ?? null);
|
||||
}
|
||||
|
||||
$sections[] = [
|
||||
'id' => $section['id'] ?? null,
|
||||
'layout' => $section['layout'] ?? SectionLayouts::DEFAULT,
|
||||
'style' => is_array($section['style'] ?? null) ? $section['style'] : [],
|
||||
'slots' => $slots,
|
||||
];
|
||||
}
|
||||
|
||||
return $sections;
|
||||
}
|
||||
|
||||
/**
|
||||
* Übersetzt Fehlerschlüssel aus PageSections ("sections.2.slots.1.data.heading") in Formularpfade.
|
||||
* Widget-Fehler stehen zusätzlich als Zusammenfassung am Platzraster des Abschnitts, weil die Widget-Felder
|
||||
* nach dem Schließen des Dialogs nicht sichtbar sind.
|
||||
*
|
||||
* @param array<string, mixed> $errors
|
||||
* @param array<int|string, mixed> $state roher Formularzustand der Abschnitte
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function mapErrors(array $errors, array $state, string $statePath = 'data.sections'): array
|
||||
{
|
||||
$registry = app(WidgetRegistry::class);
|
||||
$sectionKeys = array_keys($state);
|
||||
$mapped = [];
|
||||
|
||||
foreach ($errors as $key => $messages) {
|
||||
$messages = (array) $messages;
|
||||
|
||||
if (preg_match('/^sections\.(\d+)(?:\.(.*))?$/', (string) $key, $match) !== 1 || ! isset($sectionKeys[(int) $match[1]])) {
|
||||
$mapped[$key === 'sections' ? $statePath : 'data.'.$key] = $messages;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$sectionKey = $sectionKeys[(int) $match[1]];
|
||||
$sectionPath = "$statePath.$sectionKey";
|
||||
$rest = $match[2] ?? '';
|
||||
|
||||
if (preg_match('/^slots\.(\d+)(?:\.(.*))?$/', $rest, $slotMatch) === 1) {
|
||||
$slotKeys = array_keys(is_array($state[$sectionKey]['slots'] ?? null) ? $state[$sectionKey]['slots'] : []);
|
||||
$slotKey = $slotKeys[(int) $slotMatch[1]] ?? null;
|
||||
$field = $slotMatch[2] ?? '';
|
||||
$position = (int) $slotMatch[1] + 1;
|
||||
$widgetItems = $slotKey !== null ? ($state[$sectionKey]['slots'][$slotKey]['widget'] ?? []) : [];
|
||||
$widgetKey = is_array($widgetItems) ? array_key_first($widgetItems) : null;
|
||||
$type = $widgetKey !== null ? ($widgetItems[$widgetKey]['type'] ?? null) : null;
|
||||
$label = $registry->has($type) ? $registry->get($type)->label() : 'Widget';
|
||||
|
||||
$summary = $mapped["$sectionPath.slots"] ?? [];
|
||||
foreach ($messages as $message) {
|
||||
$summary[] = "Platz $position ($label): $message";
|
||||
}
|
||||
$mapped["$sectionPath.slots"] = array_values(array_unique($summary));
|
||||
|
||||
if ($slotKey !== null && $widgetKey !== null && $field !== '' && $field !== 'units') {
|
||||
$field = preg_replace('/\.\d+\..*$/', '', $field);
|
||||
$mapped["$sectionPath.slots.$slotKey.widget.$widgetKey.data.$field"] = $messages;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$mapped[$rest === '' ? $sectionPath : "$sectionPath.$rest"] = $messages;
|
||||
}
|
||||
|
||||
return $mapped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formularfehler aus Widget-Dialogen ("data.sections.{uuid}.slots.{uuid}.widget.{uuid}.data.data.feld") in
|
||||
* Schlüssel des Abschnittsmodells ("sections.N.slots.M.data.feld") übersetzen.
|
||||
*
|
||||
* @param array<string, mixed> $errors
|
||||
* @param array<int|string, mixed> $state
|
||||
* @return array<string, list<string>>
|
||||
*/
|
||||
public static function sectionErrorsFromForm(array $errors, array $state, string $statePath = 'data.sections'): array
|
||||
{
|
||||
$sectionKeys = array_flip(array_map('strval', array_keys($state)));
|
||||
$translated = [];
|
||||
$pattern = '/^'.preg_quote($statePath, '/').'\.([^.]+)\.slots\.([^.]+)\.widget\.[^.]+\.data\.(.+)$/';
|
||||
|
||||
foreach ($errors as $key => $messages) {
|
||||
if (preg_match($pattern, (string) $key, $match) !== 1 || ! isset($sectionKeys[$match[1]])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$slotKeys = array_flip(array_map('strval', array_keys(is_array($state[$match[1]]['slots'] ?? null) ? $state[$match[1]]['slots'] : [])));
|
||||
if (! isset($slotKeys[$match[2]])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$translated['sections.'.$sectionKeys[$match[1]].'.slots.'.$slotKeys[$match[2]].'.'.$match[3]] = array_values((array) $messages);
|
||||
}
|
||||
|
||||
return $translated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sichtbare Meldung mit Abschnittsnummer, Platz und Widget-Art.
|
||||
*
|
||||
* @param array<string, list<string>> $errors
|
||||
* @param array<int|string, mixed> $state
|
||||
*/
|
||||
public static function notifyErrors(array $errors, array $state): void
|
||||
{
|
||||
$registry = app(WidgetRegistry::class);
|
||||
$sections = array_values($state);
|
||||
$lines = [];
|
||||
|
||||
foreach ($errors as $key => $messages) {
|
||||
$text = implode(' ', (array) $messages);
|
||||
|
||||
if (preg_match('/^sections\.(\d+)(?:\.slots\.(\d+))?/', (string) $key, $match) === 1) {
|
||||
$line = 'Abschnitt '.((int) $match[1] + 1);
|
||||
|
||||
if (isset($match[2])) {
|
||||
$slots = array_values(is_array($sections[(int) $match[1]]['slots'] ?? null) ? $sections[(int) $match[1]]['slots'] : []);
|
||||
$items = $slots[(int) $match[2]]['widget'] ?? [];
|
||||
$type = is_array($items) && $items !== [] ? (array_values($items)[0]['type'] ?? null) : null;
|
||||
$line .= ', Platz '.((int) $match[2] + 1).($registry->has($type) ? ' ('.$registry->get($type)->label().')' : '');
|
||||
}
|
||||
|
||||
$lines[] = $line.': '.$text;
|
||||
} else {
|
||||
$lines[] = $text;
|
||||
}
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Nicht gespeichert')
|
||||
->body(implode("\n", array_unique($lines)))
|
||||
->danger()
|
||||
->persistent()
|
||||
->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordnet Plätze für ein neues Raster: Widgets behalten ihre Reihenfolge, leere Plätze entfallen zuerst.
|
||||
* Es wird nie ein Widget entfernt; passen nicht alle Widgets, bleiben überzählige Plätze bestehen
|
||||
* (die Auswahl solcher Raster ist im Editor gesperrt, das Speichern weist sie ab).
|
||||
*
|
||||
* @param mixed $slots roher Zustand {uuid: {widget: {...}}}
|
||||
* @return array<string, array{widget: array<string, mixed>}>
|
||||
*/
|
||||
public static function arrangeSlots(mixed $slots, string $layout): array
|
||||
{
|
||||
$slots = is_array($slots) ? $slots : [];
|
||||
$count = SectionLayouts::slotCount(SectionLayouts::has($layout) ? $layout : SectionLayouts::DEFAULT);
|
||||
|
||||
if (count($slots) === $count) {
|
||||
return $slots;
|
||||
}
|
||||
|
||||
$filled = array_filter($slots, fn ($slot): bool => self::slotHasWidget($slot));
|
||||
|
||||
if (count($slots) < $count) {
|
||||
$arranged = $slots;
|
||||
} else {
|
||||
// Leere Plätze am Ende zuerst entfernen, dann übrige leere Plätze, bis die Zahl passt.
|
||||
$arranged = $slots;
|
||||
foreach (array_reverse(array_keys($slots)) as $key) {
|
||||
if (count($arranged) <= $count) {
|
||||
break;
|
||||
}
|
||||
if (! self::slotHasWidget($slots[$key])) {
|
||||
unset($arranged[$key]);
|
||||
}
|
||||
}
|
||||
$arranged = count($arranged) > $count ? $filled : $arranged;
|
||||
}
|
||||
|
||||
while (count($arranged) < $count) {
|
||||
$arranged[(string) Str::uuid()] = ['widget' => []];
|
||||
}
|
||||
|
||||
return $arranged;
|
||||
}
|
||||
|
||||
public static function filledCount(mixed $slots): int
|
||||
{
|
||||
return count(array_filter(is_array($slots) ? $slots : [], fn ($slot): bool => self::slotHasWidget($slot)));
|
||||
}
|
||||
|
||||
private static function slotHasWidget(mixed $slot): bool
|
||||
{
|
||||
return is_array($slot) && is_array($slot['widget'] ?? null) && $slot['widget'] !== [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, HtmlString>
|
||||
*/
|
||||
private static function layoutOptions(): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (SectionLayouts::UNITS as $key => $units) {
|
||||
$options[$key] = new HtmlString(
|
||||
'<span class="luf-layout-option">'.SectionLayouts::schematicSvg($key)
|
||||
.'<span class="luf-layout-option-text">'.e(SectionLayouts::short($key)).'</span>'
|
||||
.'<span class="fi-sr-only">'.e(SectionLayouts::LABELS[$key]).'</span></span>'
|
||||
);
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spaltenverhältnis der Plätze im Editor; entspricht dem Desktop-Raster der Website.
|
||||
*/
|
||||
private static function editorColumns(mixed $layout): string
|
||||
{
|
||||
$units = SectionLayouts::units(SectionLayouts::has($layout) ? $layout : SectionLayouts::DEFAULT);
|
||||
|
||||
return implode(' ', array_map(fn (int $unit): string => "minmax(0, {$unit}fr)", $units));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $state
|
||||
*/
|
||||
private static function sectionLabel(array $state, ?int $index): string
|
||||
{
|
||||
$layout = SectionLayouts::has($state['layout'] ?? null) ? $state['layout'] : SectionLayouts::DEFAULT;
|
||||
$registry = app(WidgetRegistry::class);
|
||||
$names = [];
|
||||
|
||||
foreach (is_array($state['slots'] ?? null) ? $state['slots'] : [] as $slot) {
|
||||
$items = is_array($slot['widget'] ?? null) ? $slot['widget'] : [];
|
||||
$type = $items !== [] ? (array_values($items)[0]['type'] ?? null) : null;
|
||||
if ($registry->has($type)) {
|
||||
$names[] = $registry->get($type)->label();
|
||||
}
|
||||
}
|
||||
|
||||
$label = 'Abschnitt '.(($index ?? 0) + 1).' · Raster '.SectionLayouts::short($layout)
|
||||
.' · '.SectionStyle::summary(is_array($state['style'] ?? null) ? $state['style'] : []);
|
||||
|
||||
return $names === [] ? $label.' · noch leer' : $label.' · '.implode(', ', $names);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $state
|
||||
*/
|
||||
private static function slotLabel(array $state, ?int $index, mixed $layout): string
|
||||
{
|
||||
$layout = SectionLayouts::has($layout) ? $layout : SectionLayouts::DEFAULT;
|
||||
$units = SectionLayouts::units($layout);
|
||||
$position = $index ?? 0;
|
||||
$slotUnits = $units[$position] ?? null;
|
||||
|
||||
if ($slotUnits === null) {
|
||||
return 'Platz '.($position + 1).' · außerhalb des Rasters: Widget entfernen oder Raster mit mehr Plätzen wählen';
|
||||
}
|
||||
|
||||
$label = 'Platz '.($position + 1).' · '.$slotUnits.' '.($slotUnits === 1 ? 'Einheit' : 'Einheiten');
|
||||
$items = is_array($state['widget'] ?? null) ? $state['widget'] : [];
|
||||
$type = $items !== [] ? (array_values($items)[0]['type'] ?? null) : null;
|
||||
$registry = app(WidgetRegistry::class);
|
||||
|
||||
if ($registry->has($type) && $registry->get($type)->minUnits() > $slotUnits) {
|
||||
$label .= ' · zu schmal: „'.$registry->get($type)->label().'“ braucht '.$registry->get($type)->minUnits();
|
||||
}
|
||||
|
||||
return $label;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $items
|
||||
* @return array<string, array<string, mixed>>
|
||||
*/
|
||||
private static function keyed(array $items): array
|
||||
{
|
||||
$keyed = [];
|
||||
foreach ($items as $item) {
|
||||
$keyed[(string) Str::uuid()] = $item;
|
||||
}
|
||||
|
||||
return $keyed;
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,34 @@ public static function builder(string $name = 'blocks'): Builder
|
||||
->columnSpanFull();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Platz im Abschnittsraster: höchstens ein Widget. Hinzufügen öffnet die Widget-Auswahl und danach den
|
||||
* Bearbeitungsdialog; die Vorschau zeigt das Widget in der tatsächlichen Platzbreite.
|
||||
*/
|
||||
public static function slotBuilder(string $name = 'widget'): Builder
|
||||
{
|
||||
$registry = app(WidgetRegistry::class);
|
||||
|
||||
return Builder::make($name)
|
||||
->label('Widget')
|
||||
->hiddenLabel()
|
||||
->blocks(array_values(array_map(self::block(...), $registry->all())))
|
||||
->blockPreviews()
|
||||
->blockPickerColumns(['default' => 1, 'md' => 2])
|
||||
->blockPickerWidth('3xl')
|
||||
->addActionLabel('Widget einsetzen')
|
||||
->maxItems(1)
|
||||
->blockNumbers(false)
|
||||
->reorderable(false)
|
||||
->cloneable(false)
|
||||
->deletable()
|
||||
->collapsible(false)
|
||||
->addAction(fn ($action) => $action->modalHeading('Widget einrichten')->modalWidth('4xl')->icon('heroicon-o-plus'))
|
||||
->editAction(fn ($action) => $action->modalHeading('Widget bearbeiten')->modalWidth('4xl')->modalSubmitActionLabel('Übernehmen')->tooltip('Widget bearbeiten'))
|
||||
->deleteAction(fn ($action) => $action->tooltip('Widget aus diesem Platz entfernen')->requiresConfirmation()->modalHeading('Widget entfernen?')->modalDescription('Das Widget wird aus dem Entwurf entfernt. Gespeicherte Revisionen bleiben erhalten.')->modalSubmitActionLabel('Entfernen'))
|
||||
->columnSpanFull();
|
||||
}
|
||||
|
||||
public static function block(WidgetType $type): Block
|
||||
{
|
||||
$variants = $type->variants();
|
||||
@@ -252,10 +280,18 @@ private static function pickerLabel(WidgetType $type): 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>'
|
||||
.'<span class="luf-widget-pick-desc">'.e($type->description()).'</span>'
|
||||
.'<span class="luf-widget-pick-units">'.e(self::unitsHint($type)).'</span></span></span>'
|
||||
);
|
||||
}
|
||||
|
||||
private static function unitsHint(WidgetType $type): string
|
||||
{
|
||||
return $type->minUnits() === 1
|
||||
? 'Passt in jeden Platz'
|
||||
: 'Braucht einen Platz ab '.$type->minUnits().' Rastereinheiten';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $state
|
||||
*/
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
use App\Domain\Cms\Page;
|
||||
use App\Domain\Cms\PageRevision;
|
||||
use App\Domain\Cms\PageTemplates;
|
||||
use App\Domain\Cms\Sections\SectionRenderer;
|
||||
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;
|
||||
@@ -69,10 +69,11 @@ private function render(Page $page, bool $preview, ?PageRevision $revision = nul
|
||||
'revision' => $revision,
|
||||
'preview' => $preview,
|
||||
'template' => app(PageTemplates::class)->viewFor($page),
|
||||
'content' => app(WidgetRenderer::class)->renderAll($revision->blocks, $context),
|
||||
'content' => app(SectionRenderer::class)->renderAll($revision->sections(), $context),
|
||||
'documentTitle' => $revision->seo_title ?: ($revision->contentTitle() ?? config('app.name')),
|
||||
'documentDescription' => $revision->seo_description,
|
||||
'themes' => $page->path === '/' ? Pillar::query()->published()->get() : collect(),
|
||||
'activePath' => $page->path,
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user