Files
laraundfelix/app/Filament/Support/ManagesEditorialSurface.php
T
LarsandClaude Opus 5.5 75596bdaec Führe Bausteine ohne Zwischenschritt und wähle CMS-Bilder im gemeinsamen Picker
- Bausteindialog: „Zum Seitenaufbau“ kehrt an die Stelle zurück, „Entwurf
  speichern“ übernimmt und speichert direkt; Fehler erscheinen wie beim Kopf.
- Karten mit Fachobjekt: zentrale Angaben aus der Redaktion als Platzhalter,
  eigene Angaben als „Eigene Angabe für diese Karte“ markiert.
- Bildfelder des CMS (Bausteine und Abschnittshintergrund) öffnen den
  gemeinsamen visuellen Picker statt einer eigenen Auswahlliste. Der allgemeine
  Teil des Pickers liegt im Trait ChoosesMedia (aus der Redaktion herausgelöst,
  nicht kopiert); ChoosesWebsiteImages übernimmt nur Website-Bilder in genau
  das auslösende Feld, auch im Bausteindialog. Keine Freigabe durch Auswahl.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:46:29 +01:00

1128 lines
36 KiB
PHP

<?php
namespace App\Filament\Support;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentVersionStatus;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\EditorialProfile;
use App\Domain\Catalog\EditorialProfileReader;
use App\Domain\Catalog\EditorialTextVariant;
use App\Domain\Catalog\PresentationMedia;
use App\Domain\Catalog\PresentationRole;
use App\Domain\Media\WebsiteRelease;
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Livewire\Attributes\Url;
/**
* Gemeinsamer Redaktionsmanager für Medien, Module, Programme und Lizenzartikel.
*
* Der Manager läuft in derselben Livewire-Komponente wie der Ausgangseditor. Dessen offene Eingaben bleiben dadurch
* beim Wechsel erhalten. Texte, Einordnung, Präsentationsmedien und abweichende Formulierungen sind ein Arbeitsstand,
* den nur „Redaktion speichern“ schreibt. Website-Freigaben eines Mediums wirken dagegen sofort und global.
*
* Die Seite liefert die objektspezifischen Teile: redaktionKopf(), redaktionFelder(), einordnungGruppen(),
* einordnungUnsaved(), saveRedaktionTexte() und resetRedaktionTexte().
*/
trait ManagesEditorialSurface
{
use ChoosesMedia;
/** Steht in der Adresse, damit „Zurück“ im Browser von der Redaktion in den Ausgangseditor führt. */
#[Url(as: 'redaktion', history: true)]
public bool $redaktionOpen = false;
public string $redaktionTab = 'texte';
public string $deskFeedback = '';
public bool $deskFeedbackError = false;
public string $redaktionFehlerFeld = '';
/** @var list<array{key: string, id: int|null, role: string, element_id: int, source: int|null}> */
public array $praesentation = [];
/** @var list<array{key: string, id: int|null, role: string, element_id: int, source: int|null}>|null */
public ?array $praesentationGespeichert = null;
public ?string $praesentationFokus = null;
/** @var list<array{field: string, audience: string, body: string}> */
public array $varianten = [];
/** @var list<array{field: string, audience: string, body: string}>|null */
public ?array $variantenGespeichert = null;
public string $variantAudience = 'kachel';
public string $variantField = 'teaser';
public string $variantBody = '';
public bool $ausgabeOpen = false;
/** @var array{aktion: string, argument: int|string|null, titel: string, text: string, label: string, gefahr: bool}|null */
public ?array $bestaetigung = null;
public function getBreadcrumbs(): array
{
return [];
}
public function getHeading(): string
{
return '';
}
public function getSubheading(): ?string
{
return null;
}
/**
* Wer die Redaktion über die Adresse öffnet, braucht dieselben Rechte wie über den Knopf.
*/
public function mountManagesEditorialSurface(): void
{
if ($this->redaktionOpen && ! $this->canViewEditorial()) {
$this->redaktionOpen = false;
}
}
/**
* Fragt eine folgenreiche Handlung im gemeinsamen Dialog nach. Nur die hier genannten Handlungen sind erlaubt.
*/
public function askConfirmation(string $aktion, int|string|null $argument = null): void
{
$title = null;
if ($argument !== null && in_array($aktion, ['releaseAssigned', 'withdrawAssigned'], true)) {
$element = ContentElement::query()->find((int) $argument);
$title = $element instanceof ContentElement ? (string) ($element->display_title ?: $element->working_title) : null;
}
$this->bestaetigung = match ($aktion) {
'discardRedaktion' => ['aktion' => $aktion, 'argument' => null, 'titel' => 'Änderungen der Redaktion verwerfen?', 'text' => 'Texte, Präsentationsmedien und Einordnung kehren zum gespeicherten Stand zurück. Offene Eingaben im '.(($this->redaktionKopf()['zurueck'] ?? '') !== '' ? 'Ausgangseditor' : 'Editor').' bleiben erhalten.', 'label' => 'Verwerfen', 'gefahr' => true],
'releaseAssigned' => ['aktion' => $aktion, 'argument' => $argument, 'titel' => '„'.($title ?? 'Medium').'“ für die Website freigeben?', 'text' => 'Die Freigabe gilt sofort für alle Verwendungen dieses Mediums, nicht nur hier. Gespeichert wird sie unabhängig von „Redaktion speichern“.', 'label' => 'Für die Website freigeben', 'gefahr' => false],
'withdrawAssigned' => ['aktion' => $aktion, 'argument' => $argument, 'titel' => 'Website-Freigabe von „'.($title ?? 'Medium').'“ zurücknehmen?', 'text' => 'Das Medium verschwindet sofort aus allen öffentlichen Verwendungen. Zuordnungen und übrige Inhalte bleiben erhalten.', 'label' => 'Freigabe zurücknehmen', 'gefahr' => true],
default => $this->extraConfirmation($aktion, $argument),
};
}
public function confirmConfirmation(): void
{
$frage = $this->bestaetigung;
$this->bestaetigung = null;
if ($frage === null) {
return;
}
match ($frage['aktion']) {
'discardRedaktion' => $this->discardRedaktion(),
'releaseAssigned' => $this->releaseAssigned((int) $frage['argument']),
'withdrawAssigned' => $this->withdrawAssigned((int) $frage['argument']),
default => $this->runExtraConfirmation($frage['aktion'], $frage['argument']),
};
}
public function cancelConfirmation(): void
{
$this->bestaetigung = null;
}
/**
* Seiten können weitere bestätigte Handlungen ergänzen.
*
* @return array{aktion: string, argument: int|string|null, titel: string, text: string, label: string, gefahr: bool}|null
*/
protected function extraConfirmation(string $aktion, int|string|null $argument): ?array
{
return null;
}
protected function runExtraConfirmation(string $aktion, int|string|null $argument): void {}
public function editorialSubject(): Model
{
return $this->getRecord();
}
public function editorialProfile(?string $audience = null): EditorialProfile
{
return app(EditorialProfileReader::class)->read($this->editorialSubject(), $audience);
}
public function canEditEditorial(): bool
{
return ContentElementResource::editor();
}
public function canReleasePresentation(): bool
{
return ContentElementResource::editor();
}
// ---------------------------------------------------------------- Wechsel, Status und Speichern
public function openRedaktion(string $tab = 'texte'): void
{
abort_unless($this->canViewEditorial(), 403);
$this->redaktionWillOpen();
$this->loadRedaktionStaging();
$this->redaktionOpen = true;
$this->redaktionTab = in_array($tab, ['texte', 'medien', 'einordnung'], true) ? $tab : 'texte';
$this->ausgabeOpen = false;
$this->deskFeedback = '';
}
/**
* Für Seiten, die beim Wechsel eigene Dialoge schließen. Offene Eingaben bleiben dabei erhalten.
*/
protected function redaktionWillOpen(): void {}
public function closeRedaktion(): void
{
$this->redaktionOpen = false;
$this->ausgabeOpen = false;
$this->closePicker();
$this->deskFeedback = '';
}
/**
* Browser-Zurück und -Vor setzen den Wert über die Adresse. Dann gelten dieselben Regeln wie beim Knopf.
*/
public function updatedRedaktionOpen(bool $value): void
{
if ($value) {
abort_unless($this->canViewEditorial(), 403);
$this->redaktionWillOpen();
$this->loadRedaktionStaging();
return;
}
$this->ausgabeOpen = false;
$this->closePicker();
$this->deskFeedback = '';
}
public function showRedaktionTab(string $tab): void
{
if (in_array($tab, ['texte', 'medien', 'einordnung'], true)) {
$this->redaktionTab = $tab;
}
}
public function canViewEditorial(): bool
{
return $this->canEditEditorial() || ContentElementResource::editor();
}
public function saveRedaktion(): void
{
$this->guardEditorial();
$this->loadRedaktionStaging();
$this->deskFeedbackError = false;
$this->redaktionFehlerFeld = '';
if (! $this->saveRedaktionTexte()) {
$this->deskFeedbackError = true;
$this->redaktionTab = 'texte';
return;
}
try {
if ($this->presentationUnsaved()) {
app(PresentationMedia::class)->commit($this->editorialSubject(), $this->praesentation, $this->deskActor(), $this->praesentationGespeichert);
}
if ($this->variantsUnsaved()) {
$this->commitVariants();
}
} catch (DomainRuleException $exception) {
$this->deskFeedback = 'Die Texte sind gespeichert. '.$exception->getMessage();
$this->deskFeedbackError = true;
return;
}
$this->praesentationGespeichert = null;
$this->variantenGespeichert = null;
$this->praesentationFokus = null;
$this->loadRedaktionStaging();
$this->deskFeedback = $this->redaktionSavedMessage();
}
public function discardRedaktion(): void
{
$this->resetRedaktionTexte();
$this->praesentationGespeichert = null;
$this->variantenGespeichert = null;
$this->praesentationFokus = null;
$this->loadRedaktionStaging();
$this->closePicker();
$this->deskFeedbackError = false;
$this->deskFeedback = 'Die ungespeicherten Änderungen der Redaktion sind verworfen. Die übrige Bearbeitung bleibt unverändert.';
}
public function redaktionOffen(): bool
{
return $this->redaktionUnsaved() || $this->presentationUnsaved() || $this->variantsUnsaved();
}
/**
* Welche Register ungespeicherte Änderungen enthalten.
*
* @return array{texte: bool, medien: bool, einordnung: bool}
*/
public function redaktionOffeneRegister(): array
{
$texte = $this->variantsUnsaved();
foreach ($this->redaktionFelder() as $feld) {
if ($this->feldGeaendert($feld)) {
$texte = true;
}
}
return [
'texte' => $texte,
'medien' => $this->presentationUnsaved(),
'einordnung' => $this->einordnungUnsaved(),
];
}
public function redaktionUnsaved(): bool
{
return $this->textFieldsChanged() || $this->einordnungUnsaved();
}
/**
* @param array<string, mixed> $feld
*/
public function feldGeaendert(array $feld): bool
{
$model = (string) $feld['model'];
return trim((string) $this->{$model}) !== trim((string) ($feld['stored'] ?? ''));
}
public function textFieldsChanged(): bool
{
foreach ($this->redaktionFelder() as $feld) {
if ($this->feldGeaendert($feld)) {
return true;
}
}
return false;
}
protected function redaktionSavedMessage(): string
{
return 'Die Redaktion ist gespeichert. Es entsteht keine neue Fassung.';
}
protected function loadRedaktionStaging(): void
{
if ($this->praesentationGespeichert === null) {
$this->praesentation = app(PresentationMedia::class)->staged($this->editorialSubject());
$this->praesentationGespeichert = $this->praesentation;
}
if ($this->variantenGespeichert === null) {
$this->varianten = $this->storedVariants();
$this->variantenGespeichert = $this->varianten;
}
}
// ---------------------------------------------------------------- Ausgabe prüfen
public function openAusgabe(): void
{
$this->ausgabeOpen = $this->redaktionAusgabe() !== null;
}
public function closeAusgabe(): void
{
$this->ausgabeOpen = false;
}
/**
* Ausgabe des Objekts für „Ausgabe prüfen“. Null, wenn es für diese Objektart keine Ausgabe gibt.
*
* @return array{html?: string, view?: string, stand: string}|null
*/
public function redaktionAusgabe(): ?array
{
return null;
}
// ---------------------------------------------------------------- Präsentationsmedien (Arbeitsstand)
public function presentationUnsaved(): bool
{
if ($this->praesentationGespeichert === null) {
return false;
}
return $this->stagingFingerprint($this->praesentation) !== $this->stagingFingerprint($this->praesentationGespeichert);
}
/**
* @return list<array{role: string, label: string, multiple: bool, ordered: bool, rows: list<array<string, mixed>>}>
*/
public function presentationGroups(): array
{
$this->loadRedaktionStaging();
return app(PresentationMedia::class)->describe($this->praesentation);
}
/**
* @return array<string, string>
*/
public function presentationRoleOptions(): array
{
$options = [];
foreach (PresentationRole::selectOptions() as $slug => $label) {
$options[$slug] = PresentationRole::displayLabel((string) $slug, (string) $label);
}
return $options;
}
public function removePresentation(string $key): void
{
$this->guardEditorial();
$before = count($this->praesentation);
$this->praesentation = array_values(array_filter($this->praesentation, fn (array $row): bool => $row['key'] !== $key));
if (count($this->praesentation) === $before) {
$this->feedback('Diese Zuordnung gibt es nicht mehr.', true);
return;
}
$this->praesentationFokus = null;
$this->feedback('Die Zuordnung ist entfernt. Das Medium bleibt im Bestand. Wirksam wird das mit „Redaktion speichern“.');
}
public function movePresentation(string $key, int $direction): void
{
$this->guardEditorial();
$index = $this->stagingIndex($key);
if ($index === null || $direction === 0) {
return;
}
$role = $this->praesentation[$index]['role'];
if (! $this->roleIsOrdered($role)) {
$this->feedback('Diese Rolle hat eine einzelne Zuordnung und wird nicht sortiert.', true);
return;
}
$siblings = $this->stagingIndexesOfRole($role);
$position = array_search($index, $siblings, true);
$target = $position + ($direction < 0 ? -1 : 1);
if ($position === false || ! isset($siblings[$target])) {
return;
}
$other = $siblings[$target];
[$this->praesentation[$index], $this->praesentation[$other]] = [$this->praesentation[$other], $this->praesentation[$index]];
$this->praesentationFokus = $key;
$this->deskFeedback = '';
}
public function placePresentation(string $key, string $beforeKey): void
{
$this->guardEditorial();
$from = $this->stagingIndex($key);
$to = $this->stagingIndex($beforeKey);
if ($from === null || $to === null || $from === $to) {
return;
}
$role = $this->praesentation[$from]['role'];
if ($this->praesentation[$to]['role'] !== $role || ! $this->roleIsOrdered($role)) {
$this->feedback('Die Reihenfolge gilt nur innerhalb einer Rolle.', true);
return;
}
$siblings = $this->stagingIndexesOfRole($role);
$fromPosition = array_search($from, $siblings, true);
$toPosition = array_search($to, $siblings, true);
$direction = $toPosition < $fromPosition ? -1 : 1;
for ($step = 0; $step < abs($toPosition - $fromPosition); $step++) {
$this->movePresentation($key, $direction);
}
}
public function releaseAssigned(int $elementId): void
{
abort_unless($this->canReleasePresentation(), 403);
$element = ContentElement::query()->find($elementId);
if (! $element instanceof ContentElement) {
$this->feedback('Das Medium fehlt.', true);
return;
}
$this->feedback(app(WebsiteRelease::class)->release($element, $this->deskActor()));
}
public function withdrawAssigned(int $elementId): void
{
abort_unless($this->canReleasePresentation(), 403);
$element = ContentElement::query()->find($elementId);
if (! $element instanceof ContentElement) {
$this->feedback('Das Medium fehlt.', true);
return;
}
$this->feedback(app(WebsiteRelease::class)->withdraw($element, $this->deskActor()));
}
// ---------------------------------------------------------------- Gemeinsamer Picker
public function openPresentationPicker(?string $role = null): void
{
$this->guardEditorial();
$this->loadRedaktionStaging();
$roles = $this->presentationRoleOptions();
$this->presentationRole = $role !== null && isset($roles[$role]) ? $role : $this->defaultRole();
$this->resetPicker('praesentation');
$this->pickerKind = $this->defaultKindForRole($this->presentationRole);
$this->replacingKey = $this->occupiedSingleRoleKey($this->presentationRole);
}
/**
* Erste freie Rolle für „Medien zuordnen“: das Titelbild, solange es fehlt, sonst die Galerie.
*/
protected function defaultRole(): string
{
$roles = $this->presentationRoleOptions();
if (isset($roles['titelbild']) && $this->stagingIndexesOfRole('titelbild') === []) {
return 'titelbild';
}
return isset($roles['galerie']) ? 'galerie' : (string) array_key_first($roles);
}
/**
* Schlüssel der vorhandenen Zuordnung, wenn eine Rolle nur ein Medium erlaubt und schon belegt ist.
*/
protected function occupiedSingleRoleKey(string $role): ?string
{
if ($this->roleAllowsMany($role)) {
return null;
}
$indexes = $this->stagingIndexesOfRole($role);
return $indexes === [] ? null : $this->praesentation[$indexes[0]]['key'];
}
public function beginExchange(string $key): void
{
$this->guardEditorial();
$index = $this->stagingIndex($key);
if ($index === null) {
$this->feedback('Diese Zuordnung gibt es nicht mehr.', true);
return;
}
$this->presentationRole = $this->praesentation[$index]['role'];
$this->resetPicker('austausch');
$this->replacingKey = $key;
$this->pickerKind = $this->defaultKindForRole($this->presentationRole);
}
public function updatedPresentationRole(string $value): void
{
if ($this->pickerPurpose === 'praesentation') {
$this->pickerKind = $this->defaultKindForRole($value);
$this->replacingKey = $this->occupiedSingleRoleKey($value);
}
if (! in_array($value, PresentationRole::BOUND_ROLES, true)) {
$this->bindToVersion = false;
}
if (! $this->pickerAllowsMany() && count($this->pickerMarked) > 1) {
$first = array_key_first($this->pickerMarked);
$this->pickerMarked = [$first => $this->pickerMarked[$first]];
}
}
public function closePicker(): void
{
$wasExchange = $this->pickerPurpose === 'austausch' && $this->pickerOpen;
$this->pickerOpen = false;
$this->pickerSelected = '';
$this->pickerInspected = '';
$this->pickerMarked = [];
$this->replacingKey = null;
if ($wasExchange) {
$this->feedback('Die vorhandene Zuordnung bleibt unverändert.');
}
}
public function pickerAllowsMany(): bool
{
return $this->pickerPurpose === 'praesentation' && $this->roleAllowsMany($this->presentationRole);
}
/**
* Für Seiten mit eigenem Vorschaubild: ein vorhandenes Bild als Vorschaubild übernehmen.
*/
protected function adoptThumbnailFromPicker(string $target): void {}
public function confirmPicker(): void
{
$marked = array_keys($this->pickerMarked);
if ($marked === []) {
return;
}
if ($this->pickerPurpose === 'aufbau') {
$target = $marked[0];
$this->closePicker();
if (method_exists($this, 'addPart')) {
$this->addPart($target);
}
return;
}
$this->guardEditorial();
if ($this->pickerPurpose === 'austausch' || ($this->pickerPurpose === 'praesentation' && $this->replacingKey !== null)) {
$this->exchangeStaged($marked[0]);
return;
}
if ($this->pickerPurpose === 'vorschaubild') {
$this->closePicker();
$this->adoptThumbnailFromPicker($marked[0]);
return;
}
$added = [];
$notes = [];
foreach ($marked as $target) {
$result = $this->stageTarget($target);
if ($result === true) {
$added[] = $this->pickerMarked[$target];
} else {
$notes[] = $result;
}
}
$this->pickerOpen = false;
$this->pickerMarked = [];
$this->pickerSelected = '';
$this->pickerInspected = '';
$this->redaktionTab = 'medien';
$label = $this->presentationRoleOptions()[$this->presentationRole] ?? 'Rolle';
$message = $added === []
? ''
: (count($added) === 1 ? '„'.$added[0].'“ ist' : count($added).' Medien sind').' als '.$label.' vorgemerkt. Wirksam wird das mit „Redaktion speichern“.';
$this->feedback(trim($message.' '.implode(' ', $notes)), $added === []);
}
/**
* Einzelnes Ziel direkt übernehmen (Tastatur- und Testpfad für den Picker).
*/
public function assignFromPicker(string $target): void
{
if (! $this->pickerOpen) {
$this->openPresentationPicker($this->presentationRole);
}
$this->pickerMarked = [];
$this->markPicker($target, true);
$this->confirmPicker();
}
/**
* @return array<string, string>
*/
public function pickerKinds(): array
{
if ($this->pickerPurpose === 'vorschaubild') {
return ['bild' => 'Bilder'];
}
if ($this->pickerPurpose === 'aufbau') {
return ['alle' => 'Alle Inhalte', 'film' => 'Filme', 'bild' => 'Bilder', 'audio' => 'Hörstücke', 'dokument' => 'Dokumente', 'text' => 'Texte', 'modul' => 'Module'];
}
return ['alle' => 'Alle Medien', 'bild' => 'Bilder', 'film' => 'Filme', 'audio' => 'Hörstücke', 'dokument' => 'Dokumente'];
}
/**
* @return array{art: string, titel: string}
*/
public function pickerKontext(): array
{
return ['art' => (string) ($this->redaktionKopf()['fuer'] ?? 'das Objekt'), 'titel' => $this->redaktionTitel()];
}
public function pickerTitle(): string
{
return match ($this->pickerPurpose) {
'aufbau' => 'Bestandteil auswählen',
'austausch' => 'Medium austauschen',
'vorschaubild' => 'Vorschaubild aus dem Bestand',
default => 'Medien auswählen',
};
}
public function pickerConfirmLabel(): string
{
$count = count($this->pickerMarked);
if ($this->pickerPurpose === 'praesentation' && $this->replacingKey !== null) {
return 'Austauschen';
}
return match ($this->pickerPurpose) {
'aufbau' => 'In den Aufbau übernehmen',
'austausch' => 'Austauschen',
'vorschaubild' => 'Als Vorschaubild übernehmen',
default => $count === 1 ? '1 Medium übernehmen' : ($count === 0 ? 'Medien übernehmen' : $count.' Medien übernehmen'),
};
}
public function pickerReplacing(): ?array
{
if ($this->replacingKey === null) {
return null;
}
foreach ($this->presentationGroups() as $group) {
foreach ($group['rows'] as $row) {
if ($row['key'] === $this->replacingKey) {
return $row + ['role_label' => $group['label']];
}
}
}
return null;
}
protected function defaultKindForRole(string $role): string
{
return match ($role) {
'titelbild', 'titelbild_alternativ', 'hero', 'hover', 'galerie' => 'bild',
'trailer', 'vorschauclip', 'interview' => 'film',
'audiovorschau' => 'audio',
default => 'alle',
};
}
/**
* Ein Ziel in den Arbeitsstand der gewählten Rolle aufnehmen.
*/
protected function stageTarget(string $target): true|string
{
$elementId = $this->elementIdOf($target);
if ($elementId === null) {
return 'Präsentationsmedien sind Medien aus dem Bestand.';
}
$refusal = app(PresentationMedia::class)->refusal($this->editorialSubject(), $this->presentationRole, $elementId);
if ($refusal !== null) {
return $refusal;
}
foreach ($this->praesentation as $row) {
if ($row['role'] === $this->presentationRole && $row['element_id'] === $elementId) {
return '„'.($this->pickerMarked[$target] ?? 'Dieses Medium').'“ ist in dieser Rolle bereits zugeordnet.';
}
}
$row = [
'key' => 'n'.bin2hex(random_bytes(4)),
'id' => null,
'role' => $this->presentationRole,
'element_id' => $elementId,
'source' => $this->sourceFor($target),
];
if (! $this->roleAllowsMany($this->presentationRole)) {
$existing = $this->stagingIndexesOfRole($this->presentationRole);
if ($existing !== []) {
$this->praesentation[$existing[0]] = $row;
$this->praesentationFokus = $row['key'];
return true;
}
}
$this->insertStaged($row);
$this->praesentationFokus = $row['key'];
return true;
}
protected function exchangeStaged(string $target): void
{
$index = $this->replacingKey !== null ? $this->stagingIndex($this->replacingKey) : null;
$elementId = $this->elementIdOf($target);
if ($index === null || $elementId === null) {
$this->closePicker();
$this->feedback('Diese Zuordnung gibt es nicht mehr.', true);
return;
}
$old = $this->praesentation[$index];
$refusal = app(PresentationMedia::class)->refusal($this->editorialSubject(), $old['role'], $elementId);
foreach ($this->praesentation as $other) {
if ($other['key'] !== $old['key'] && $other['role'] === $old['role'] && $other['element_id'] === $elementId) {
$refusal = 'Dieses Medium ist in dieser Rolle bereits zugeordnet.';
}
}
if ($refusal !== null) {
$this->feedback($refusal, true);
return;
}
$title = $this->pickerMarked[$target] ?? 'Das neue Medium';
$oldTitle = ContentElement::query()->whereKey($old['element_id'])->value('working_title');
$this->praesentation[$index] = [
'key' => $old['element_id'] === $elementId ? $old['key'] : 'n'.bin2hex(random_bytes(4)),
'id' => $old['element_id'] === $elementId ? $old['id'] : null,
'role' => $old['role'],
'element_id' => $elementId,
'source' => $old['element_id'] === $elementId ? $old['source'] : $this->sourceFor($target, $old['role']),
];
$this->praesentationFokus = $this->praesentation[$index]['key'];
$this->pickerOpen = false;
$this->pickerMarked = [];
$this->pickerSelected = '';
$this->pickerInspected = '';
$this->replacingKey = null;
$this->feedback('„'.$title.'“ ersetzt „'.($oldTitle ?? 'die bisherige Zuordnung').'“ an derselben Stelle. Wirksam wird das mit „Redaktion speichern“.');
}
protected function insertStaged(array $row): void
{
$order = array_keys($this->presentationRoleOptions());
$rank = array_search($row['role'], $order, true);
$insertAt = count($this->praesentation);
foreach ($this->praesentation as $index => $existing) {
$existingRank = array_search($existing['role'], $order, true);
if ($existingRank !== false && $rank !== false && $existingRank > $rank) {
$insertAt = $index;
break;
}
}
array_splice($this->praesentation, $insertAt, 0, [$row]);
$this->praesentation = array_values($this->praesentation);
}
protected function elementIdOf(string $target): ?int
{
if (preg_match('/^medium:(\d+)$/', $target, $match) === 1) {
return (int) $match[1];
}
if (preg_match('/^element:(\d+)$/', $target, $match) === 1) {
$id = ContentElementVersion::query()->whereKey((int) $match[1])->value('content_element_id');
return $id !== null ? (int) $id : null;
}
return null;
}
protected function sourceFor(string $target, ?string $role = null): ?int
{
$role ??= $this->presentationRole;
if (! $this->bindToVersion || ! in_array($role, PresentationRole::BOUND_ROLES, true)) {
return null;
}
$subject = $this->editorialSubject();
if ($subject instanceof ContentElement) {
$id = $subject->versions()->where('status', ContentVersionStatus::Bereit)->orderByDesc('number')->value('id');
return $id !== null ? (int) $id : null;
}
return preg_match('/^element:(\d+)$/', $target, $match) === 1 ? (int) $match[1] : null;
}
protected function stagingIndex(string $key): ?int
{
foreach ($this->praesentation as $index => $row) {
if ($row['key'] === $key) {
return $index;
}
}
return null;
}
/**
* @return list<int>
*/
protected function stagingIndexesOfRole(string $role): array
{
$indexes = [];
foreach ($this->praesentation as $index => $row) {
if ($row['role'] === $role) {
$indexes[] = $index;
}
}
return $indexes;
}
protected function roleIsOrdered(string $role): bool
{
return (bool) PresentationRole::query()->where('slug', $role)->value('ordered');
}
protected function roleAllowsMany(string $role): bool
{
return (bool) PresentationRole::query()->where('slug', $role)->value('multiple');
}
/**
* @param list<array<string, mixed>> $rows
*/
protected function stagingFingerprint(array $rows): string
{
return json_encode(array_map(
fn (array $row): array => [$row['id'], $row['role'], (int) $row['element_id'], $row['source']],
$rows,
), JSON_THROW_ON_ERROR);
}
// ---------------------------------------------------------------- Abweichende Formulierungen (Arbeitsstand)
/**
* @return list<array{field: string, audience: string, body: string}>
*/
public function variantRows(): array
{
$this->loadRedaktionStaging();
return $this->varianten;
}
public function variantsUnsaved(): bool
{
if ($this->variantenGespeichert === null) {
return false;
}
return $this->variantFingerprint($this->varianten) !== $this->variantFingerprint($this->variantenGespeichert);
}
public function saveVariant(): void
{
$this->guardEditorial();
$this->loadRedaktionStaging();
$body = trim($this->variantBody);
if (! in_array($this->variantField, EditorialProfileReader::TEXT_FIELDS, true) || ! array_key_exists($this->variantAudience, EditorialProfileReader::AUDIENCES)) {
$this->feedback('Diese Abweichung ist nicht vorgesehen.', true);
return;
}
$this->varianten = array_values(array_filter(
$this->varianten,
fn (array $row): bool => ! ($row['field'] === $this->variantField && $row['audience'] === $this->variantAudience),
));
if ($body !== '') {
$this->varianten[] = ['field' => $this->variantField, 'audience' => $this->variantAudience, 'body' => $body];
}
$this->variantBody = '';
$this->deskFeedback = '';
}
public function editVariant(string $field, string $audience): void
{
foreach ($this->varianten as $row) {
if ($row['field'] === $field && $row['audience'] === $audience) {
$this->variantField = $field;
$this->variantAudience = $audience;
$this->variantBody = $row['body'];
}
}
}
public function forgetVariant(string $field, string $audience): void
{
$this->guardEditorial();
$this->loadRedaktionStaging();
$this->varianten = array_values(array_filter(
$this->varianten,
fn (array $row): bool => ! ($row['field'] === $field && $row['audience'] === $audience),
));
}
public function variantFieldLabel(string $field): string
{
return match ($field) {
'display_title' => 'Anzeigename',
'teaser' => 'Teaser',
'summary' => 'Kurzbeschreibung',
'description' => 'Ausführliche Beschreibung',
default => $field,
};
}
/**
* @return list<array{field: string, audience: string, body: string}>
*/
protected function storedVariants(): array
{
$subject = $this->editorialSubject();
return EditorialTextVariant::query()
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->orderBy('audience')
->orderBy('field')
->get()
->map(fn (EditorialTextVariant $variant): array => [
'field' => (string) $variant->field,
'audience' => (string) $variant->audience,
'body' => (string) $variant->body,
])
->all();
}
protected function commitVariants(): void
{
$reader = app(EditorialProfileReader::class);
$subject = $this->editorialSubject();
$wanted = [];
foreach ($this->varianten as $row) {
$wanted[$row['field'].'|'.$row['audience']] = $row;
}
foreach ($this->variantenGespeichert ?? [] as $row) {
if (! isset($wanted[$row['field'].'|'.$row['audience']])) {
$reader->putVariant($subject, $row['field'], $row['audience'], null, $this->deskActor());
}
}
foreach ($wanted as $row) {
$reader->putVariant($subject, $row['field'], $row['audience'], $row['body'], $this->deskActor());
}
}
/**
* @param list<array{field: string, audience: string, body: string}> $rows
*/
protected function variantFingerprint(array $rows): string
{
$keys = array_map(fn (array $row): string => $row['field'].'|'.$row['audience'].'|'.trim($row['body']), $rows);
sort($keys);
return implode("\n", $keys);
}
// ---------------------------------------------------------------- Hilfen
/**
* Fehlende zentrale Texte, für den Hinweis im Register Texte.
*
* @return list<string>
*/
public function editorialGaps(): array
{
$profile = $this->editorialProfile();
$gaps = [];
foreach (['display_title' => 'Anzeigename', 'teaser' => 'Teaser', 'summary' => 'Kurzbeschreibung', 'description' => 'Ausführliche Beschreibung'] as $field => $label) {
if ($profile->value($field) === null) {
$gaps[] = $label;
}
}
return $gaps;
}
public function clearFeedback(): void
{
$this->deskFeedback = '';
if (property_exists($this, 'feedback')) {
$this->feedback = '';
}
}
protected function feedback(string $message, bool $error = false): void
{
$this->deskFeedback = $message;
$this->deskFeedbackError = $error;
}
protected function guardEditorial(): void
{
abort_unless($this->canEditEditorial(), 403);
}
protected function deskActor(): ?User
{
$user = auth()->user();
return $user instanceof User ? $user : null;
}
}