329 lines
12 KiB
PHP
329 lines
12 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\Filament\Resources\Pages\PageResource;
|
|
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 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()));
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|