Führe Abschnitte mit Raster, gemeinsames Designsystem und globales Website-Gerüst ein.
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:
LarsandClaude Opus 5.5 committed 2026-11-17 20:34:06 +01:00
1 parent db4bd30319
commit 480d55989b
57 files changed
+4730 -818

No files matched your search

@@ -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.'),
]);
}
+38 -5
View File
@@ -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);
}
}
}
}
}
+516
View File
@@ -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;
}
}
+37 -1
View File
@@ -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
*/