435 lines
17 KiB
PHP
435 lines
17 KiB
PHP
<?php
|
|
|
|
namespace App\Filament\Resources\Pages\Pages;
|
|
|
|
use App\Domain\Catalog\PillarService;
|
|
use App\Domain\Cms\Page;
|
|
use App\Domain\Cms\PageService;
|
|
use App\Domain\Cms\Sections\PageSections;
|
|
use App\Domain\Cms\SectionTransfer;
|
|
use App\Filament\Resources\Pages\PageResource;
|
|
use App\Filament\Support\ChoosesLinkTargets;
|
|
use App\Filament\Support\ChoosesWebsiteImages;
|
|
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\Schemas\Components\Group;
|
|
use Filament\Schemas\Schema;
|
|
use Filament\Support\Enums\Width;
|
|
use Illuminate\Contracts\View\View;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Livewire\Attributes\Url;
|
|
|
|
class EditPage extends EditRecord
|
|
{
|
|
use ChoosesLinkTargets;
|
|
use ChoosesWebsiteImages;
|
|
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;
|
|
|
|
/** Warnt vor dem Verlassen oder Neuladen, wenn Änderungen noch nicht gespeichert sind. */
|
|
protected ?bool $hasUnsavedDataChangesAlert = true;
|
|
|
|
/** Register des Seiten-Arbeitsplatzes: inhalt, einstellungen, verlauf (Dokument 12, CMS-R01). */
|
|
#[Url(as: 'bereich', except: 'inhalt')]
|
|
public string $register = 'inhalt';
|
|
|
|
/**
|
|
* Kontext „Abschnitt gestalten“: Position des Abschnitts (die Repeater-Schlüssel wechseln beim Speichern,
|
|
* die Reihenfolge nicht). null ist der Seitenaufbau.
|
|
*/
|
|
#[Url(as: 'abschnitt', except: null)]
|
|
public ?int $abschnitt = null;
|
|
|
|
/** Fingerabdruck des zuletzt geladenen oder gespeicherten Stands; Grundlage für „nicht gespeichert“. */
|
|
public string $gespeicherterStand = '';
|
|
|
|
public function showRegister(string $register): void
|
|
{
|
|
$this->register = in_array($register, ['inhalt', 'einstellungen', 'verlauf'], true) ? $register : 'inhalt';
|
|
$this->abschnitt = null;
|
|
}
|
|
|
|
public function openAbschnitt(string $key): void
|
|
{
|
|
$index = array_search($key, array_map('strval', array_keys($this->data['sections'] ?? [])), true);
|
|
|
|
if ($index === false) {
|
|
return;
|
|
}
|
|
|
|
$this->register = 'inhalt';
|
|
$this->abschnitt = (int) $index;
|
|
$this->js('window.scrollTo({ top: 0 })');
|
|
}
|
|
|
|
/**
|
|
* Zurück zum Seitenaufbau, an die Stelle des gestalteten Abschnitts (Fokus auf „Abschnitt gestalten“).
|
|
*/
|
|
public function closeAbschnitt(): void
|
|
{
|
|
$key = $this->abschnittSchluessel();
|
|
$this->abschnitt = null;
|
|
|
|
if ($key !== null) {
|
|
$selector = json_encode('.luf-sections [x-sortable-item="'.$key.'"]');
|
|
$this->js("requestAnimationFrame(() => requestAnimationFrame(() => { const el = document.querySelector($selector); if (! el) return; window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 96 }); [...el.querySelectorAll('button')].find((b) => b.textContent.includes('Abschnitt gestalten'))?.focus({ preventScroll: true }); }))");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Repeater-Schlüssel des gestalteten Abschnitts, aufgelöst zur Laufzeit.
|
|
*/
|
|
public function abschnittSchluessel(): ?string
|
|
{
|
|
if ($this->abschnitt === null) {
|
|
return null;
|
|
}
|
|
|
|
$keys = array_map('strval', array_keys($this->data['sections'] ?? []));
|
|
|
|
return $keys[$this->abschnitt] ?? null;
|
|
}
|
|
|
|
/**
|
|
* Gemeinsamer Objektkopf statt Filaments Titel, Pfad und Kopfaktionen.
|
|
*/
|
|
public function getHeader(): ?View
|
|
{
|
|
return view('filament.cms.seite-kopf', ['seite' => $this->record, 'ungespeichert' => $this->hasUnsavedEditorChanges()]);
|
|
}
|
|
|
|
/**
|
|
* Weicht der Editorstand vom geladenen oder gespeicherten Stand ab? Verglichen wird derselbe normalisierte
|
|
* Zustand, der auch gespeichert würde; Vorschaubreiten zählen nicht.
|
|
*/
|
|
public function hasUnsavedEditorChanges(): bool
|
|
{
|
|
return $this->gespeicherterStand !== '' && $this->editorFingerprint() !== $this->gespeicherterStand;
|
|
}
|
|
|
|
protected function afterFill(): void
|
|
{
|
|
$this->gespeicherterStand = $this->editorFingerprint();
|
|
}
|
|
|
|
private function editorFingerprint(): string
|
|
{
|
|
$data = is_array($this->data ?? null) ? $this->data : [];
|
|
$pillars = array_map('intval', (array) ($data['pillars'] ?? []));
|
|
sort($pillars);
|
|
|
|
return md5(json_encode([
|
|
self::withoutPreviewKeys(SectionEditor::fromEditorState(is_array($data['sections'] ?? null) ? $data['sections'] : [])),
|
|
(string) ($data['path'] ?? ''),
|
|
(string) ($data['seo_title'] ?? ''),
|
|
(string) ($data['seo_description'] ?? ''),
|
|
$pillars,
|
|
], JSON_UNESCAPED_UNICODE) ?: '');
|
|
}
|
|
|
|
private static function withoutPreviewKeys(mixed $value): mixed
|
|
{
|
|
if (! is_array($value)) {
|
|
return $value;
|
|
}
|
|
|
|
unset($value['_preview_width']);
|
|
|
|
return array_map(self::withoutPreviewKeys(...), $value);
|
|
}
|
|
|
|
/**
|
|
* Formular und Verlauf (Revisionen) als Register; ausgeblendete Teile bleiben im Formularzustand.
|
|
*/
|
|
public function content(Schema $schema): Schema
|
|
{
|
|
return $schema->components([
|
|
$this->getFormContentComponent(),
|
|
Group::make([$this->getRelationManagersContentComponent()])
|
|
->extraAttributes(fn (): array => ['class' => $this->register === 'verlauf' ? '' : 'vw-ausgeblendet']),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Speichern steht im Kopf; die Leiste unter dem Formular entfällt.
|
|
*/
|
|
protected function getFormActions(): array
|
|
{
|
|
return [];
|
|
}
|
|
|
|
/**
|
|
* Ein Fehler in einem gerade ausgeblendeten Register oder Abschnittsteil wird sichtbar gemacht (CMS-12).
|
|
*/
|
|
public function save(bool $shouldRedirect = true, bool $shouldSendSavedNotification = true): void
|
|
{
|
|
try {
|
|
parent::save($shouldRedirect, $shouldSendSavedNotification);
|
|
} catch (ValidationException $exception) {
|
|
$keys = implode(' ', array_keys($exception->errors()));
|
|
$this->register = str_contains($keys, 'data.sections') ? 'inhalt' : (preg_match('/data\.(path|seo_|pillars)/', $keys) === 1 ? 'einstellungen' : $this->register);
|
|
$this->showFailingSection(array_keys($exception->errors()));
|
|
|
|
// Name und Sprungmarke stehen im Einstellungsdialog; die Meldung am Abschnitt führt dorthin. Hierher scrollen.
|
|
if (preg_match('/data\.sections\.[^.]+\.(name|anchor)(\.|\s|$)/', $keys) === 1) {
|
|
$this->js("requestAnimationFrame(() => requestAnimationFrame(() => document.querySelector('[data-abschnitt-fehler]')?.scrollIntoView({ block: 'center' })))");
|
|
}
|
|
|
|
throw $exception;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Raster und Gestaltung stehen nur im Kontext „Abschnitt gestalten“, andere Abschnitte sind dort ausgeblendet.
|
|
* Liegt der Fehler im gestalteten Abschnitt, bleibt der Kontext. Ein Raster- oder Gestaltungsfehler öffnet den
|
|
* betroffenen Abschnitt; jeder andere Abschnittsfehler (etwa die Platzübersicht) steht im Seitenaufbau.
|
|
*
|
|
* @param list<string> $errorKeys
|
|
*/
|
|
private function showFailingSection(array $errorKeys): void
|
|
{
|
|
$sectionKeys = array_map('strval', array_keys($this->data['sections'] ?? []));
|
|
$failing = [];
|
|
$design = null;
|
|
|
|
foreach ($errorKeys as $key) {
|
|
if (preg_match('/^data\.sections\.([^.]+)(?:\.(.*))?$/', $key, $match) !== 1) {
|
|
continue;
|
|
}
|
|
|
|
$index = array_search($match[1], $sectionKeys, true);
|
|
if ($index === false) {
|
|
continue;
|
|
}
|
|
|
|
$failing[] = $index;
|
|
if ($design === null && preg_match('/^(layout|style)(\.|$)/', $match[2] ?? '') === 1) {
|
|
$design = $index;
|
|
}
|
|
}
|
|
|
|
if ($failing === [] || ($this->abschnitt !== null && in_array($this->abschnitt, $failing, true))) {
|
|
return;
|
|
}
|
|
|
|
$this->abschnitt = $design;
|
|
}
|
|
|
|
/**
|
|
* „Entwurf speichern“ aus dem Bausteindialog: Der Baustein ist bereits übernommen, der Dialog schließt. Ein Fehler
|
|
* wird wie beim Speichern im Kopf gezeigt (Register, Abschnitt, Meldung), ohne den Baustein erneut zu öffnen.
|
|
*/
|
|
public function saveFromBlock(): void
|
|
{
|
|
// Nach einer Dialogaktion rendert Filament sonst nur den Dialog neu; der Kopf zeigte den alten Speicherstand.
|
|
$this->forceRender();
|
|
|
|
try {
|
|
$this->save(shouldRedirect: false);
|
|
} catch (ValidationException $exception) {
|
|
foreach ($exception->errors() as $key => $messages) {
|
|
foreach ((array) $messages as $message) {
|
|
$this->addError($key, $message);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Abschnitt auf eine andere Seite kopieren oder verschieben (Schalter im Abschnittskopf). Der Abschnitt stammt aus
|
|
* dem Arbeitsstand dieser Seite. Die Zielseite erhält eine neue Entwurfsrevision. Beim Verschieben wird er danach
|
|
* aus dem Arbeitsstand entfernt und die Seite als Entwurf gespeichert. Geprüft wird vor dem ersten Schreiben:
|
|
* scheitert eine Seite, bleibt beides unverändert.
|
|
*/
|
|
public function transferSection(string $key, int $targetId, string $position, bool $move): void
|
|
{
|
|
$this->forceRender();
|
|
$raw = is_array($this->data['sections'] ?? null) ? $this->data['sections'] : [];
|
|
$target = Page::query()->find($targetId);
|
|
|
|
if (! isset($raw[$key]) || $target === null || $target->is($this->record)) {
|
|
Notification::make()->title('Zielseite oder Abschnitt nicht gefunden')->danger()->send();
|
|
|
|
return;
|
|
}
|
|
|
|
abort_unless(auth()->user()?->can('update', $target) ?? false, 403);
|
|
|
|
// Der Arbeitsstand in der Form wie beim Speichern (formatierte Texte als HTML, Leeres entfernt).
|
|
try {
|
|
$state = $this->form->getState()['sections'] ?? [];
|
|
} catch (ValidationException) {
|
|
Notification::make()->title($move ? 'Abschnitt nicht verschoben' : 'Abschnitt nicht kopiert')->body('Auf dieser Seite gibt es noch Eingabefehler. Bitte zuerst beheben.')->danger()->send();
|
|
|
|
return;
|
|
}
|
|
|
|
// Die Schlüssel des Formulars gehen beim Aufbereiten verloren; die Reihenfolge bleibt.
|
|
$index = array_search($key, array_map('strval', array_keys($raw)), true);
|
|
$items = array_values(is_array($state) ? $state : []);
|
|
|
|
if ($index === false || ! isset($items[$index])) {
|
|
Notification::make()->title('Zielseite oder Abschnitt nicht gefunden')->danger()->send();
|
|
|
|
return;
|
|
}
|
|
|
|
$transfer = app(SectionTransfer::class);
|
|
$section = SectionEditor::fromEditorState([$items[$index]])[0] ?? [];
|
|
$remaining = $items;
|
|
unset($remaining[$index]);
|
|
|
|
try {
|
|
$transfer->plan($target, $section, $position, ! $move);
|
|
|
|
if ($move) {
|
|
// Die Quellseite muss ohne den Abschnitt gültig bleiben, sonst wird nichts geschrieben.
|
|
app(PageSections::class)->normalize(SectionEditor::fromEditorState($remaining));
|
|
}
|
|
|
|
$result = $transfer->insert($target, $section, $position, ! $move, auth()->user());
|
|
} catch (ValidationException $exception) {
|
|
Notification::make()
|
|
->title($move ? 'Abschnitt nicht verschoben' : 'Abschnitt nicht kopiert')
|
|
->body(collect($exception->errors())->flatten()->first() ?? 'Die Seite wäre danach ungültig.')
|
|
->danger()
|
|
->send();
|
|
|
|
return;
|
|
}
|
|
|
|
if ($move) {
|
|
unset($raw[$key]);
|
|
$this->data['sections'] = $raw;
|
|
// Der Kontext „Abschnitt gestalten“ merkt sich eine Position, die sich durch das Entfernen verschiebt.
|
|
$this->abschnitt = null;
|
|
|
|
try {
|
|
$this->save(shouldRedirect: false, shouldSendSavedNotification: false);
|
|
} catch (ValidationException $exception) {
|
|
foreach ($exception->errors() as $errorKey => $messages) {
|
|
foreach ((array) $messages as $message) {
|
|
$this->addError($errorKey, $message);
|
|
}
|
|
}
|
|
Notification::make()->title('Auf der Zielseite eingefügt, hier nicht gespeichert')->body('Bitte die markierten Fehler beheben und „Entwurf speichern“ wählen; sonst steht der Abschnitt auf beiden Seiten.')->warning()->send();
|
|
|
|
return;
|
|
}
|
|
}
|
|
|
|
$anchorNote = match (true) {
|
|
! $result['anchorChanged'] => '',
|
|
$result['anchor'] !== null => ' Die Sprungmarke war dort vergeben und heißt jetzt „'.$result['anchor'].'“.',
|
|
default => ' Die Sprungmarke war dort vergeben; der Abschnitt hat keine mehr.',
|
|
};
|
|
|
|
Notification::make()
|
|
->title($move ? 'Abschnitt verschoben' : 'Abschnitt kopiert')
|
|
->body('Als Abschnitt '.$result['position'].' auf '.$target->path.' eingefügt (Entwurf, noch nicht veröffentlicht).'.$anchorNote)
|
|
->success()
|
|
->actions([Action::make('open')->label('Zielseite öffnen')->url(PageResource::getUrl('edit', ['record' => $target]))->button()])
|
|
->send();
|
|
}
|
|
|
|
protected function getHeaderActions(): array
|
|
{
|
|
return [];
|
|
}
|
|
|
|
public function publishAction(): Action
|
|
{
|
|
return Action::make('publish')
|
|
->label('Veröffentlichen')
|
|
->icon('heroicon-o-globe-alt')
|
|
->requiresConfirmation()
|
|
->modalHeading('Seite veröffentlichen?')
|
|
->modalDescription('Der aktuelle Stand im Editor wird als Entwurf gespeichert und genau dieser Stand wird veröffentlicht. Enthält er Fehler, wird nichts veröffentlicht.')
|
|
->modalSubmitActionLabel('Speichern und veröffentlichen')
|
|
->visible(fn (): bool => auth()->user()?->can('publish', $this->record) ?? false)
|
|
->action(function (PageService $service): void {
|
|
// Ungespeicherte Änderungen (zum Beispiel ein eben gewähltes Bild) gingen sonst beim Veröffentlichen verloren.
|
|
$this->save(shouldRedirect: false, shouldSendSavedNotification: false);
|
|
|
|
$this->record->unsetRelation('latestRevision');
|
|
$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();
|
|
});
|
|
}
|
|
|
|
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.';
|
|
}
|
|
|
|
/**
|
|
* Nach dem Speichern den Editor aus der gespeicherten Revision neu befüllen, damit duplizierte
|
|
* Abschnitte ihre beim Speichern vergebene Kennung behalten.
|
|
*/
|
|
protected function afterSave(): void
|
|
{
|
|
$this->record->unsetRelation('latestRevision');
|
|
$this->fillForm();
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $data
|
|
* @return array<string, mixed>
|
|
*/
|
|
protected function mutateFormDataBeforeFill(array $data): array
|
|
{
|
|
$revision = $this->record->latestRevision ?? $this->record->publishedRevision;
|
|
$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();
|
|
|
|
return $data;
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $data
|
|
*/
|
|
protected function handleRecordUpdate(Model $record, array $data): Model
|
|
{
|
|
/** @var Page $record */
|
|
$service = app(PageService::class);
|
|
$content = SectionEditor::fromEditorState($data['sections'] ?? []);
|
|
|
|
try {
|
|
$path = $service->availablePath($data['path'], $record);
|
|
$service->saveRevision($record, $content, $data['seo_title'] ?? null, $data['seo_description'] ?? null, auth()->user());
|
|
} catch (ValidationException $exception) {
|
|
SectionEditor::notifyErrors($exception->errors(), $this->data['sections'] ?? []);
|
|
|
|
throw ValidationException::withMessages(
|
|
SectionEditor::mapErrors($exception->errors(), $this->data['sections'] ?? []),
|
|
);
|
|
}
|
|
|
|
$record->update([
|
|
'path' => $path,
|
|
]);
|
|
app(PillarService::class)->assignPages($record, array_map(intval(...), $data['pillars'] ?? []));
|
|
|
|
return $record;
|
|
}
|
|
}
|