Files
laraundfelix/app/Filament/Support/WidgetEditor.php
T
LarsandClaude Opus 5.5 d4110b1d51
CI Feature / test (push) Successful in 1m6s
Deploy Test / test (push) Successful in 1m1s
Deploy Test / deploy (push) Successful in 33s
Halte den Fuß des Bausteindialogs in schmalen Fenstern erreichbar
Der Inhaltsbereich des großen Dialogs wuchs über das Fenster hinaus; bei 900 px
(Vorschau unter dem Formular) lagen „Zur Seite“ und „Änderungen verwerfen“
außerhalb des sichtbaren Bereichs. Der Inhalt scrollt jetzt im Dialog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:37:13 +01:00

544 lines
22 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Filament\Support;
use App\Domain\Cms\Sections\SectionLayouts;
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\Actions\Action;
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\Notifications\Notification;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\View;
use Filament\Support\Enums\Width;
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();
}
/**
* 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'))
// Baustein konfigurieren (Dokument 12, CMS-R03/R11): großer Kontext mit Vorschau. „Zur Seite“ übernimmt die
// Eingaben in den Seitenentwurf; Verwerfen ist eine ausdrückliche Handlung, Esc und Klick daneben verwerfen
// nichts still. Eine Bearbeitung direkt in der Seite war gemessen deutlich langsamer (Abnahme Teil C).
->editAction(fn (Action $action) => $action
->label('Konfigurieren')
->icon('heroicon-o-adjustments-horizontal')
->button()
->size('sm')
->color('gray')
->modalHeading(fn (Builder $component, array $arguments): string => self::configureHeading($component, (string) ($arguments['item'] ?? '')))
->modalDescription('Inhalt, Medien und Darstellung dieses Bausteins. „Zur Seite“ übernimmt die Eingaben in den Seitenentwurf; gespeichert wird über „Entwurf speichern“.')
->modalWidth(Width::Screen)
->modalSubmitActionLabel('Zur Seite')
->modalCancelActionLabel('Änderungen verwerfen')
->closeModalByClickingAway(false)
->closeModalByEscaping(false)
->modalCloseButton(false)
// Eigener Scrollbereich: Sonst wächst der Inhalt über das Fenster und der Dialogfuß ist bei schmalen
// Fenstern (Vorschau unter dem Formular) nicht erreichbar.
->extraModalWindowAttributes(['class' => 'luf-baustein-dialog']))
->deleteAction(fn ($action) => $action->label('Entfernen')->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
{
$icons = $type->optionIcons();
$display = [];
if (count($type->variants()) > 1) {
$display[] = ToggleButtons::make('variant')
->label('Darstellung')
->options($type->variants())
->icons($icons['variant'] ?? [])
->default($type->defaultVariant())
->inline()
->required()
->live();
}
$settings = [];
$labels = $type->settingLabels();
foreach ($type->settingOptions() as $key => $options) {
// Gemeinsame Höhe (ADR-38): immer als sichtbare Auswahl mit Vorgabe, nie als freie Eingabe.
$settings[] = $key === 'height'
? ToggleButtons::make('height')
->label('Höhe')
->helperText('Gestaltungsparameter, keine Begrenzung: Längere Inhalte erhalten immer den nötigen Platz.')
->options($options)
->icons($icons['height'] ?? [])
->default($type->defaultHeight())
->inline()
->live()
: Select::make($key)
->label($labels[$key][0] ?? Str::headline($key))
->helperText($labels[$key][1] ?? null)
->placeholder('Vorgabe der Darstellung')
->options($options)
->live();
}
if ($settings !== []) {
$display[] = Grid::make(['default' => 1, 'md' => 2])->schema($settings)->statePath('settings');
}
$variantField = count($type->variants()) > 1 ? [] : [Hidden::make('variant')->default($type->defaultVariant())];
$content = $type->editorSchema();
$media = $type->mediaSchema();
if ($display === [] && $media === []) {
$schema = [Hidden::make('id'), ...$variantField, ...$content];
} else {
$tabs = [Tab::make('Inhalt')->icon('heroicon-o-pencil-square')->schema($content)];
if ($media !== []) {
$tabs[] = Tab::make('Medien')->icon('heroicon-o-photo')->schema($media);
}
if ($display !== []) {
$tabs[] = Tab::make('Darstellung')->icon('heroicon-o-adjustments-horizontal')->schema([
...$display,
Text::make('Platzbreiten: '.$type->unitsLabel().' Rastereinheiten. '.$type->narrowBehavior()),
]);
}
// Auf breiten Schirmen stehen Inhalt/Medien/Darstellung und die Bausteinvorschau nebeneinander.
$schema = [
Hidden::make('id'),
...$variantField,
Grid::make(['default' => 1, 'xl' => 5])->schema([
Tabs::make('Widget')->tabs($tabs)->contained(false)->columnSpan(['default' => 1, 'xl' => 3]),
self::livePreview($type)->columnSpan(['default' => 1, 'xl' => 2]),
]),
];
}
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');
}
/**
* „Programmkarte konfigurieren · Abschnitt 2 · Platz 2 · 1 Einheit“ aus dem Zustandspfad des Platzes.
*/
public static function configureHeading(Builder $component, string $itemKey): string
{
$registry = app(WidgetRegistry::class);
$type = $component->getRawState()[$itemKey]['type'] ?? null;
$heading = ($registry->has($type) ? $registry->get($type)->label() : 'Baustein').' konfigurieren';
if (preg_match('/sections\.([^.]+)\.slots\.([^.]+)\.widget$/', (string) $component->getStatePath(), $match) !== 1) {
return $heading;
}
$sections = $component->getLivewire()->data['sections'] ?? [];
$sectionIndex = array_search($match[1], array_map('strval', array_keys(is_array($sections) ? $sections : [])), true);
$slots = is_array($sections[$match[1]]['slots'] ?? null) ? $sections[$match[1]]['slots'] : [];
$slotIndex = array_search($match[2], array_map('strval', array_keys($slots)), true);
if ($sectionIndex === false || $slotIndex === false) {
return $heading;
}
$layout = $sections[$match[1]]['layout'] ?? SectionLayouts::DEFAULT;
$units = SectionLayouts::units(SectionLayouts::has($layout) ? $layout : SectionLayouts::DEFAULT)[$slotIndex] ?? null;
return $heading.' · Abschnitt '.($sectionIndex + 1).' · Platz '.($slotIndex + 1)
.($units !== null ? ' · '.$units.' '.($units === 1 ? 'Einheit' : 'Einheiten') : '');
}
/**
* 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;
}
/**
* Fehler aus der Registry als sichtbare Meldung: Die Felder eines Abschnitts liegen im Bearbeitungsdialog
* und sind nach dem Speichern nicht auf der Seite sichtbar. Die Meldung nennt Abschnittsnummer und Art.
*
* @param array<string, list<string>> $errors
* @param array<int|string, mixed> $blocks Bausteine in Anzeigereihenfolge
*/
public static function notifyErrors(array $errors, array $blocks): void
{
$registry = app(WidgetRegistry::class);
$blocks = array_values($blocks);
$lines = [];
foreach ($errors as $key => $messages) {
if (preg_match('/^blocks\.(\d+)/', (string) $key, $match) === 1) {
$type = $blocks[(int) $match[1]]['type'] ?? null;
$label = $registry->has($type) ? $registry->get($type)->label() : 'Abschnitt';
$lines[] = 'Abschnitt '.((int) $match[1] + 1).' ('.$label.'): '.implode(' ', (array) $messages);
} else {
$lines[] = implode(' ', (array) $messages);
}
}
Notification::make()
->title('Nicht gespeichert')
->body(implode("\n", array_unique($lines)))
->danger()
->persistent()
->send();
}
/** Logische Vorschaubreiten in px: tatsächliche Platzbreiten im Standardabschnitt bei 1440 px Fensterbreite. */
public const PREVIEW_UNIT_WIDTHS = [1 => 310, 2 => 640, 3 => 960, 4 => 1300];
public const PREVIEW_PHONE_WIDTH = 390;
/**
* Live-Vorschau im Bearbeitungsdialog: rendert den ungespeicherten Zustand mit derselben Ansicht wie die Website
* in einer wählbaren Platzbreite. Die Breitenwahl (_preview_width) wird nicht gespeichert.
*/
private static function livePreview(WidgetType $type): Section
{
$default = (string) self::PREVIEW_UNIT_WIDTHS[$type->preferredUnits()];
$widths = [(string) self::PREVIEW_PHONE_WIDTH => 'Smartphone'];
foreach ($type->supportedUnits() as $units) {
$widths[(string) self::PREVIEW_UNIT_WIDTHS[$units]] = $units.' '.($units === 1 ? 'Einheit' : 'Einheiten');
}
return Section::make('Vorschau')
->description('Änderungen erscheinen sofort. Unter 860 px zeigt der Einstieg den Sicherheitsumbruch, Bild und Text ab 900 px zwei Spalten.')
->collapsible()
->compact()
->schema([
ToggleButtons::make('_preview_width')
->hiddenLabel()
->options($widths)
->default($default)
// Beim Bearbeiten fehlt der Wert (er wird nicht gespeichert); ohne ihn zeigte die Vorschau die
// Vorgabe, ohne dass ein Knopf als gewählt markiert war.
->afterStateHydrated(fn (ToggleButtons $component, mixed $state) => filled($state) ? null : $component->state($default))
->inline()
->live()
->dehydrated(false)
->extraAttributes(['class' => 'luf-preview-width']),
View::make('filament.cms.widget-live-preview')
->viewData(fn (Get $get): array => [
'html' => self::renderPreview($type->key(), [
'variant' => $get('variant'),
'settings' => $get('settings'),
'data' => $get('data'),
'refs' => $get('refs'),
]),
'stylesheets' => self::previewStylesheets(),
'width' => (int) ($get('_preview_width') ?: $default),
]),
]);
}
/**
* 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 class="luf-widget-pick-units">'.e(self::unitsHint($type)).'</span></span></span>'
);
}
private static function unitsHint(WidgetType $type): string
{
return $type->supportedUnits() === [1, 2, 3, 4]
? 'Passt in jeden Platz (1 bis 4 Einheiten)'
: 'Für Plätze mit '.$type->unitsLabel().' Rastereinheiten';
}
/**
* @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;
}
}