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

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

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

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

No files matched your search

@@ -4,14 +4,22 @@
use App\Domain\Cms\NavigationItem;
use App\Domain\Cms\Page;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Filament\Resources\NavigationItems\Pages\ManageNavigationItems;
use Closure;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Grouping\Group;
use Filament\Tables\Table;
class NavigationItemResource extends Resource
@@ -28,13 +36,21 @@ public static function form(Schema $schema): Schema
{
return $schema->components([
TextInput::make('label')->label('Beschriftung')->required()->maxLength(80),
Select::make('placement')
->label('Platz')
->options(NavigationItem::PLACEMENTS)
->default('header')
->required(),
Select::make('page_id')
->label('Seite')
->label('Interne Seite')
->options(fn (): array => Page::query()->orderBy('path')->pluck('path', 'id')->all())
->searchable(),
->searchable()
->helperText('Bevorzugt: eine CMS-Seite wählen. Dann folgt der Link automatisch einer Pfadänderung.'),
TextInput::make('url')
->label('Adresse')
->label('Oder Adresse')
->maxLength(500)
->helperText('Nur wenn keine Seite gewählt ist: Pfad wie /anmelden oder eine vollständige http(s)-Adresse.')
->rule(SafeUrl::rule())
->rule(function (Get $get): Closure {
return function (string $attribute, mixed $value, Closure $fail) use ($get): void {
if (blank($get('page_id')) && blank($value)) {
@@ -42,14 +58,16 @@ public static function form(Schema $schema): Schema
}
};
}),
Select::make('placement')
->label('Platz')
->options([
'header' => 'Kopfzeile',
'footer' => 'Fußzeile',
])
Toggle::make('is_visible')
->label('Auf der Website anzeigen')
->default(true),
TextInput::make('sort_order')
->label('Reihenfolge')
->numeric()
->minValue(0)
->default(fn (): int => (int) NavigationItem::query()->max('sort_order') + 1)
->helperText('Kleinere Zahlen stehen weiter vorn. In der Liste lässt sich die Reihenfolge auch per Ziehen ändern.')
->required(),
TextInput::make('sort_order')->label('Reihenfolge')->numeric()->required()->default(0),
]);
}
@@ -57,13 +75,43 @@ public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('label')->label('Beschriftung'),
TextColumn::make('page.path')->label('Seite'),
TextColumn::make('url')->label('Adresse'),
TextColumn::make('placement')->label('Platz'),
TextColumn::make('sort_order')->label('Reihenfolge')->sortable(),
TextColumn::make('label')->label('Beschriftung')->searchable(),
TextColumn::make('target')
->label('Ziel')
->state(fn (NavigationItem $record): string => $record->page?->path ?? (string) $record->url),
IconColumn::make('is_visible')
->label('Sichtbar')
->boolean(),
TextColumn::make('sort_order')->label('Reihenfolge'),
])
->defaultSort('sort_order');
->defaultGroup(
Group::make('placement')
->label('Platz')
->getTitleFromRecordUsing(fn (NavigationItem $record): string => NavigationItem::PLACEMENTS[$record->placement] ?? $record->placement)
->orderQueryUsing(fn ($query, string $direction) => $query->orderByRaw("CASE placement WHEN 'header' THEN 0 ELSE 1 END"))
->collapsible(),
)
->paginated([50, 100])
->defaultPaginationPageOption(50)
->filters([
SelectFilter::make('placement')->label('Platz')->options(NavigationItem::PLACEMENTS),
])
->reorderable('sort_order')
->reorderRecordsTriggerAction(fn (Action $action, bool $isReordering): Action => $action
->button()
->label($isReordering ? 'Sortieren beenden' : 'Reihenfolge ändern'))
->defaultSort('sort_order')
->recordActions([
Action::make('toggleVisibility')
->label(fn (NavigationItem $record): string => $record->is_visible ? 'Ausblenden' : 'Einblenden')
->icon(fn (NavigationItem $record): string => $record->is_visible ? 'heroicon-o-eye-slash' : 'heroicon-o-eye')
->color('gray')
->authorize(fn (NavigationItem $record): bool => auth()->user()?->can('update', $record) ?? false)
->action(fn (NavigationItem $record) => $record->update(['is_visible' => ! $record->is_visible])),
EditAction::make(),
DeleteAction::make()
->modalDescription('Der Eintrag wird aus der Navigation entfernt. Die verlinkte Seite bleibt bestehen.'),
]);
}
public static function getPages(): array
+31 -73
View File
@@ -3,20 +3,17 @@
namespace App\Filament\Resources\Pages;
use App\Domain\Catalog\Pillar;
use App\Domain\Cms\Blocks\BlockRegistry;
use App\Domain\Cms\Page;
use App\Filament\Resources\Pages\Pages\CreatePage;
use App\Filament\Resources\Pages\Pages\EditPage;
use App\Filament\Resources\Pages\Pages\ListPages;
use App\Filament\Resources\Pages\RelationManagers\RevisionsRelationManager;
use App\Filament\Support\WidgetEditor;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
@@ -35,76 +32,37 @@ class PageResource extends Resource
public static function form(Schema $schema): Schema
{
$labels = app(BlockRegistry::class)->labels();
return $schema->components([
TextInput::make('path')
->label('Pfad')
->required()
->maxLength(255)
->helperText('Zum Beispiel / oder /praevention'),
TextInput::make('seo_title')
->label('SEO-Titel')
->maxLength(255),
Textarea::make('seo_description')
->label('SEO-Beschreibung')
->maxLength(500)
->columnSpanFull(),
CheckboxList::make('pillars')
->label('Fachliche Säulen')
->options(fn (): array => Pillar::query()->orderBy('name')->pluck('name', 'id')->all())
->helperText('Eine veröffentlichte Seite erscheint auf den gewählten Themenbereichen der Website. Eine Seite kann mehreren Säulen zugeordnet sein.')
->columns(1),
Repeater::make('blocks')
->label('Bausteine')
->schema([
Select::make('type')
->label('Typ')
->options($labels)
->required()
->live(),
TextInput::make('heading')
->label('Überschrift')
->visible(fn (Get $get): bool => in_array($get('type'), ['heading', 'call_to_action'], true)),
Textarea::make('intro')
->label('Einleitung')
->visible(fn (Get $get): bool => $get('type') === 'heading'),
Textarea::make('body')
->label('Text')
->visible(fn (Get $get): bool => in_array($get('type'), ['prose', 'image_text'], true))
->columnSpanFull(),
FileUpload::make('image')
->label('Bild')
->disk('cms_incoming')
->directory('cms')
->image()
->visible(fn (Get $get): bool => $get('type') === 'image_text'),
TextInput::make('alt')
->label('Alternativtext')
->visible(fn (Get $get): bool => $get('type') === 'image_text'),
Textarea::make('text')
->label('Text')
->visible(fn (Get $get): bool => $get('type') === 'call_to_action'),
TextInput::make('label')
->label('Beschriftung der Aktion')
->visible(fn (Get $get): bool => $get('type') === 'call_to_action'),
TextInput::make('url')
->label('Adresse')
->visible(fn (Get $get): bool => $get('type') === 'call_to_action'),
Repeater::make('items')
->label('Einträge')
->visible(fn (Get $get): bool => in_array($get('type'), ['cards', 'faq'], true))
->schema([
TextInput::make('title')->label('Titel')->visible(fn (Get $get): bool => $get('../../type') === 'cards'),
Textarea::make('text')->label('Text')->visible(fn (Get $get): bool => $get('../../type') === 'cards'),
TextInput::make('url')->label('Adresse')->visible(fn (Get $get): bool => $get('../../type') === 'cards'),
TextInput::make('question')->label('Frage')->visible(fn (Get $get): bool => $get('../../type') === 'faq'),
Textarea::make('answer')->label('Antwort')->visible(fn (Get $get): bool => $get('../../type') === 'faq'),
]),
])
Section::make('Seite und Suchmaschinen')
->description('Adresse, Titel für Suchmaschinen und Zuordnung zu Themenbereichen.')
->collapsible()
->columns(2)
->columnSpanFull()
->reorderable()
->collapsed(),
->schema([
TextInput::make('path')
->label('Pfad')
->required()
->maxLength(255)
->helperText('Zum Beispiel / oder /praevention'),
TextInput::make('seo_title')
->label('SEO-Titel')
->maxLength(255),
Textarea::make('seo_description')
->label('SEO-Beschreibung')
->maxLength(500)
->columnSpanFull(),
CheckboxList::make('pillars')
->label('Fachliche Säulen')
->options(fn (): array => Pillar::query()->orderBy('name')->pluck('name', 'id')->all())
->helperText('Eine veröffentlichte Seite erscheint auf den gewählten Themenbereichen der Website. Eine Seite kann mehreren Säulen zugeordnet sein.')
->columns(1),
]),
Section::make('Inhalt der Seite')
->description('Abschnitte hinzufügen, per Klick auf die Vorschau bearbeiten, mit den Pfeilen sortieren. Speichern legt einen Entwurf an; veröffentlicht wird erst über „Veröffentlichen“.')
->columnSpanFull()
->schema([
WidgetEditor::builder('blocks'),
]),
]);
}
@@ -5,31 +5,51 @@
use App\Domain\Cms\Page;
use App\Domain\Cms\PageService;
use App\Filament\Resources\Pages\PageResource;
use App\Filament\Support\WidgetEditor;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class CreatePage extends CreateRecord
{
protected static string $resource = PageResource::class;
protected static bool $canCreateAnother = false;
/**
* @param array<string, mixed> $data
*/
protected function handleRecordCreation(array $data): Model
{
$service = app(PageService::class);
$page = Page::query()->create([
'path' => $service->normalizePath($data['path']),
]);
$blocks = WidgetEditor::fromBuilderState($data['blocks'] ?? []);
$service->saveRevision(
$page,
$data['blocks'] ?? [],
$data['seo_title'] ?? null,
$data['seo_description'] ?? null,
auth()->user(),
);
try {
return DB::transaction(function () use ($service, $data, $blocks): Page {
$page = Page::query()->create([
'path' => $service->availablePath($data['path']),
]);
return $page;
$service->saveRevision(
$page,
$blocks,
$data['seo_title'] ?? null,
$data['seo_description'] ?? null,
auth()->user(),
);
return $page;
});
} catch (ValidationException $exception) {
throw ValidationException::withMessages(
WidgetEditor::mapErrors($exception->errors(), array_keys($this->data['blocks'] ?? [])),
);
}
}
protected function getRedirectUrl(): string
{
return static::getResource()::getUrl('edit', ['record' => $this->getRecord()]);
}
}
+42 -11
View File
@@ -6,9 +6,12 @@
use App\Domain\Cms\Page;
use App\Domain\Cms\PageService;
use App\Filament\Resources\Pages\PageResource;
use App\Filament\Support\WidgetEditor;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\ValidationException;
class EditPage extends EditRecord
{
@@ -19,27 +22,52 @@ protected function getHeaderActions(): array
return [
Action::make('preview')
->label('Vorschau')
->icon('heroicon-o-device-phone-mobile')
->color('gray')
->tooltip('Zuletzt gespeicherten Entwurf in Smartphone-, Tablet- und Desktopbreite ansehen')
->url(function (): string {
$revision = $this->record->latestRevision;
return $revision === null
? '#'
: route('pages.preview', $revision);
: route('pages.preview.devices', $revision);
})
->openUrlInNewTab(),
Action::make('publish')
->label('Veröffentlichen')
->icon('heroicon-o-globe-alt')
->requiresConfirmation()
->modalHeading('Zuletzt gespeicherten Entwurf veröffentlichen?')
->modalDescription(fn (): string => 'Veröffentlicht wird Revision Nr. '.($this->record->latestRevision?->id ?? '–').'. Noch nicht gespeicherte Änderungen werden nicht veröffentlicht.')
->visible(fn (): bool => auth()->user()?->can('publish', $this->record) ?? false)
->action(function (PageService $service): void {
$revision = $this->record->latestRevision;
abort_if($revision === null, 404);
$service->publish($this->record, $revision);
$this->record->refresh();
Notification::make()->title('Seite veröffentlicht')->success()->send();
}),
Action::make('open')
->label('Live-Seite')
->icon('heroicon-o-arrow-top-right-on-square')
->color('gray')
->visible(fn (): bool => $this->record->isPublished())
->url(fn (): string => $this->record->publicUrl())
->openUrlInNewTab(),
];
}
protected function getSaveFormAction(): Action
{
return parent::getSaveFormAction()->label('Entwurf speichern');
}
protected function getSavedNotificationTitle(): ?string
{
return 'Entwurf gespeichert. Die Live-Seite bleibt unverändert, bis Sie veröffentlichen.';
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
@@ -47,7 +75,7 @@ protected function getHeaderActions(): array
protected function mutateFormDataBeforeFill(array $data): array
{
$revision = $this->record->latestRevision ?? $this->record->publishedRevision;
$data['blocks'] = $revision?->blocks ?? [];
$data['blocks'] = WidgetEditor::toBuilderState($revision?->blocks);
$data['seo_title'] = $revision?->seo_title;
$data['seo_description'] = $revision?->seo_description;
$data['pillars'] = $this->record->pillars()->pluck('pillars.id')->all();
@@ -62,19 +90,22 @@ protected function handleRecordUpdate(Model $record, array $data): Model
{
/** @var Page $record */
$service = app(PageService::class);
$blocks = WidgetEditor::fromBuilderState($data['blocks'] ?? []);
try {
$path = $service->availablePath($data['path'], $record);
$service->saveRevision($record, $blocks, $data['seo_title'] ?? null, $data['seo_description'] ?? null, auth()->user());
} catch (ValidationException $exception) {
throw ValidationException::withMessages(
WidgetEditor::mapErrors($exception->errors(), array_keys($this->data['blocks'] ?? [])),
);
}
$record->update([
'path' => $service->normalizePath($data['path']),
'path' => $path,
]);
app(PillarService::class)->assignPages($record, array_map(intval(...), $data['pillars'] ?? []));
$service->saveRevision(
$record,
$data['blocks'] ?? [],
$data['seo_title'] ?? null,
$data['seo_description'] ?? null,
auth()->user(),
);
return $record;
}
}
@@ -4,7 +4,9 @@
use App\Domain\Cms\PageRevision;
use App\Domain\Cms\PageService;
use App\Filament\Resources\Pages\PageResource;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
@@ -22,11 +24,22 @@ public function table(Table $table): Table
TextColumn::make('id')->label('Nr.'),
TextColumn::make('created_at')->label('Gespeichert')->dateTime('d.m.Y H:i'),
TextColumn::make('author.name')->label('Von'),
TextColumn::make('sections')
->label('Abschnitte')
->state(fn (PageRevision $record): int => count($record->widgets())),
TextColumn::make('published')
->label('Live')
->badge()
->color(fn (string $state): string => $state === 'Ja' ? 'success' : 'gray')
->state(fn (PageRevision $record): string => $record->id === $this->getOwnerRecord()->published_revision_id ? 'Ja' : 'Nein'),
])
->recordActions([
Action::make('preview')
->label('Vorschau')
->icon('heroicon-o-eye')
->color('gray')
->url(fn (PageRevision $record): string => route('pages.preview.devices', $record))
->openUrlInNewTab(),
Action::make('publish')
->label('Veröffentlichen')
->requiresConfirmation()
@@ -34,13 +47,16 @@ public function table(Table $table): Table
->action(function (PageRevision $record, PageService $service): void {
$service->publish($this->getOwnerRecord(), $record);
$this->getOwnerRecord()->refresh();
Notification::make()->title('Revision '.$record->id.' ist jetzt live.')->success()->send();
}),
Action::make('restore')
->label('Wiederherstellen')
->requiresConfirmation()
->modalDescription('Es entsteht eine neue Revision. Die Live-Seite bleibt unverändert, bis sie veröffentlicht wird.')
->modalDescription('Es entsteht eine neue Revision mit diesem Stand. Die Live-Seite bleibt unverändert, bis sie veröffentlicht wird.')
->action(function (PageRevision $record, PageService $service): void {
$service->restore($this->getOwnerRecord(), $record, auth()->user());
$restored = $service->restore($this->getOwnerRecord(), $record, auth()->user());
Notification::make()->title('Als neue Revision '.$restored->id.' wiederhergestellt.')->success()->send();
$this->redirect(PageResource::getUrl('edit', ['record' => $this->getOwnerRecord()]));
}),
])
->defaultSort('id', 'desc');
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Filament\Support;
use Filament\Forms\Components\Builder\Block;
use Illuminate\Contracts\View\View;
/**
* Builder-Block, dessen Vorschau den gemeinsamen Widget-Renderer verwendet.
*/
class WidgetBlock extends Block
{
/**
* @param array<string, mixed> $data
*/
public function renderPreview(array $data): View
{
return view('filament.cms.widget-preview', [
'html' => WidgetEditor::renderPreview($this->getName(), $data),
'stylesheets' => WidgetEditor::previewStylesheets(),
]);
}
}
+328
View File
@@ -0,0 +1,328 @@
<?php
namespace App\Filament\Support;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\WidgetRegistry;
use App\Domain\Cms\Widgets\WidgetRenderer;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\Builder\Block;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\RichEditor\RichContentRenderer;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\ToggleButtons;
use Filament\Schemas\Components\Group;
use Illuminate\Foundation\Vite;
use Illuminate\Support\HtmlString;
use Illuminate\Support\Str;
use Throwable;
/**
* Übersetzt das Widget-Register in den Filament-Builder des Seiteneditors.
*
* Der Editor kennt keine einzelne Widget-Art: Auswahl, Felder, Varianten, Zusammenfassung und
* Blockvorschau kommen vollständig aus dem Register. Zustand eines Builder-Eintrags:
* {type, data: {id, variant, settings, data, refs}}.
*/
class WidgetEditor
{
public const MAX_WIDGETS = 40;
public static function builder(string $name = 'blocks'): Builder
{
$registry = app(WidgetRegistry::class);
return Builder::make($name)
->label('Abschnitte')
->blocks(array_values(array_map(self::block(...), $registry->all())))
->blockPreviews()
->blockPickerColumns(['default' => 1, 'md' => 2])
->blockPickerWidth('3xl')
->addActionLabel('Abschnitt hinzufügen')
->addBetweenActionLabel('Hier einfügen')
->reorderableWithButtons()
->reorderableWithDragAndDrop()
->cloneable()
->deletable()
->maxItems(self::MAX_WIDGETS)
->addAction(fn ($action) => $action->modalHeading('Neuen Abschnitt einrichten')->modalWidth('4xl'))
->addBetweenAction(fn ($action) => $action->modalHeading('Neuen Abschnitt einrichten')->modalWidth('4xl'))
->editAction(fn ($action) => $action->modalHeading('Abschnitt bearbeiten')->modalWidth('4xl')->modalSubmitActionLabel('Übernehmen'))
->columnSpanFull();
}
public static function block(WidgetType $type): Block
{
$variants = $type->variants();
$schema = [Hidden::make('id')];
$schema[] = count($variants) > 1
? ToggleButtons::make('variant')
->label('Darstellung')
->options($variants)
->default($type->defaultVariant())
->inline()
->required()
: Hidden::make('variant')->default($type->defaultVariant());
if ($type->settings() !== []) {
$settings = [];
foreach ($type->settings() as $key => $options) {
$settings[] = Select::make($key)->label(Str::headline($key))->options($options);
}
$schema[] = Group::make($settings)->statePath('settings');
}
foreach ($type->editorSchema() as $component) {
$schema[] = $component;
}
return WidgetBlock::make($type->key())
->label(function (?array $state) use ($type): string|HtmlString {
if ($state === null) {
return self::pickerLabel($type);
}
return self::itemLabel($type, $state);
})
->icon($type->icon())
->schema($schema)
->preview('filament.cms.widget-preview');
}
/**
* Gespeicherte Bausteine (Altformat oder Hülle) als Builder-Zustand.
*
* @param array<int|string, mixed>|null $blocks
* @return list<array{type: string, data: array<string, mixed>}>
*/
public static function toBuilderState(?array $blocks): array
{
$state = [];
foreach (app(WidgetRegistry::class)->read($blocks) as $widget) {
$state[] = [
'type' => $widget['type'],
'data' => [
'id' => $widget['id'] ?? (string) Str::uuid(),
'variant' => $widget['variant'],
'settings' => $widget['settings'],
'data' => $widget['data'],
'refs' => $widget['refs'],
],
];
}
return $state;
}
/**
* Builder-Zustand als Hüllen für PageService::saveRevision().
*
* @param array<int|string, mixed>|null $state
* @return list<array<string, mixed>>
*/
public static function fromBuilderState(?array $state): array
{
$registry = app(WidgetRegistry::class);
$blocks = [];
foreach (array_values($state ?? []) as $item) {
$key = $item['type'] ?? null;
$data = is_array($item['data'] ?? null) ? $item['data'] : [];
$blocks[] = [
'id' => $data['id'] ?? null,
'type' => $key,
'v' => $registry->has($key) ? $registry->get($key)->version() : 1,
'variant' => $data['variant'] ?? null,
'settings' => is_array($data['settings'] ?? null) ? $data['settings'] : [],
'data' => self::listValues(is_array($data['data'] ?? null) ? $data['data'] : []),
'refs' => self::listValues(is_array($data['refs'] ?? null) ? $data['refs'] : []),
];
}
return $blocks;
}
/**
* Übersetzt Fehlerschlüssel des Registers ("blocks.3.data.url") in Formularpfade des Builders.
*
* @param array<string, mixed> $errors
* @param list<string> $itemKeys Builder-Schlüssel in Anzeigereihenfolge
* @return array<string, mixed>
*/
public static function mapErrors(array $errors, array $itemKeys, string $statePath = 'data.blocks'): array
{
$mapped = [];
foreach ($errors as $key => $messages) {
if (preg_match('/^blocks\.(\d+)(?:\.(.*))?$/', (string) $key, $match) === 1 && isset($itemKeys[(int) $match[1]])) {
// Verschachtelte Listen (items.2.url) tragen im Formular UUID-Schlüssel; die Meldung steht dann am Listenfeld.
$suffix = preg_replace('/\.\d+\..*$/', '', $match[2] ?? '');
$mapped[$statePath.'.'.$itemKeys[(int) $match[1]].'.data'.($suffix !== '' ? '.'.$suffix : '')] = $messages;
continue;
}
$mapped['data.'.$key] = $messages;
}
return $mapped;
}
/**
* Blockvorschau: dieselbe Widget-Ansicht wie öffentlich, aus dem ungespeicherten Zustand.
*
* @param array<string, mixed> $state roher Zustand eines Builder-Eintrags
*/
public static function renderPreview(string $type, array $state): string
{
$registry = app(WidgetRegistry::class);
if (! $registry->has($type)) {
return '';
}
$widget = $registry->upcast([
'id' => null,
'type' => $type,
'v' => $registry->get($type)->version(),
'variant' => $state['variant'] ?? null,
'settings' => is_array($state['settings'] ?? null) ? $state['settings'] : [],
'data' => self::plainState(is_array($state['data'] ?? null) ? $state['data'] : []),
'refs' => self::plainState(is_array($state['refs'] ?? null) ? $state['refs'] : []),
]);
try {
return app(WidgetRenderer::class)->renderWidget($widget, RenderContext::preview());
} catch (Throwable $exception) {
report($exception);
return '<p class="preview-note">Die Vorschau dieses Abschnitts ist noch unvollständig.</p>';
}
}
public static function previewStylesheets(): string
{
try {
return app(Vite::class)(['resources/css/app.css'])->toHtml();
} catch (Throwable) {
return '';
}
}
private static function pickerLabel(WidgetType $type): HtmlString
{
return new HtmlString(
'<span class="luf-widget-pick">'
.self::schematicSvg($type)
.'<span class="luf-widget-pick-text"><span class="luf-widget-pick-name">'.e($type->label()).'</span>'
.'<span class="luf-widget-pick-desc">'.e($type->description()).'</span></span></span>'
);
}
/**
* @param array<string, mixed> $state
*/
private static function itemLabel(WidgetType $type, array $state): string
{
$variant = $state['variant'] ?? $type->defaultVariant();
$variantLabel = $type->variants()[$variant] ?? null;
try {
$summary = $type->summary([
'type' => $type->key(),
'variant' => $variant,
'data' => self::plainState(is_array($state['data'] ?? null) ? $state['data'] : []),
'refs' => self::plainState(is_array($state['refs'] ?? null) ? $state['refs'] : []),
'settings' => [],
]);
} catch (Throwable) {
$summary = '';
}
$parts = [$type->label()];
if (count($type->variants()) > 1 && $variantLabel !== null) {
$parts[] = $variantLabel;
}
$label = implode(' · ', $parts);
return $summary !== '' ? $label.' – '.Str::limit($summary, 90) : $label;
}
private static function schematicSvg(WidgetType $type): string
{
$fills = ['ink' => '#1b2838', 'accent' => '#0f6e56', 'line' => '#c5d2cb', 'image' => '#9fb8ab'];
$rects = '';
foreach ($type->schematic() as [$x, $y, $w, $h, $tone]) {
$rects .= sprintf('<rect x="%d" y="%d" width="%d" height="%d" rx="1" fill="%s"/>', $x, $y, $w, $h, $fills[$tone] ?? $fills['line']);
}
return '<svg class="luf-widget-pick-schematic" viewBox="0 0 60 36" width="60" height="36" aria-hidden="true" focusable="false"><rect width="60" height="36" rx="2" fill="#f7faf8"/>'.$rects.'</svg>';
}
/**
* Roh-Zustand des Formulars (Repeater mit UUID-Schlüsseln, Texteditor als Dokument) in einfache Werte.
*
* @param array<int|string, mixed> $state
* @return array<int|string, mixed>
*/
private static function plainState(array $state): array
{
foreach ($state as $key => $value) {
if (is_array($value) && ($value['type'] ?? null) === 'doc') {
try {
$state[$key] = RichContentRenderer::make($value)->toHtml();
} catch (Throwable) {
$state[$key] = '';
}
continue;
}
if (is_array($value) && ! str_starts_with((string) $key, '_')) {
$state[$key] = self::plainState(array_is_list($value) || ! self::isUuidKeyed($value) ? $value : array_values($value));
}
}
return $state;
}
/**
* @param array<int|string, mixed> $values
* @return array<int|string, mixed>
*/
private static function listValues(array $values): array
{
foreach ($values as $key => $value) {
if (is_array($value) && ! str_starts_with((string) $key, '_')) {
$values[$key] = self::isUuidKeyed($value) ? array_values(array_map(fn ($item) => is_array($item) ? self::listValues($item) : $item, $value)) : self::listValues($value);
}
}
return $values;
}
/**
* @param array<int|string, mixed> $value
*/
private static function isUuidKeyed(array $value): bool
{
if ($value === []) {
return false;
}
foreach (array_keys($value) as $key) {
if (! is_string($key) || ! Str::isUuid($key)) {
return false;
}
}
return true;
}
}