Files
laraundfelix/app/Filament/Support/SectionEditor.php
T
LarsandClaude Sonnet 5.5 e29014a8a1
CI Feature / test (push) Successful in 5m48s
Deploy Test / test (push) Successful in 6m13s
Deploy Test / deploy (push) Successful in 42s
Benenne die Schaltfläche der Sprungmarke und lass Esc im Linkdialog nur den Dialog schließen
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 07:38:07 +01:00

715 lines
33 KiB
PHP

<?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\ImageRefFields;
use App\Domain\Cms\Widgets\WidgetRegistry;
use Filament\Actions\Action;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
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;
/**
* 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, name, anchor, hidden, 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())
->columns(['default' => 1, 'xl' => 2])
->itemLabel(fn (array $state, ?int $index): HtmlString => 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
->label('Abschnitt duplizieren')
->tooltip('Abschnitt duplizieren')
->action(function (array $arguments, Repeater $component): void {
// Die Kopie steht direkt hinter dem Original (Filament hängt sie sonst ans Seitenende).
$component->rawState(self::insertCopyAfter($component->getRawState() ?? [], (string) $arguments['item'], (string) $component->generateUuid()));
$component->callAfterStateUpdated();
$component->shouldPartiallyRenderAfterActionsCalled() ? $component->partiallyRender() : null;
}))
->deleteAction(fn (Action $action): Action => $action
->label('Abschnitt löschen')
->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->label('Abschnitt nach oben')->tooltip('Abschnitt nach oben'))
->moveDownAction(fn (Action $action): Action => $action->label('Abschnitt nach unten')->tooltip('Abschnitt nach unten'))
->reorderAction(fn (Action $action): Action => $action->label('Abschnitt ziehen')->tooltip('Abschnitt ziehen'))
->extraItemActions([
// Seiten-Arbeitsplatz (EditPage): Raster und Gestaltung im eigenen Kontext statt an jedem Abschnitt.
Action::make('gestalten')
->label('Abschnitt gestalten')
->icon('heroicon-o-swatch')
->button()
->size('sm')
->color('gray')
->visible(fn ($livewire): bool => is_object($livewire) && method_exists($livewire, 'openAbschnitt'))
->action(fn (array $arguments, Repeater $component) => $component->getLivewire()->openAbschnitt((string) $arguments['item'])),
])
->collapseAction(fn (Action $action): Action => $action->label('Abschnitt einklappen')->tooltip('Abschnitt einklappen'))
->expandAction(fn (Action $action): Action => $action->label('Abschnitt aufklappen')->tooltip('Abschnitt aufklappen'))
->extraAttributes(['class' => 'luf-sections'])
->columnSpanFull();
}
/**
* @return list<mixed>
*/
private static function sectionSchema(): array
{
return [
Hidden::make('id'),
self::labelSection(),
// Abschnittsgestaltung in drei Gruppen. Im Seiten-Arbeitsplatz nur im Kontext „Abschnitt gestalten“
// sichtbar und dort offen; beim Anlegen einer Seite an jedem Abschnitt, eingeklappt.
Section::make('Raster und Breite')
->columnSpanFull()
->extraAttributes(['class' => 'luf-nur-gestalten luf-gestaltung'])
->collapsible(fn ($livewire): bool => ! self::onWorkplace($livewire))
->collapsed(fn ($livewire): bool => ! self::onWorkplace($livewire))
->compact()
->schema([
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']),
Group::make([self::widthField()])->statePath('style')->columns(['default' => 1, 'md' => 2]),
]),
Section::make('Hintergrund')
->extraAttributes(['class' => 'luf-nur-gestalten luf-gestaltung'])
->collapsible(fn ($livewire): bool => ! self::onWorkplace($livewire))
->collapsed(fn ($livewire): bool => ! self::onWorkplace($livewire))
->compact()
->schema([
Group::make(self::backgroundFields())->statePath('style')->columns(['default' => 1, 'md' => 2]),
]),
Section::make('Abstände und Trenner')
->extraAttributes(['class' => 'luf-nur-gestalten luf-gestaltung'])
->collapsible(fn ($livewire): bool => ! self::onWorkplace($livewire))
->collapsed(fn ($livewire): bool => ! self::onWorkplace($livewire))
->compact()
->schema([
Group::make(self::spacingFields())->statePath('style')->columns(['default' => 1, 'md' => 2]),
]),
Repeater::make('slots')
->columnSpanFull()
->label('Plätze im Raster')
->hiddenLabel()
->schema([
WidgetEditor::slotBuilder('widget'),
])
->addable(false)
->deletable(false)
->reorderableWithDragAndDrop()
->reorderableWithButtons(false)
->reorderAction(fn (Action $action): Action => $action->label('Baustein auf einen anderen Platz ziehen')->tooltip('Baustein auf einen anderen Platz ziehen'))
->itemLabel(fn (array $state, ?int $index, Get $get): HtmlString => 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')),
]),
];
}
/**
* Name, Sprungmarke und Sichtbarkeit: stehen im Seitenaufbau am Abschnitt, damit man sie beim Ordnen der Seite sieht.
*/
private static function labelSection(): Section
{
return Section::make('Name, Sprungmarke und Sichtbarkeit')
->columnSpanFull()
->compact()
->collapsible()
->collapsed(fn (Get $get): bool => blank($get('name')) && blank($get('anchor')) && ! $get('hidden'))
->extraAttributes(['class' => 'luf-abschnitt-bezeichnung'])
->schema([
TextInput::make('name')
->label('Name des Abschnitts')
->placeholder('Zum Beispiel „Kursübersicht“')
->maxLength(PageSections::MAX_NAME)
->live(onBlur: true)
->hintIcon('heroicon-m-information-circle', tooltip: 'Nur zur Orientierung im Seitenaufbau und in der Linkauswahl. Der Name erscheint nie auf der Website.')
->hintColor('gray'),
TextInput::make('anchor')
->label('Sprungmarke')
->prefix('#')
->placeholder('zum-beispiel-kurse')
->maxLength(PageSections::MAX_ANCHOR)
->live(onBlur: true)
->afterStateUpdated(function (?string $state, Set $set): void {
$set('anchor', filled($state) ? Str::slug($state, '-', 'de') : null);
})
->suffixAction(Action::make('anchorFromName')
->label('Sprungmarke aus dem Namen vorschlagen')
->icon('heroicon-o-sparkles')
->tooltip('Aus dem Namen vorschlagen')
->action(fn (Get $get, Set $set) => $set('anchor', Str::limit(Str::slug((string) $get('name'), '-', 'de'), PageSections::MAX_ANCHOR, ''))))
->hintIcon('heroicon-m-information-circle', tooltip: 'Macht den Abschnitt zum Ziel eines Links. Auf derselben Seite genügt „#marke“, von anderen Seiten und von außen „Adresse der Seite#marke“. Nur Kleinbuchstaben, Ziffern und Bindestriche; jede Marke einmal je Seite.')
->hintColor('gray')
->helperText(fn (Get $get, $livewire): ?string => self::anchorLinkText($get('anchor'), $livewire)),
Toggle::make('hidden')
->label('Auf der Website ausblenden')
->live()
->hintIcon('heroicon-m-information-circle', tooltip: 'Der Abschnitt bleibt im Entwurf erhalten, erscheint aber nicht auf der Website. Auch eine Sprungmarke dieses Abschnitts führt dann ins Leere. In der Seitenvorschau steht an seiner Stelle ein Hinweis.')
->hintColor('gray')
->columnSpanFull(),
])
->columns(['default' => 1, 'md' => 2]);
}
/**
* Vollständiger Link zur Sprungmarke (für Verweise von außen); eine neue Seite hat noch keine Adresse.
*/
private static function anchorLinkText(mixed $anchor, mixed $livewire): ?string
{
if (! is_string($anchor) || $anchor === '') {
return 'Ohne Sprungmarke ist der Abschnitt kein Linkziel.';
}
$path = is_object($livewire) && property_exists($livewire, 'record') && is_object($livewire->record ?? null) ? ($livewire->record->path ?? null) : null;
return is_string($path) && $path !== ''
? 'Link von anderen Seiten: '.($path === '/' ? '' : $path).'#'.$anchor.' · von außen: '.url($path === '/' ? '/' : $path).'#'.$anchor
: 'Link auf dieser Seite: #'.$anchor.'. Die Adresse für Verweise von außen steht nach dem ersten Speichern fest.';
}
private static function onWorkplace(mixed $livewire): bool
{
return is_object($livewire) && method_exists($livewire, 'openAbschnitt');
}
private static function widthField(): Select
{
return Select::make('width')
->label('Inhaltsbreite')
->options(SectionStyle::WIDTHS)
->default('standard')
->selectablePlaceholder(false)
->hintIcon('heroicon-o-question-mark-circle', 'Ein Hintergrund reicht immer über die ganze Bildschirmbreite.');
}
/**
* Hintergrund; Bild, Ausschnitt und Überlagerung nur beim Hintergrund „Bild“.
*
* @return list<mixed>
*/
private static function backgroundFields(): array
{
return [
Select::make('background')
->label('Hintergrund')
->options(SectionStyle::BACKGROUNDS)
->default('default')
->selectablePlaceholder(false)
->live(),
...array_map(
fn ($field) => $field->visible(fn (Get $get): bool => $get('background') === 'image')->columnSpan(['default' => 1, 'md' => 2]),
ImageRefFields::fields('Hintergrundbild'),
),
Select::make('focus')
->label('Bildausschnitt (Fokuspunkt)')
->options(SectionStyle::FOCUS)
->default('center')
->selectablePlaceholder(false)
->hintIcon('heroicon-o-question-mark-circle', '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)
->hintIcon('heroicon-o-question-mark-circle', 'Sorgt für lesbaren Text auf dem Bild.')
->visible(fn (Get $get): bool => $get('background') === 'image'),
];
}
/**
* @return list<mixed>
*/
private static function spacingFields(): array
{
return [
Select::make('spacing_top')
->label('Abstand oben')
->options(SectionStyle::SPACINGS)
->default(SectionStyle::DEFAULTS['spacing_top'])
->selectablePlaceholder(false)
->hintIcon('heroicon-o-question-mark-circle', 'Vor dem Inhalt. Zwischen zwei Abschnitten addieren sich „unten“ und „oben“; „Kein Abstand“ lässt einen Einstieg direkt unter der Kopfzeile beginnen.'),
Select::make('spacing_bottom')
->label('Abstand unten')
->options(SectionStyle::SPACINGS)
->default(SectionStyle::DEFAULTS['spacing_bottom'])
->selectablePlaceholder(false)
->hintIcon('heroicon-o-question-mark-circle', 'Nach dem Inhalt. Bei eigener Fläche liegen beide Abstände innerhalb der Fläche.'),
Select::make('gap')
->label('Widget-Abstand')
->options(SectionStyle::SPACINGS)
->default(SectionStyle::DEFAULTS['gap'])
->selectablePlaceholder(false)
->hintIcon('heroicon-o-question-mark-circle', 'Zwischen den Plätzen dieses Abschnitts, nebeneinander und gestapelt. Abstände innerhalb eines Widgets bleiben Sache des Widgets.'),
Select::make('divider')
->label('Trenner zum nächsten Abschnitt')
->options(SectionStyle::DIVIDERS)
->default('none')
->selectablePlaceholder(false),
];
}
/**
* 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(),
'name' => $section['name'] ?? null,
'anchor' => $section['anchor'] ?? null,
'hidden' => (bool) ($section['hidden'] ?? false),
'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,
'name' => is_string($section['name'] ?? null) ? $section['name'] : null,
'anchor' => is_string($section['anchor'] ?? null) ? $section['anchor'] : null,
'hidden' => (bool) ($section['hidden'] ?? false),
'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;
}
/**
* Fügt die Kopie eines Abschnitts direkt hinter dem Original ein. Kennungen bleiben gleich; beim Speichern
* behält das Original seine Kennungen und die Kopie erhält neue.
*
* @param array<string, mixed> $items
* @return array<string, mixed>
*/
public static function insertCopyAfter(array $items, string $key, string $newKey): array
{
if (! array_key_exists($key, $items)) {
return $items;
}
$result = [];
foreach ($items as $itemKey => $item) {
$result[$itemKey] = $item;
if ((string) $itemKey === $key) {
// Eine Sprungmarke gibt es je Seite nur einmal: Die Kopie bekommt keine, der Name wird kenntlich gemacht.
$copy = is_array($item) ? $item : [];
$copy['anchor'] = null;
$name = is_string($copy['name'] ?? null) ? trim($copy['name']) : '';
$copy['name'] = $name !== '' ? Str::limit($name, PageSections::MAX_NAME - 9, '').' (Kopie)' : null;
$result[$newKey] = $copy;
}
}
return $result;
}
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): HtmlString
{
$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();
}
}
// Kurz sichtbar: Nummer, Raster und nur abweichende Gestaltung. Vollständig im Titel und für Screenreader.
$style = SectionStyle::fromStored(is_array($state['style'] ?? null) ? $state['style'] : []);
$meta = ['Raster '.SectionLayouts::short($layout)];
if ($style['background'] !== 'default') {
$meta[] = SectionStyle::BACKGROUNDS[$style['background']] ?? $style['background'];
}
if ($style['width'] !== 'standard') {
$meta[] = SectionStyle::WIDTHS[$style['width']] ?? $style['width'];
}
if ($style['divider'] !== 'none') {
$meta[] = 'Trenner';
}
if ($names === []) {
$meta[] = 'noch leer';
}
$number = 'Abschnitt '.(($index ?? 0) + 1);
$given = PageSections::cleanName($state['name'] ?? null);
$anchor = PageSections::cleanAnchor($state['anchor'] ?? null);
$hidden = (bool) ($state['hidden'] ?? false);
$full = 'Raster '.SectionLayouts::short($layout).' · '.SectionStyle::summary($style)
.($names === [] ? ' · noch leer' : ' · '.implode(', ', $names));
// Der Name steht vorn; die Nummer bleibt als Orientierung daneben. Sprungmarke und „Ausgeblendet“ sind auch
// für Screenreader lesbar, die Nummer und die Rastermeta nicht doppelt.
$text = $given !== null ? $given : $number;
$badges = ($anchor !== null ? '<span class="luf-abschnitt-marke" title="Sprungmarke">#'.e($anchor).'</span>' : '')
.($hidden ? '<span class="luf-abschnitt-aus" title="Auf der Website ausgeblendet">Ausgeblendet</span>' : '');
$spoken = ($given !== null ? $number.': ' : '').($anchor !== null ? 'Sprungmarke '.$anchor.'. ' : '').($hidden ? 'Auf der Website ausgeblendet. ' : '').$full;
return new HtmlString('<span class="luf-abschnitt'.($hidden ? ' is-ausgeblendet' : '').'" title="'.e(($given !== null ? $number.' · ' : '').$full).'"><span class="luf-abschnitt-nr">'.e($text).'</span>'
.($given !== null ? '<span class="luf-abschnitt-nummer" aria-hidden="true">'.e($number).'</span>' : '')
.$badges
.'<span class="luf-abschnitt-meta" aria-hidden="true">'.e(implode(' · ', $meta)).'</span>'
.'<span class="vw-sr">: '.e($spoken).'</span></span>');
}
/**
* @param array<string, mixed> $state
*/
private static function slotLabel(array $state, ?int $index, mixed $layout): HtmlString
{
$text = self::slotText($state, $index, $layout);
// Plätze zeigen sich über Lage und Breite; benannt werden sie nur für Screenreader oder bei einem Problem.
return str_contains($text, 'passt nicht') || str_contains($text, 'außerhalb')
? new HtmlString('<span class="luf-platz-warnung">'.e($text).'</span>')
: new HtmlString('<span class="vw-sr">'.e($text).'</span>');
}
/**
* @param array<string, mixed> $state
*/
private static function slotText(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)->supportsUnits($slotUnits)) {
$label .= ' · passt nicht: „'.$registry->get($type)->label().'“ ist für '.$registry->get($type)->unitsLabel().' Einheiten vorgesehen';
}
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;
}
}