diff --git a/app/Domain/Cms/Blocks/BlockRegistry.php b/app/Domain/Cms/Blocks/BlockRegistry.php deleted file mode 100644 index a699052..0000000 --- a/app/Domain/Cms/Blocks/BlockRegistry.php +++ /dev/null @@ -1,181 +0,0 @@ - - */ - public function labels(): array - { - return [ - 'heading' => 'Überschrift und Einleitung', - 'prose' => 'Fließtext', - 'image_text' => 'Bild und Text', - 'call_to_action' => 'Handlungsaufruf', - 'cards' => 'Karten', - 'faq' => 'FAQ', - ]; - } - - /** - * @param list> $blocks - * @return list> - */ - public function normalize(array $blocks): array - { - $normalized = []; - - foreach (array_values($blocks) as $index => $block) { - if (! is_array($block)) { - throw ValidationException::withMessages([ - "blocks.$index" => 'Ein Baustein ist unvollständig.', - ]); - } - - $type = $block['type'] ?? null; - - if (! is_string($type) || ! array_key_exists($type, $this->labels())) { - throw ValidationException::withMessages([ - "blocks.$index.type" => 'Dieser Bausteintyp ist nicht freigegeben.', - ]); - } - - $normalized[] = $this->normalizeOne($type, $block, $index); - } - - return $normalized; - } - - /** - * @param array $block - * @return array - */ - private function normalizeOne(string $type, array $block, int $index): array - { - $rules = match ($type) { - 'heading' => [ - 'heading' => ['required', 'string', 'max:200'], - 'intro' => ['nullable', 'string', 'max:1000'], - ], - 'prose' => [ - 'body' => ['required', 'string', 'max:20000'], - ], - 'image_text' => [ - 'image' => ['nullable', 'string', 'max:255'], - 'alt' => ['required', 'string', 'max:300'], - 'body' => ['required', 'string', 'max:5000'], - ], - 'call_to_action' => [ - 'heading' => ['required', 'string', 'max:200'], - 'text' => ['nullable', 'string', 'max:1000'], - 'label' => ['required', 'string', 'max:80'], - 'url' => ['required', 'string', 'max:500'], - ], - 'cards' => [ - 'items' => ['required', 'array', 'min:1', 'max:6'], - 'items.*.title' => ['required', 'string', 'max:120'], - 'items.*.text' => ['nullable', 'string', 'max:500'], - 'items.*.url' => ['nullable', 'string', 'max:500'], - ], - 'faq' => [ - 'items' => ['required', 'array', 'min:1', 'max:20'], - 'items.*.question' => ['required', 'string', 'max:300'], - 'items.*.answer' => ['required', 'string', 'max:2000'], - ], - default => [], - }; - - $validator = Validator::make($block, $rules); - - if ($validator->fails()) { - $messages = []; - - foreach ($validator->errors()->messages() as $key => $errors) { - $messages["blocks.$index.$key"] = $errors; - } - - throw ValidationException::withMessages($messages); - } - - $clean = ['type' => $type]; - - foreach (array_keys($rules) as $key) { - if (str_contains($key, '.*')) { - continue; - } - - $clean[$key] = $block[$key] ?? null; - } - - if ($type === 'image_text') { - $clean['image'] = $this->imagePath($clean['image'] ?? null, $index); - } - - if (in_array($type, ['call_to_action', 'cards'], true)) { - $clean = $this->assertSafeUrls($clean, $index); - } - - return $clean; - } - - private function imagePath(mixed $image, int $index): ?string - { - if (is_array($image)) { - $image = $image[0] ?? null; - } - - if ($image === null || $image === '') { - return null; - } - - if (! is_string($image) || str_contains($image, '..') || ! str_starts_with($image, 'cms/')) { - throw ValidationException::withMessages([ - "blocks.$index.image" => 'Das Bild liegt nicht im öffentlichen Medienbereich.', - ]); - } - - return $image; - } - - /** - * @param array $block - * @return array - */ - private function assertSafeUrls(array $block, int $index): array - { - if (array_key_exists('url', $block)) { - $block['url'] = $this->safeUrl($block['url'], "blocks.$index.url"); - } - - if (isset($block['items']) && is_array($block['items'])) { - foreach ($block['items'] as $itemIndex => $item) { - if (is_array($item) && filled($item['url'] ?? null)) { - $block['items'][$itemIndex]['url'] = $this->safeUrl($item['url'], "blocks.$index.items.$itemIndex.url"); - } - } - } - - return $block; - } - - private function safeUrl(mixed $url, string $key): string - { - if (! is_string($url)) { - throw ValidationException::withMessages([$key => 'Die Adresse ist ungültig.']); - } - - $isRelative = str_starts_with($url, '/') && ! str_starts_with($url, '//'); - $isAbsolute = preg_match('#^https?://#i', $url) === 1; - - if (! $isRelative && ! $isAbsolute) { - throw ValidationException::withMessages([$key => 'Erlaubt sind Seitenpfade oder http(s)-Adressen.']); - } - - return $url; - } -} diff --git a/app/Domain/Cms/Catalog/CatalogEntry.php b/app/Domain/Cms/Catalog/CatalogEntry.php new file mode 100644 index 0000000..a4051db --- /dev/null +++ b/app/Domain/Cms/Catalog/CatalogEntry.php @@ -0,0 +1,18 @@ + + */ + public function publicPrograms(): Collection + { + $kind = EditorialContentKind::query()->where('slug', 'programm')->first(); + + if ($kind === null) { + return collect(); + } + + return Composition::query() + ->where('editorial_content_kind_id', $kind->id) + ->orderBy('designation') + ->get() + ->filter(fn (Composition $composition): bool => $this->shownVersion($composition) !== null) + ->values(); + } + + /** + * Gezeigte Fassung einer öffentlich gezeigten Komposition, sonst null. + */ + public function shownVersion(Composition $composition): ?CompositionVersion + { + if (! in_array($composition->editorialContentKind?->slug, self::PUBLIC_KINDS, true)) { + return null; + } + + return $this->releases->highestReleasedVersion($composition); + } + + public function isPublic(Composition $composition): bool + { + return $this->shownVersion($composition) !== null; + } + + /** + * Wählbar sind Programme und Module mit zur Anzeige freigegebener Fassung, die nicht archiviert sind. + */ + public function isSelectable(Composition $composition): bool + { + return $composition->archived_at === null + && in_array($composition->editorialContentKind?->slug, self::SELECTABLE_KINDS, true) + && $this->releases->highestReleasedVersion($composition) !== null; + } + + /** + * Suchtreffer für die Auswahl im Editor: Kennung => Bezeichnung mit Sichtbarkeitshinweis. + * + * @return array + */ + public function search(?string $term, int $limit = 25): array + { + $term = trim((string) $term); + + $candidates = Composition::query() + ->with('editorialContentKind') + ->whereNull('archived_at') + ->whereHas('editorialContentKind', fn ($query) => $query->whereIn('slug', self::SELECTABLE_KINDS)) + ->when($term !== '', function ($query) use ($term): void { + $like = '%'.mb_strtolower($term).'%'; + $query->where(fn ($inner) => $inner + ->whereRaw('LOWER(designation) LIKE ?', [$like]) + ->orWhereRaw('LOWER(COALESCE(display_title, \'\')) LIKE ?', [$like])); + }) + ->orderBy('designation') + ->limit($limit * 3) + ->get(); + + $options = []; + + foreach ($candidates as $composition) { + if (! $this->isSelectable($composition)) { + continue; + } + + $options[$composition->id] = $this->optionLabel($composition); + + if (count($options) >= $limit) { + break; + } + } + + return $options; + } + + public function labelFor(mixed $id): ?string + { + $composition = is_numeric($id) ? Composition::query()->with('editorialContentKind')->find((int) $id) : null; + + return $composition === null ? null : $this->optionLabel($composition); + } + + /** + * Löst Verweise in Anzeigeeinträge auf. Öffentlich entfallen nicht öffentliche Objekte stillschweigend. + * + * @param list $refs + * @return list + */ + public function entries(array $refs, bool $includeNonPublic): array + { + $ids = []; + foreach ($refs as $ref) { + if (is_array($ref) && ($ref['type'] ?? null) === 'composition' && is_numeric($ref['id'] ?? null)) { + $ids[] = (int) $ref['id']; + } + } + + if ($ids === []) { + return []; + } + + $compositions = Composition::query()->with('editorialContentKind')->whereIn('id', $ids)->get()->keyBy('id'); + $entries = []; + + foreach (array_unique($ids) as $id) { + $composition = $compositions->get($id); + + if ($composition === null || ! $this->isSelectable($composition)) { + continue; + } + + $public = $this->isPublic($composition); + + if (! $public && ! $includeNonPublic) { + continue; + } + + $entries[] = new CatalogEntry( + id: $composition->id, + title: $this->title($composition), + summary: filled($composition->summary) ? (string) $composition->summary : null, + kindLabel: (string) ($composition->editorialContentKind?->label ?? ''), + url: $public ? route('public.program', $composition) : null, + public: $public, + ); + } + + return $entries; + } + + private function title(Composition $composition): string + { + return (string) ($composition->display_title ?: $composition->designation); + } + + private function optionLabel(Composition $composition): string + { + $visibility = $this->isPublic($composition) ? 'öffentlich sichtbar' : 'nur Redaktionsvorschau'; + + return $this->title($composition).' · '.($composition->editorialContentKind?->label ?? '').' · '.$visibility; + } +} diff --git a/app/Domain/Cms/NavigationItem.php b/app/Domain/Cms/NavigationItem.php index 633e4b8..1b42fae 100644 --- a/app/Domain/Cms/NavigationItem.php +++ b/app/Domain/Cms/NavigationItem.php @@ -2,35 +2,58 @@ namespace App\Domain\Cms; +use App\Domain\Cms\Widgets\Support\SafeUrl; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class NavigationItem extends Model { + public const PLACEMENTS = [ + 'header' => 'Kopfzeile', + 'footer' => 'Fußzeile', + ]; + protected $fillable = [ 'label', 'page_id', 'url', 'placement', 'sort_order', + 'is_visible', ]; + protected function casts(): array + { + return [ + 'is_visible' => 'boolean', + ]; + } + public function page(): BelongsTo { return $this->belongsTo(Page::class); } + /** + * @param Builder $query + */ + public function scopeVisible(Builder $query): void + { + $query->where('is_visible', true); + } + public function href(): ?string { if ($this->page !== null) { return $this->page->path === '/' ? url('/') : url($this->page->path); } - if ($this->url === null || $this->url === '') { + if ($this->url === null || $this->url === '' || ! SafeUrl::isSafe($this->url)) { return null; } - if (str_starts_with($this->url, '/') && ! str_starts_with($this->url, '//')) { + if (str_starts_with($this->url, '/')) { return url($this->url); } diff --git a/app/Domain/Cms/Page.php b/app/Domain/Cms/Page.php index 93b8e3e..f902f44 100644 --- a/app/Domain/Cms/Page.php +++ b/app/Domain/Cms/Page.php @@ -48,17 +48,12 @@ public function publicUrl(): string public function publicTitle(): string { $revision = $this->publishedRevision; - $heading = collect($revision?->blocks ?? [])->firstWhere('type', 'heading'); if (is_string($revision?->seo_title) && $revision->seo_title !== '') { return $revision->seo_title; } - if (is_array($heading) && is_string($heading['heading'] ?? null) && $heading['heading'] !== '') { - return $heading['heading']; - } - - return $this->path; + return $revision?->contentTitle() ?? $this->path; } public function pillars(): BelongsToMany diff --git a/app/Domain/Cms/PageRevision.php b/app/Domain/Cms/PageRevision.php index 98b5d55..c51778b 100644 --- a/app/Domain/Cms/PageRevision.php +++ b/app/Domain/Cms/PageRevision.php @@ -2,6 +2,7 @@ namespace App\Domain\Cms; +use App\Domain\Cms\Widgets\WidgetRegistry; use App\Models\User; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; @@ -35,4 +36,22 @@ public function author(): BelongsTo { return $this->belongsTo(User::class, 'created_by'); } + + /** + * Bausteine als aktuelle Widget-Hüllen. Die gespeicherten Daten bleiben unverändert. + * + * @return list> + */ + public function widgets(): array + { + return app(WidgetRegistry::class)->read($this->blocks); + } + + /** + * Titel aus dem ersten Überschriften- oder Einstiegs-Widget. + */ + public function contentTitle(): ?string + { + return app(WidgetRegistry::class)->pageTitle($this->blocks); + } } diff --git a/app/Domain/Cms/PageService.php b/app/Domain/Cms/PageService.php index 0b0c3cb..9715a8a 100644 --- a/app/Domain/Cms/PageService.php +++ b/app/Domain/Cms/PageService.php @@ -2,36 +2,23 @@ namespace App\Domain\Cms; -use App\Domain\Cms\Blocks\BlockRegistry; +use App\Domain\Cms\Widgets\WidgetRegistry; use App\Jobs\PublishPublicMedia; use App\Models\User; use Illuminate\Validation\ValidationException; class PageService { - public function __construct(private readonly BlockRegistry $blocks) {} + public function __construct(private readonly WidgetRegistry $widgets) {} /** - * @param list> $blocks + * Speichert einen Entwurf als neue Revision. Veröffentlicht nichts. + * + * @param array $blocks Bausteine im Altformat oder als Widget-Hülle */ public function saveRevision(Page $page, array $blocks, ?string $seoTitle, ?string $seoDescription, ?User $author): PageRevision { - $normalized = $this->blocks->normalize($blocks); - - $revision = $page->revisions()->create([ - 'blocks' => $normalized, - 'seo_title' => $seoTitle !== null && $seoTitle !== '' ? $seoTitle : null, - 'seo_description' => $seoDescription !== null && $seoDescription !== '' ? $seoDescription : null, - 'created_by' => $author?->id, - ]); - - foreach ($normalized as $block) { - if (($block['type'] ?? null) === 'image_text' && filled($block['image'] ?? null)) { - PublishPublicMedia::dispatch($block['image']); - } - } - - return $revision; + return $this->storeRevision($page, $this->widgets->normalize($blocks), $seoTitle, $seoDescription, $author); } public function publish(Page $page, PageRevision $revision): void @@ -46,6 +33,10 @@ public function publish(Page $page, PageRevision $revision): void $page->save(); } + /** + * Legt den Stand einer früheren Revision unverändert als neue Revision an. Die gespeicherten Bausteine + * werden nicht umgeschrieben; ältere Formate werden erst beim Lesen angehoben. + */ public function restore(Page $page, PageRevision $source, ?User $author): PageRevision { if ($source->page_id !== $page->id) { @@ -54,15 +45,36 @@ public function restore(Page $page, PageRevision $source, ?User $author): PageRe ]); } - return $this->saveRevision( + return $this->storeRevision( $page, - $source->blocks, + $source->blocks ?? [], $source->seo_title, $source->seo_description, $author, ); } + /** + * Normalisiert den Pfad und prüft, dass keine andere Seite ihn verwendet. + */ + public function availablePath(string $path, ?Page $except = null): string + { + $path = $this->normalizePath($path); + + $taken = Page::query() + ->where('path', $path) + ->when($except !== null, fn ($query) => $query->whereKeyNot($except->getKey())) + ->exists(); + + if ($taken) { + throw ValidationException::withMessages([ + 'path' => 'Diesen Pfad verwendet bereits eine andere Seite.', + ]); + } + + return $path; + } + public function normalizePath(string $path): string { $path = '/'.trim($path, '/'); @@ -81,4 +93,23 @@ public function normalizePath(string $path): string return $path; } + + /** + * @param array $blocks + */ + private function storeRevision(Page $page, array $blocks, ?string $seoTitle, ?string $seoDescription, ?User $author): PageRevision + { + $revision = $page->revisions()->create([ + 'blocks' => array_values($blocks), + 'seo_title' => $seoTitle !== null && $seoTitle !== '' ? $seoTitle : null, + 'seo_description' => $seoDescription !== null && $seoDescription !== '' ? $seoDescription : null, + 'created_by' => $author?->id, + ]); + + foreach ($this->widgets->mediaPaths($revision->blocks) as $path) { + PublishPublicMedia::dispatch($path); + } + + return $revision; + } } diff --git a/app/Domain/Cms/PageTemplates.php b/app/Domain/Cms/PageTemplates.php new file mode 100644 index 0000000..57bfe98 --- /dev/null +++ b/app/Domain/Cms/PageTemplates.php @@ -0,0 +1,28 @@ + + */ + public function all(): array + { + return config('cms.templates', [self::DEFAULT => 'site.templates.standard']); + } + + public function viewFor(Page $page): string + { + $templates = $this->all(); + + return $templates[self::DEFAULT]; + } +} diff --git a/app/Domain/Cms/Widgets/RenderContext.php b/app/Domain/Cms/Widgets/RenderContext.php new file mode 100644 index 0000000..f9412c8 --- /dev/null +++ b/app/Domain/Cms/Widgets/RenderContext.php @@ -0,0 +1,22 @@ + + */ + public static function fields(string $label = 'Bild'): array + { + return [ + Select::make('image') + ->label($label.': vorhandenes Bild') + ->options(fn (): array => PublicMedia::imageOptions()) + ->searchable() + ->placeholder('Kein Bild') + ->helperText('Auswahl aus den Bildern, die bereits für die Website hochgeladen wurden.'), + FileUpload::make('_upload') + ->label($label.': neu hochladen') + ->disk('cms_incoming') + ->directory('cms') + ->image() + ->maxSize(8192) + ->acceptedFileTypes(['image/jpeg', 'image/png', 'image/webp']) + ->getUploadedFileNameForStorageUsing(fn (TemporaryUploadedFile $file): string => Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)).'-'.Str::lower(Str::random(6)).'.'.$file->guessExtension()) + ->helperText('Ein neues Bild ersetzt die Auswahl oben. Es wird beim Speichern im öffentlichen Bereich der Website abgelegt.'), + ]; + } + + /** + * @return array + */ + public static function rules(): array + { + return [ + 'image' => ['nullable', 'string', 'max:255'], + '_upload' => ['nullable'], + ]; + } + + /** + * Übernimmt einen neuen Upload als Bild und prüft, dass das Bild im öffentlichen Bereich liegt. + * + * @param array $refs + * @return array + */ + public static function clean(array $refs, WidgetErrors $errors, string $key = 'image', ?string $errorKey = null): array + { + $upload = PublicMedia::fromUploadState($refs['_upload'] ?? null); + $image = $upload ?? PublicMedia::fromUploadState($refs[$key] ?? null); + + if ($image !== null && ! PublicMedia::isPublicPath($image)) { + $errors->add($errorKey ?? "refs.$key", 'Das Bild liegt nicht im öffentlichen Medienbereich.'); + } + + $refs[$key] = $image; + unset($refs['_upload']); + + return $refs; + } +} diff --git a/app/Domain/Cms/Widgets/Support/PublicMedia.php b/app/Domain/Cms/Widgets/Support/PublicMedia.php new file mode 100644 index 0000000..4984750 --- /dev/null +++ b/app/Domain/Cms/Widgets/Support/PublicMedia.php @@ -0,0 +1,100 @@ + $path]); + } + + /** + * Bereits vorhandene Bilder im öffentlichen Bereich (veröffentlicht oder zur Veröffentlichung vorgemerkt). + * + * @return array + */ + public static function imageOptions(): array + { + $options = []; + + foreach (['media_public', 'cms_incoming'] as $disk) { + try { + $files = Storage::disk($disk)->allFiles(rtrim(self::PREFIX, '/')); + } catch (Throwable) { + $files = []; + } + + foreach ($files as $file) { + $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION)); + + if (self::isPublicPath($file) && in_array($extension, self::IMAGE_EXTENSIONS, true)) { + $options[$file] = substr($file, strlen(self::PREFIX)); + } + } + } + + ksort($options); + + return $options; + } + + /** + * Pfad aus dem Zustand eines Upload-Felds (Zeichenkette oder Liste). + */ + public static function fromUploadState(mixed $state): ?string + { + if (is_array($state)) { + $state = array_values($state)[0] ?? null; + } + + return is_string($state) && $state !== '' ? $state : null; + } + + /** + * Bildadresse für Darstellung und Blockvorschau. In der Vorschau kann ein noch nicht gespeicherter Upload vorliegen. + * + * @param array $refs + */ + public static function imageUrl(array $refs, string $key = 'image'): ?string + { + $upload = $refs['_upload'] ?? null; + $upload = is_array($upload) ? (array_values($upload)[0] ?? null) : $upload; + + if ($upload instanceof TemporaryUploadedFile) { + try { + return $upload->temporaryUrl(); + } catch (Throwable) { + return null; + } + } + + if (self::isPublicPath($upload)) { + return self::url($upload); + } + + $path = $refs[$key] ?? null; + + return self::isPublicPath($path) ? self::url($path) : null; + } +} diff --git a/app/Domain/Cms/Widgets/Support/RichText.php b/app/Domain/Cms/Widgets/Support/RichText.php new file mode 100644 index 0000000..152ebae --- /dev/null +++ b/app/Domain/Cms/Widgets/Support/RichText.php @@ -0,0 +1,79 @@ +sanitize($html)); + } + + /** + * Übernimmt Klartext aus dem Altbestand: Absätze an Leerzeilen, Zeichen maskiert. + */ + public static function fromPlainText(?string $text): string + { + $text = trim((string) $text); + + if ($text === '') { + return ''; + } + + $paragraphs = preg_split("/\n\s*\n/", $text) ?: []; + + return implode('', array_map( + fn (string $paragraph): string => '

'.e(trim($paragraph)).'

', + $paragraphs, + )); + } + + public static function isBlank(?string $html): bool + { + return trim(html_entity_decode(strip_tags((string) $html), ENT_QUOTES | ENT_HTML5, 'UTF-8')) === ''; + } + + public static function excerpt(?string $html, int $length = 80): string + { + $text = trim(preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags(str_replace('<', ' <', (string) $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8')) ?? ''); + + return mb_strlen($text) > $length ? rtrim(mb_substr($text, 0, $length - 1)).'…' : $text; + } + + private static function sanitizer(): HtmlSanitizer + { + return self::$sanitizer ??= new HtmlSanitizer( + (new HtmlSanitizerConfig) + ->allowElement('p') + ->allowElement('br') + ->allowElement('strong') + ->allowElement('b') + ->allowElement('em') + ->allowElement('i') + ->allowElement('ul') + ->allowElement('ol') + ->allowElement('li') + ->allowElement('a', ['href']) + ->allowLinkSchemes(['http', 'https', 'mailto']) + ->allowRelativeLinks() + ->forceAttribute('a', 'rel', 'noopener') + ->withMaxInputLength(40000), + ); + } +} diff --git a/app/Domain/Cms/Widgets/Support/SafeUrl.php b/app/Domain/Cms/Widgets/Support/SafeUrl.php new file mode 100644 index 0000000..a385792 --- /dev/null +++ b/app/Domain/Cms/Widgets/Support/SafeUrl.php @@ -0,0 +1,44 @@ + ['required', 'string', 'max:200'], + 'text' => ['nullable', 'string', 'max:1000'], + 'label' => ['required', 'string', 'max:80'], + 'url' => ['required', 'string', 'max:500'], + ]; + } + + public function dataFields(): array + { + return [ + TextInput::make('heading')->label('Überschrift')->required()->maxLength(200), + Textarea::make('text')->label('Text')->rows(3)->maxLength(1000), + TextInput::make('label')->label('Beschriftung der Schaltfläche')->required()->maxLength(80), + TextInput::make('url') + ->label('Linkziel') + ->required() + ->maxLength(500) + ->rule(SafeUrl::rule()) + ->helperText('Seitenpfad wie /angebote oder eine vollständige http(s)-Adresse.'), + ]; + } + + public function clean(array $data, array $refs, WidgetErrors $errors): array + { + if (! SafeUrl::isSafe($data['url'] ?? null)) { + $errors->add('data.url', SafeUrl::message()); + } + + return [$data, $refs]; + } + + public function summary(array $widget): string + { + return trim(($widget['data']['heading'] ?? '').' → '.($widget['data']['label'] ?? '')); + } +} diff --git a/app/Domain/Cms/Widgets/Types/CardsWidget.php b/app/Domain/Cms/Widgets/Types/CardsWidget.php new file mode 100644 index 0000000..5eff5a7 --- /dev/null +++ b/app/Domain/Cms/Widgets/Types/CardsWidget.php @@ -0,0 +1,155 @@ + 'Raster', + 'compact' => 'Kompakte Liste', + ]; + } + + public function dataRules(): array + { + return [ + 'items' => ['required', 'array', 'min:1', 'max:12'], + 'items.*.title' => ['required', 'string', 'max:120'], + 'items.*.text' => ['nullable', 'string', 'max:500'], + 'items.*.url' => ['nullable', 'string', 'max:500'], + 'items.*.image' => ['nullable', 'string', 'max:255'], + 'items.*._upload' => ['nullable'], + ]; + } + + public function dataFields(): array + { + [$image, $upload] = ImageRefFields::fields('Bild (optional)'); + + return [ + Repeater::make('items') + ->label('Karten') + ->schema([ + TextInput::make('title')->label('Titel')->required()->maxLength(120), + Textarea::make('text')->label('Beschreibung')->rows(2)->maxLength(500), + TextInput::make('url') + ->label('Linkziel') + ->maxLength(500) + ->rule(SafeUrl::rule()) + ->helperText('Seitenpfad wie /praevention oder eine http(s)-Adresse. Leer lassen für eine Karte ohne Link.'), + $image, + $upload, + ]) + ->minItems(1) + ->maxItems(12) + ->reorderableWithButtons() + ->collapsible() + ->cloneable() + ->itemLabel(fn (array $state): ?string => $state['title'] ?? null) + ->addActionLabel('Karte hinzufügen'), + ]; + } + + public function clean(array $data, array $refs, WidgetErrors $errors): array + { + foreach ($data['items'] as $index => $item) { + if (filled($item['url'] ?? null) && ! SafeUrl::isSafe($item['url'])) { + $errors->add("data.items.$index.url", SafeUrl::message()); + } + + $itemRefs = ImageRefFields::clean(['image' => $item['image'] ?? null, '_upload' => $item['_upload'] ?? null], $errors, errorKey: "data.items.$index.image"); + + $data['items'][$index] = [ + 'title' => $item['title'], + 'text' => filled($item['text'] ?? null) ? $item['text'] : null, + 'url' => filled($item['url'] ?? null) ? $item['url'] : null, + 'image' => $itemRefs['image'], + ]; + } + + return [$data, $refs]; + } + + public function resolve(array $widget, RenderContext $context): array + { + $items = []; + + foreach ($widget['data']['items'] ?? [] as $item) { + if (! is_array($item) || ! filled($item['title'] ?? null)) { + continue; + } + + $items[] = [ + 'title' => $item['title'], + 'text' => $item['text'] ?? null, + 'url' => SafeUrl::isSafe($item['url'] ?? null) ? $item['url'] : null, + 'imageUrl' => PublicMedia::imageUrl($item), + ]; + } + + return ['items' => $items]; + } + + public function mediaPaths(array $widget): array + { + $paths = []; + + foreach ($widget['data']['items'] ?? [] as $item) { + if (is_array($item) && PublicMedia::isPublicPath($item['image'] ?? null)) { + $paths[] = $item['image']; + } + } + + return $paths; + } + + public function summary(array $widget): string + { + $titles = array_filter(array_map(fn ($item) => is_array($item) ? ($item['title'] ?? null) : null, $widget['data']['items'] ?? [])); + + return count($titles).' Karten: '.implode(', ', $titles); + } +} diff --git a/app/Domain/Cms/Widgets/Types/CatalogCardsWidget.php b/app/Domain/Cms/Widgets/Types/CatalogCardsWidget.php new file mode 100644 index 0000000..8c0b63e --- /dev/null +++ b/app/Domain/Cms/Widgets/Types/CatalogCardsWidget.php @@ -0,0 +1,157 @@ + 'Karten mit Kurzbeschreibung', + 'compact' => 'Kompakte Liste', + ]; + } + + public function dataRules(): array + { + return [ + 'heading' => ['nullable', 'string', 'max:160'], + 'intro' => ['nullable', 'string', 'max:400'], + ]; + } + + public function refRules(): array + { + return [ + 'items' => ['required', 'array', 'min:1', 'max:12'], + 'items.*.type' => ['required', 'string', 'in:composition'], + 'items.*.id' => ['required', 'integer'], + ]; + } + + public function dataFields(): array + { + return [ + TextInput::make('heading')->label('Abschnittsüberschrift (optional)')->maxLength(160), + Textarea::make('intro')->label('Einleitung (optional)')->rows(2)->maxLength(400), + ]; + } + + public function refFields(): array + { + return [ + Repeater::make('items') + ->label('Programme und Module') + ->helperText('Nur zur Anzeige freigegebene Programme und Module sind wählbar. Öffentlich erscheinen derzeit nur Programme mit öffentlicher Programmseite; Module nur in der Redaktionsvorschau.') + ->schema([ + Hidden::make('type')->default('composition'), + Select::make('id') + ->label('Programm oder Modul') + ->required() + ->live() + ->searchable() + ->getSearchResultsUsing(fn (?string $search): array => app(PublicCatalogReader::class)->search($search)) + ->getOptionLabelUsing(fn (mixed $value): ?string => app(PublicCatalogReader::class)->labelFor($value)) + ->options(fn (): array => app(PublicCatalogReader::class)->search(null, 10)), + ]) + ->minItems(1) + ->maxItems(12) + ->reorderableWithButtons() + ->itemLabel(fn (array $state): ?string => filled($state['id'] ?? null) ? app(PublicCatalogReader::class)->labelFor($state['id']) : null) + ->addActionLabel('Programm oder Modul hinzufügen'), + ]; + } + + public function clean(array $data, array $refs, WidgetErrors $errors): array + { + $reader = app(PublicCatalogReader::class); + $items = []; + $seen = []; + + foreach ($refs['items'] as $index => $item) { + $id = (int) $item['id']; + $composition = Composition::query()->with('editorialContentKind')->find($id); + + if ($composition === null || ! $reader->isSelectable($composition)) { + $errors->add("refs.items.$index.id", 'Dieses Objekt ist kein zur Anzeige freigegebenes Programm oder Modul.'); + + continue; + } + + if (isset($seen[$id])) { + continue; + } + + $seen[$id] = true; + $items[] = ['type' => 'composition', 'id' => $id]; + } + + $refs['items'] = $items; + + foreach (['heading', 'intro'] as $key) { + $data[$key] = filled($data[$key] ?? null) ? trim($data[$key]) : null; + } + + return [$data, $refs]; + } + + public function resolve(array $widget, RenderContext $context): array + { + $refs = is_array($widget['refs']['items'] ?? null) ? array_values($widget['refs']['items']) : []; + + return [ + 'entries' => app(PublicCatalogReader::class)->entries($refs, includeNonPublic: $context->preview), + ]; + } + + public function summary(array $widget): string + { + $count = count($widget['refs']['items'] ?? []); + $heading = $widget['data']['heading'] ?? null; + + return trim(($heading ? $heading.' · ' : '').($count === 1 ? '1 Verweis' : $count.' Verweise')); + } +} diff --git a/app/Domain/Cms/Widgets/Types/FaqWidget.php b/app/Domain/Cms/Widgets/Types/FaqWidget.php new file mode 100644 index 0000000..37a6258 --- /dev/null +++ b/app/Domain/Cms/Widgets/Types/FaqWidget.php @@ -0,0 +1,70 @@ + ['required', 'array', 'min:1', 'max:20'], + 'items.*.question' => ['required', 'string', 'max:300'], + 'items.*.answer' => ['required', 'string', 'max:2000'], + ]; + } + + public function dataFields(): array + { + return [ + Repeater::make('items') + ->label('Fragen') + ->schema([ + TextInput::make('question')->label('Frage')->required()->maxLength(300), + Textarea::make('answer')->label('Antwort')->rows(3)->required()->maxLength(2000), + ]) + ->minItems(1) + ->maxItems(20) + ->reorderableWithButtons() + ->collapsible() + ->itemLabel(fn (array $state): ?string => $state['question'] ?? null) + ->addActionLabel('Frage hinzufügen'), + ]; + } + + public function summary(array $widget): string + { + $count = count($widget['data']['items'] ?? []); + + return $count === 1 ? '1 Frage' : $count.' Fragen'; + } +} diff --git a/app/Domain/Cms/Widgets/Types/HeadingWidget.php b/app/Domain/Cms/Widgets/Types/HeadingWidget.php new file mode 100644 index 0000000..7becae8 --- /dev/null +++ b/app/Domain/Cms/Widgets/Types/HeadingWidget.php @@ -0,0 +1,61 @@ + ['required', 'string', 'max:200'], + 'intro' => ['nullable', 'string', 'max:1000'], + ]; + } + + public function dataFields(): array + { + return [ + TextInput::make('heading')->label('Überschrift')->required()->maxLength(200), + Textarea::make('intro')->label('Einleitung')->rows(3)->maxLength(1000), + ]; + } + + public function summary(array $widget): string + { + return (string) ($widget['data']['heading'] ?? ''); + } + + public function pageTitle(array $widget): ?string + { + return $widget['data']['heading'] ?? null; + } +} diff --git a/app/Domain/Cms/Widgets/Types/HeroWidget.php b/app/Domain/Cms/Widgets/Types/HeroWidget.php new file mode 100644 index 0000000..1740703 --- /dev/null +++ b/app/Domain/Cms/Widgets/Types/HeroWidget.php @@ -0,0 +1,149 @@ + 'Standard (Bild neben dem Text)', + 'highlight' => 'Hervorgehoben (Markenfläche)', + ]; + } + + public function dataRules(): array + { + return [ + 'heading' => ['required', 'string', 'max:200'], + 'text' => ['nullable', 'string', 'max:600'], + 'cta_label' => ['nullable', 'string', 'max:80', 'required_with:data.cta_url'], + 'cta_url' => ['nullable', 'string', 'max:500', 'required_with:data.cta_label'], + 'alt' => ['nullable', 'string', 'max:300'], + ]; + } + + public function refRules(): array + { + return ImageRefFields::rules(); + } + + public function dataFields(): array + { + return [ + TextInput::make('heading')->label('Überschrift')->required()->maxLength(200), + Textarea::make('text')->label('Beschreibung')->rows(3)->maxLength(600), + Grid::make(2)->schema([ + TextInput::make('cta_label')->label('Schaltfläche: Beschriftung (optional)')->maxLength(80), + TextInput::make('cta_url') + ->label('Schaltfläche: Linkziel') + ->maxLength(500) + ->rule(SafeUrl::rule()) + ->requiredWith('cta_label'), + ]), + TextInput::make('alt') + ->label('Alternativtext des Bildes') + ->maxLength(300) + ->helperText('Pflicht, sobald ein Bild gewählt ist.'), + ]; + } + + public function refFields(): array + { + return ImageRefFields::fields(); + } + + public function editorSchema(): array + { + [$heading, $text, $cta, $alt] = $this->dataFields(); + + return [ + Group::make([$heading, $text, $cta])->statePath('data'), + Group::make($this->refFields())->statePath('refs'), + Group::make([$alt])->statePath('data'), + ]; + } + + public function clean(array $data, array $refs, WidgetErrors $errors): array + { + $refs = ImageRefFields::clean($refs, $errors); + + foreach (['text', 'cta_label', 'cta_url', 'alt'] as $key) { + $data[$key] = filled($data[$key] ?? null) ? trim($data[$key]) : null; + } + + if ($data['cta_url'] !== null && ! SafeUrl::isSafe($data['cta_url'])) { + $errors->add('data.cta_url', SafeUrl::message()); + } + + if ($refs['image'] !== null && $data['alt'] === null) { + $errors->add('data.alt', 'Bitte einen Alternativtext für das Bild angeben.'); + } + + return [$data, $refs]; + } + + public function resolve(array $widget, RenderContext $context): array + { + $data = $widget['data']; + $hasAction = filled($data['cta_label'] ?? null) && SafeUrl::isSafe($data['cta_url'] ?? null); + + return [ + 'imageUrl' => PublicMedia::imageUrl($widget['refs']), + 'action' => $hasAction ? ['label' => $data['cta_label'], 'url' => $data['cta_url']] : null, + ]; + } + + public function mediaPaths(array $widget): array + { + $image = $widget['refs']['image'] ?? null; + + return PublicMedia::isPublicPath($image) ? [$image] : []; + } + + public function summary(array $widget): string + { + return (string) ($widget['data']['heading'] ?? ''); + } + + public function pageTitle(array $widget): ?string + { + return $widget['data']['heading'] ?? null; + } +} diff --git a/app/Domain/Cms/Widgets/Types/ImageTextWidget.php b/app/Domain/Cms/Widgets/Types/ImageTextWidget.php new file mode 100644 index 0000000..b5d89ba --- /dev/null +++ b/app/Domain/Cms/Widgets/Types/ImageTextWidget.php @@ -0,0 +1,165 @@ + 'Bild links', + 'image_right' => 'Bild rechts', + ]; + } + + public function upgrade(array $widget, int $from): array + { + if ($from !== 1) { + return parent::upgrade($widget, $from); + } + + $data = $widget['data']; + + $widget['data'] = [ + 'title' => null, + 'body' => RichText::fromPlainText(is_string($data['body'] ?? null) ? $data['body'] : ''), + 'alt' => $data['alt'] ?? null, + ]; + $widget['refs'] = [ + 'image' => PublicMedia::fromUploadState($data['image'] ?? null), + ]; + + return $widget; + } + + public function dataRules(): array + { + return [ + 'title' => ['nullable', 'string', 'max:160'], + 'body' => ['required', 'string', 'max:40000'], + 'alt' => ['nullable', 'string', 'max:300'], + ]; + } + + public function refRules(): array + { + return ImageRefFields::rules(); + } + + public function dataFields(): array + { + return [ + TextInput::make('title')->label('Titel (optional)')->maxLength(160), + RichEditor::make('body') + ->label('Text') + ->required() + ->toolbarButtons(RichText::TOOLBAR), + TextInput::make('alt') + ->label('Alternativtext des Bildes') + ->maxLength(300) + ->helperText('Beschreibt, was auf dem Bild zu sehen ist. Pflicht, sobald ein Bild gewählt ist.'), + ]; + } + + public function refFields(): array + { + return ImageRefFields::fields(); + } + + public function editorSchema(): array + { + [$title, $body, $alt] = $this->dataFields(); + + return [ + Group::make([$title, $body])->statePath('data'), + Group::make($this->refFields())->statePath('refs'), + Group::make([$alt])->statePath('data'), + ]; + } + + public function clean(array $data, array $refs, WidgetErrors $errors): array + { + $refs = ImageRefFields::clean($refs, $errors); + $data['body'] = RichText::sanitize($data['body'] ?? ''); + $data['title'] = filled($data['title'] ?? null) ? trim($data['title']) : null; + $data['alt'] = filled($data['alt'] ?? null) ? trim($data['alt']) : null; + + if (RichText::isBlank($data['body'])) { + $errors->add('data.body', 'Bitte einen Text eingeben.'); + } + + if ($refs['image'] !== null && $data['alt'] === null) { + $errors->add('data.alt', 'Bitte einen Alternativtext für das Bild angeben.'); + } + + return [$data, $refs]; + } + + public function resolve(array $widget, RenderContext $context): array + { + return [ + 'imageUrl' => PublicMedia::imageUrl($widget['refs']), + 'body' => RichText::sanitize(is_string($widget['data']['body'] ?? null) ? $widget['data']['body'] : ''), + ]; + } + + public function mediaPaths(array $widget): array + { + $image = $widget['refs']['image'] ?? null; + + return PublicMedia::isPublicPath($image) ? [$image] : []; + } + + public function summary(array $widget): string + { + $title = $widget['data']['title'] ?? null; + + return filled($title) ? (string) $title : RichText::excerpt($widget['data']['body'] ?? ''); + } +} diff --git a/app/Domain/Cms/Widgets/Types/ProseWidget.php b/app/Domain/Cms/Widgets/Types/ProseWidget.php new file mode 100644 index 0000000..dcb99b8 --- /dev/null +++ b/app/Domain/Cms/Widgets/Types/ProseWidget.php @@ -0,0 +1,54 @@ + ['required', 'string', 'max:20000'], + ]; + } + + public function dataFields(): array + { + return [ + Textarea::make('body') + ->label('Text') + ->rows(10) + ->required() + ->maxLength(20000) + ->helperText('Eine Leerzeile beginnt einen neuen Absatz.'), + ]; + } + + public function summary(array $widget): string + { + return RichText::excerpt(e((string) ($widget['data']['body'] ?? ''))); + } +} diff --git a/app/Domain/Cms/Widgets/WidgetErrors.php b/app/Domain/Cms/Widgets/WidgetErrors.php new file mode 100644 index 0000000..b262e98 --- /dev/null +++ b/app/Domain/Cms/Widgets/WidgetErrors.php @@ -0,0 +1,30 @@ +> */ + private array $messages = []; + + public function add(string $key, string $message): void + { + $this->messages[$key][] = $message; + } + + public function isEmpty(): bool + { + return $this->messages === []; + } + + /** + * @return array> + */ + public function all(): array + { + return $this->messages; + } +} diff --git a/app/Domain/Cms/Widgets/WidgetRegistry.php b/app/Domain/Cms/Widgets/WidgetRegistry.php new file mode 100644 index 0000000..16db1ed --- /dev/null +++ b/app/Domain/Cms/Widgets/WidgetRegistry.php @@ -0,0 +1,380 @@ + */ + private array $types = []; + + /** + * @param iterable $types + */ + public function __construct(iterable $types = []) + { + foreach ($types as $type) { + $this->register($type); + } + } + + public function register(WidgetType $type): void + { + $key = $type->key(); + + if (preg_match('/^[a-z][a-z0-9_]{1,40}$/', $key) !== 1) { + throw new InvalidArgumentException("Ungültige Widget-Kennung „{$key}“."); + } + + if (isset($this->types[$key])) { + throw new InvalidArgumentException("Die Widget-Kennung „{$key}“ ist bereits registriert."); + } + + if ($type->version() < 1) { + throw new InvalidArgumentException("Widget „{$key}“ braucht eine Schemaversion ab 1."); + } + + if ($type->variants() === []) { + throw new InvalidArgumentException("Widget „{$key}“ braucht mindestens eine Darstellungsvariante."); + } + + foreach (array_keys($type->variants()) as $variant) { + if (preg_match('/^[a-z][a-z0-9_]*$/', (string) $variant) !== 1) { + throw new InvalidArgumentException("Widget „{$key}“ hat eine ungültige Variantenkennung."); + } + } + + $this->types[$key] = $type; + } + + public function has(mixed $key): bool + { + return is_string($key) && isset($this->types[$key]); + } + + public function get(string $key): WidgetType + { + return $this->types[$key] ?? throw new InvalidArgumentException("Unbekannte Widget-Art „{$key}“."); + } + + /** + * @return array + */ + public function all(): array + { + return $this->types; + } + + /** + * @return array + */ + public function labels(): array + { + return array_map(fn (WidgetType $type): string => $type->label(), $this->types); + } + + /** + * Hebt einen gespeicherten Baustein auf die aktuelle Hülle an. Unbekannte Arten liefern null. + * + * @param array $block + * @return array{id: ?string, type: string, v: int, variant: string, settings: array, data: array, refs: array}|null + */ + public function upcast(array $block): ?array + { + $key = $block['type'] ?? null; + + if (! $this->has($key)) { + return null; + } + + $type = $this->get($key); + + if (array_key_exists('v', $block)) { + $widget = [ + 'id' => is_string($block['id'] ?? null) ? $block['id'] : null, + 'type' => $key, + 'v' => max(1, (int) $block['v']), + 'variant' => is_string($block['variant'] ?? null) ? $block['variant'] : $type->defaultVariant(), + 'settings' => is_array($block['settings'] ?? null) ? $block['settings'] : [], + 'data' => is_array($block['data'] ?? null) ? $block['data'] : [], + 'refs' => is_array($block['refs'] ?? null) ? $block['refs'] : [], + ]; + } else { + $legacy = $type->fromLegacy($block); + $widget = [ + 'id' => null, + 'type' => $key, + 'v' => 1, + 'variant' => $legacy['variant'] ?? $type->defaultVariant(), + 'settings' => [], + 'data' => $legacy['data'], + 'refs' => $legacy['refs'], + ]; + } + + while ($widget['v'] < $type->version()) { + $from = $widget['v']; + $widget = $type->upgrade($widget, $from); + $widget['v'] = $from + 1; + } + + if (! array_key_exists($widget['variant'], $type->variants())) { + $widget['variant'] = $type->defaultVariant(); + } + + return $widget; + } + + /** + * Prüft und bereinigt Bausteine für eine neue Revision. + * + * @param array $blocks + * @return list, data: array, refs: array}> + */ + public function normalize(array $blocks): array + { + $normalized = []; + $seenIds = []; + + foreach (array_values($blocks) as $index => $block) { + if (! is_array($block)) { + throw ValidationException::withMessages([ + "blocks.$index" => 'Ein Baustein ist unvollständig.', + ]); + } + + if (! $this->has($block['type'] ?? null)) { + throw ValidationException::withMessages([ + "blocks.$index.type" => 'Dieser Bausteintyp ist nicht freigegeben.', + ]); + } + + $type = $this->get($block['type']); + + if (array_key_exists('v', $block) && (int) $block['v'] > $type->version()) { + throw ValidationException::withMessages([ + "blocks.$index.v" => 'Dieser Baustein stammt aus einer neueren Programmfassung und kann hier nicht gespeichert werden.', + ]); + } + + $requested = $block['variant'] ?? null; + $isCurrent = array_key_exists('v', $block) && (int) $block['v'] === $type->version(); + + if ($isCurrent && is_string($requested) && $requested !== '' && ! array_key_exists($requested, $type->variants())) { + throw ValidationException::withMessages([ + "blocks.$index.variant" => 'Diese Darstellungsvariante ist für den Baustein nicht freigegeben.', + ]); + } + + $widget = $this->upcast($block); + $normalized[] = $this->validateOne($type, $widget, $index, $seenIds); + } + + return $normalized; + } + + /** + * Gespeicherte Bausteine einer Revision als aktuelle Hüllen; unbekannte Arten entfallen. + * + * @param array|null $blocks + * @return list> + */ + public function read(?array $blocks): array + { + $widgets = []; + + foreach (array_values($blocks ?? []) as $block) { + if (is_array($block) && ($widget = $this->upcast($block)) !== null) { + $widgets[] = $widget; + } + } + + return $widgets; + } + + /** + * @param array|null $blocks + */ + public function pageTitle(?array $blocks): ?string + { + foreach ($this->read($blocks) as $widget) { + $title = $this->get($widget['type'])->pageTitle($widget); + + if (is_string($title) && trim($title) !== '') { + return $title; + } + } + + return null; + } + + /** + * @param array|null $blocks + * @return list + */ + public function mediaPaths(?array $blocks): array + { + $paths = []; + + foreach ($this->read($blocks) as $widget) { + foreach ($this->get($widget['type'])->mediaPaths($widget) as $path) { + $paths[] = $path; + } + } + + return array_values(array_unique($paths)); + } + + /** + * @param array $widget + * @param array $seenIds + * @return array{id: string, type: string, v: int, variant: string, settings: array, data: array, refs: array} + */ + private function validateOne(WidgetType $type, array $widget, int $index, array &$seenIds): array + { + $errors = new WidgetErrors; + + $variant = $widget['variant']; + if (! array_key_exists($variant, $type->variants())) { + $errors->add('variant', 'Diese Darstellungsvariante ist für den Baustein nicht freigegeben.'); + } + + $settings = []; + $allowedSettings = $type->settings(); + foreach ($widget['settings'] as $key => $value) { + if ($value === null || $value === '') { + continue; + } + + if (! isset($allowedSettings[$key]) || ! is_string($value) || ! array_key_exists($value, $allowedSettings[$key])) { + $errors->add("settings.$key", 'Diese Einstellung ist für den Baustein nicht freigegeben.'); + + continue; + } + + $settings[$key] = $value; + } + + $rules = []; + foreach ($type->dataRules() as $key => $rule) { + $rules["data.$key"] = $rule; + } + foreach ($type->refRules() as $key => $rule) { + $rules["refs.$key"] = $rule; + } + + $validator = Validator::make(['data' => $widget['data'], 'refs' => $widget['refs']], $rules); + + foreach ($validator->errors()->messages() as $key => $messages) { + foreach ($messages as $message) { + $errors->add($key, $message); + } + } + + $data = $this->onlyDeclared($widget['data'], $type->dataRules()); + $refs = $this->onlyDeclared($widget['refs'], $type->refRules()); + + if ($errors->isEmpty()) { + [$data, $refs] = $type->clean($data, $refs, $errors); + } + + if (! $errors->isEmpty()) { + $messages = []; + foreach ($errors->all() as $key => $list) { + $messages["blocks.$index.$key"] = $list; + } + + throw ValidationException::withMessages($messages); + } + + $id = $widget['id']; + if (! is_string($id) || preg_match('/^[A-Za-z0-9-]{1,64}$/', $id) !== 1 || isset($seenIds[$id])) { + $id = (string) Str::uuid(); + } + $seenIds[$id] = true; + + return [ + 'id' => $id, + 'type' => $type->key(), + 'v' => $type->version(), + 'variant' => $variant, + 'settings' => $settings, + 'data' => $this->withoutTransient($data), + 'refs' => $this->withoutTransient($refs), + ]; + } + + /** + * Behält nur Schlüssel, für die Prüfregeln bestehen; Listen ('items.*.feld') werden je Eintrag gefiltert. + * + * @param array $values + * @param array $rules + * @return array + */ + private function onlyDeclared(array $values, array $rules): array + { + $top = []; + $nested = []; + + foreach (array_keys($rules) as $key) { + if (preg_match('/^([a-z_]+)\.\*\.([a-z_]+)$/', (string) $key, $match) === 1) { + $nested[$match[1]][] = $match[2]; + } elseif (! str_contains((string) $key, '.')) { + $top[] = (string) $key; + } + } + + $clean = []; + foreach ($top as $key) { + $value = $values[$key] ?? null; + + if (isset($nested[$key])) { + $items = []; + foreach (array_values(is_array($value) ? $value : []) as $item) { + if (! is_array($item)) { + continue; + } + + $entry = []; + foreach ($nested[$key] as $field) { + $entry[$field] = $item[$field] ?? null; + } + $items[] = $entry; + } + $value = $items; + } + + $clean[$key] = $value; + } + + return $clean; + } + + /** + * Felder mit führendem Unterstrich (zum Beispiel '_upload') sind reine Editorhilfen und werden nicht gespeichert. + * + * @param array $values + * @return array + */ + private function withoutTransient(array $values): array + { + foreach (array_keys($values) as $key) { + if (str_starts_with((string) $key, '_')) { + unset($values[$key]); + } + } + + return $values; + } +} diff --git a/app/Domain/Cms/Widgets/WidgetRenderer.php b/app/Domain/Cms/Widgets/WidgetRenderer.php new file mode 100644 index 0000000..34dc383 --- /dev/null +++ b/app/Domain/Cms/Widgets/WidgetRenderer.php @@ -0,0 +1,78 @@ +|null $blocks gespeicherte Bausteine (Altformat oder Hülle) + */ + public function renderAll(?array $blocks, RenderContext $context): HtmlString + { + $html = ''; + $position = 0; + + foreach (array_values($blocks ?? []) as $block) { + if (! is_array($block)) { + continue; + } + + $widget = $this->registry->upcast($block); + + if ($widget === null) { + if ($context->preview) { + $html .= '

Unbekannter Baustein „'.e((string) ($block['type'] ?? '')).'“ wird öffentlich nicht angezeigt.

'; + } + + continue; + } + + $rendered = $this->renderWidget($widget, $context, $position === 0); + + if ($rendered !== '') { + $html .= $rendered; + $position++; + } + } + + return new HtmlString($html); + } + + /** + * Rendert eine Instanz samt Abschnittshülle. Liefert '' wenn das Widget nichts darzustellen hat. + * + * @param array $widget aktuelle Hülle + */ + public function renderWidget(array $widget, RenderContext $context, bool $first = false): string + { + $type = $this->registry->get($widget['type']); + + $inner = trim(view($type->view(), [ + 'widget' => $widget, + 'data' => $widget['data'], + 'refs' => $widget['refs'], + 'variant' => $widget['variant'], + 'settings' => $widget['settings'], + 'first' => $first, + 'context' => $context, + ] + $type->resolve($widget, $context))->render()); + + if ($inner === '') { + return ''; + } + + $id = is_string($widget['id'] ?? null) ? ' id="abschnitt-'.e($widget['id']).'"' : ''; + + return '
' + .$inner + .'
'; + } +} diff --git a/app/Domain/Cms/Widgets/WidgetType.php b/app/Domain/Cms/Widgets/WidgetType.php new file mode 100644 index 0000000..a3acc98 --- /dev/null +++ b/app/Domain/Cms/Widgets/WidgetType.php @@ -0,0 +1,217 @@ + + */ + public function schematic(): array + { + return [[4, 6, 52, 4, 'ink'], [4, 14, 40, 3, 'line'], [4, 20, 44, 3, 'line'], [4, 26, 30, 3, 'line']]; + } + + /** + * Freigegebene Darstellungsvarianten: Kennung => Bezeichnung. Die erste ist die Vorgabe. + * + * @return array + */ + public function variants(): array + { + return ['standard' => 'Standard']; + } + + public function defaultVariant(): string + { + return (string) array_key_first($this->variants()); + } + + /** + * Zulässige Einstellungen: Schlüssel => [Wert => Bezeichnung]. Keine freien CSS-Klassen. + * + * @return array> + */ + public function settings(): array + { + return []; + } + + /** + * Prüfregeln für data. Schlüssel relativ zu data (zum Beispiel 'heading', 'items.*.title'). + * + * @return array + */ + abstract public function dataRules(): array; + + /** + * Prüfregeln für refs, relativ zu refs. + * + * @return array + */ + public function refRules(): array + { + return []; + } + + /** + * Formularfelder für data. Sie werden im Editor unter dem Zustandspfad 'data' eingehängt. + * + * @return list + */ + abstract public function dataFields(): array; + + /** + * Formularfelder für refs, eingehängt unter 'refs'. + * + * @return list + */ + public function refFields(): array + { + return []; + } + + /** + * Anordnung der Felder im Bearbeitungsdialog. Vorgabe: Inhalte, dann Verweise. + * Eine Art kann die Reihenfolge ändern, solange Felder unter 'data' beziehungsweise 'refs' bleiben. + * + * @return list + */ + public function editorSchema(): array + { + $schema = []; + + if ($this->dataFields() !== []) { + $schema[] = Group::make($this->dataFields())->statePath('data'); + } + + if ($this->refFields() !== []) { + $schema[] = Group::make($this->refFields())->statePath('refs'); + } + + return $schema; + } + + /** Blade-Ansicht. Sie dient öffentlicher Seite, ganzseitiger Vorschau und Blockvorschau gleichermaßen. */ + public function view(): string + { + return 'widgets.'.$this->key(); + } + + /** + * Übersetzt einen Altbaustein ohne Hülle (Bestand vor der Registry) in data/refs/variant der Version 1. + * + * @param array $legacy + * @return array{data: array, refs: array, variant?: string} + */ + public function fromLegacy(array $legacy): array + { + unset($legacy['type']); + + return ['data' => $legacy, 'refs' => []]; + } + + /** + * Hebt eine Instanz von Version $from auf $from + 1. Alte Revisionen bleiben gespeichert, wie sie sind. + * + * @param array $widget + * @return array + */ + public function upgrade(array $widget, int $from): array + { + throw new \LogicException(sprintf('Widget %s kennt keinen Schritt von Version %d.', $this->key(), $from)); + } + + /** + * Bereinigt geprüfte Inhalte vor dem Speichern (Adressen, formatierter Text, Bildauswahl). + * + * @param array $data + * @param array $refs + * @return array{0: array, 1: array} + */ + public function clean(array $data, array $refs, WidgetErrors $errors): array + { + return [$data, $refs]; + } + + /** + * Löst Verweise für die Darstellung auf und liefert zusätzliche Ansichtsvariablen. + * + * @param array $widget + * @return array + */ + public function resolve(array $widget, RenderContext $context): array + { + return []; + } + + /** + * Öffentliche Medienpfade dieser Instanz (für Veröffentlichung und Verwendungsnachweis). + * + * @param array $widget + * @return list + */ + public function mediaPaths(array $widget): array + { + return []; + } + + /** + * Kurze Inhaltszusammenfassung für die Abschnittsliste im Editor. + * + * @param array $widget + */ + public function summary(array $widget): string + { + return ''; + } + + /** + * Titel, den eine Seite aus diesem Widget übernehmen kann, wenn kein SEO-Titel gesetzt ist. + * + * @param array $widget + */ + public function pageTitle(array $widget): ?string + { + return null; + } +} diff --git a/app/Filament/Resources/NavigationItems/NavigationItemResource.php b/app/Filament/Resources/NavigationItems/NavigationItemResource.php index fc39226..58a4ed2 100644 --- a/app/Filament/Resources/NavigationItems/NavigationItemResource.php +++ b/app/Filament/Resources/NavigationItems/NavigationItemResource.php @@ -4,14 +4,22 @@ use App\Domain\Cms\NavigationItem; use App\Domain\Cms\Page; +use App\Domain\Cms\Widgets\Support\SafeUrl; use App\Filament\Resources\NavigationItems\Pages\ManageNavigationItems; use Closure; +use Filament\Actions\Action; +use Filament\Actions\DeleteAction; +use Filament\Actions\EditAction; use Filament\Forms\Components\Select; use Filament\Forms\Components\TextInput; +use Filament\Forms\Components\Toggle; use Filament\Resources\Resource; use Filament\Schemas\Components\Utilities\Get; use Filament\Schemas\Schema; +use Filament\Tables\Columns\IconColumn; use Filament\Tables\Columns\TextColumn; +use Filament\Tables\Filters\SelectFilter; +use Filament\Tables\Grouping\Group; use Filament\Tables\Table; class NavigationItemResource extends Resource @@ -28,13 +36,21 @@ public static function form(Schema $schema): Schema { return $schema->components([ TextInput::make('label')->label('Beschriftung')->required()->maxLength(80), + Select::make('placement') + ->label('Platz') + ->options(NavigationItem::PLACEMENTS) + ->default('header') + ->required(), Select::make('page_id') - ->label('Seite') + ->label('Interne Seite') ->options(fn (): array => Page::query()->orderBy('path')->pluck('path', 'id')->all()) - ->searchable(), + ->searchable() + ->helperText('Bevorzugt: eine CMS-Seite wählen. Dann folgt der Link automatisch einer Pfadänderung.'), TextInput::make('url') - ->label('Adresse') + ->label('Oder Adresse') ->maxLength(500) + ->helperText('Nur wenn keine Seite gewählt ist: Pfad wie /anmelden oder eine vollständige http(s)-Adresse.') + ->rule(SafeUrl::rule()) ->rule(function (Get $get): Closure { return function (string $attribute, mixed $value, Closure $fail) use ($get): void { if (blank($get('page_id')) && blank($value)) { @@ -42,14 +58,16 @@ public static function form(Schema $schema): Schema } }; }), - Select::make('placement') - ->label('Platz') - ->options([ - 'header' => 'Kopfzeile', - 'footer' => 'Fußzeile', - ]) + Toggle::make('is_visible') + ->label('Auf der Website anzeigen') + ->default(true), + TextInput::make('sort_order') + ->label('Reihenfolge') + ->numeric() + ->minValue(0) + ->default(fn (): int => (int) NavigationItem::query()->max('sort_order') + 1) + ->helperText('Kleinere Zahlen stehen weiter vorn. In der Liste lässt sich die Reihenfolge auch per Ziehen ändern.') ->required(), - TextInput::make('sort_order')->label('Reihenfolge')->numeric()->required()->default(0), ]); } @@ -57,13 +75,43 @@ public static function table(Table $table): Table { return $table ->columns([ - TextColumn::make('label')->label('Beschriftung'), - TextColumn::make('page.path')->label('Seite'), - TextColumn::make('url')->label('Adresse'), - TextColumn::make('placement')->label('Platz'), - TextColumn::make('sort_order')->label('Reihenfolge')->sortable(), + TextColumn::make('label')->label('Beschriftung')->searchable(), + TextColumn::make('target') + ->label('Ziel') + ->state(fn (NavigationItem $record): string => $record->page?->path ?? (string) $record->url), + IconColumn::make('is_visible') + ->label('Sichtbar') + ->boolean(), + TextColumn::make('sort_order')->label('Reihenfolge'), ]) - ->defaultSort('sort_order'); + ->defaultGroup( + Group::make('placement') + ->label('Platz') + ->getTitleFromRecordUsing(fn (NavigationItem $record): string => NavigationItem::PLACEMENTS[$record->placement] ?? $record->placement) + ->orderQueryUsing(fn ($query, string $direction) => $query->orderByRaw("CASE placement WHEN 'header' THEN 0 ELSE 1 END")) + ->collapsible(), + ) + ->paginated([50, 100]) + ->defaultPaginationPageOption(50) + ->filters([ + SelectFilter::make('placement')->label('Platz')->options(NavigationItem::PLACEMENTS), + ]) + ->reorderable('sort_order') + ->reorderRecordsTriggerAction(fn (Action $action, bool $isReordering): Action => $action + ->button() + ->label($isReordering ? 'Sortieren beenden' : 'Reihenfolge ändern')) + ->defaultSort('sort_order') + ->recordActions([ + Action::make('toggleVisibility') + ->label(fn (NavigationItem $record): string => $record->is_visible ? 'Ausblenden' : 'Einblenden') + ->icon(fn (NavigationItem $record): string => $record->is_visible ? 'heroicon-o-eye-slash' : 'heroicon-o-eye') + ->color('gray') + ->authorize(fn (NavigationItem $record): bool => auth()->user()?->can('update', $record) ?? false) + ->action(fn (NavigationItem $record) => $record->update(['is_visible' => ! $record->is_visible])), + EditAction::make(), + DeleteAction::make() + ->modalDescription('Der Eintrag wird aus der Navigation entfernt. Die verlinkte Seite bleibt bestehen.'), + ]); } public static function getPages(): array diff --git a/app/Filament/Resources/Pages/PageResource.php b/app/Filament/Resources/Pages/PageResource.php index 463bbc8..ea601b3 100644 --- a/app/Filament/Resources/Pages/PageResource.php +++ b/app/Filament/Resources/Pages/PageResource.php @@ -3,20 +3,17 @@ namespace App\Filament\Resources\Pages; use App\Domain\Catalog\Pillar; -use App\Domain\Cms\Blocks\BlockRegistry; use App\Domain\Cms\Page; use App\Filament\Resources\Pages\Pages\CreatePage; use App\Filament\Resources\Pages\Pages\EditPage; use App\Filament\Resources\Pages\Pages\ListPages; use App\Filament\Resources\Pages\RelationManagers\RevisionsRelationManager; +use App\Filament\Support\WidgetEditor; use Filament\Forms\Components\CheckboxList; -use Filament\Forms\Components\FileUpload; -use Filament\Forms\Components\Repeater; -use Filament\Forms\Components\Select; use Filament\Forms\Components\Textarea; use Filament\Forms\Components\TextInput; use Filament\Resources\Resource; -use Filament\Schemas\Components\Utilities\Get; +use Filament\Schemas\Components\Section; use Filament\Schemas\Schema; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; @@ -35,76 +32,37 @@ class PageResource extends Resource public static function form(Schema $schema): Schema { - $labels = app(BlockRegistry::class)->labels(); - return $schema->components([ - TextInput::make('path') - ->label('Pfad') - ->required() - ->maxLength(255) - ->helperText('Zum Beispiel / oder /praevention'), - TextInput::make('seo_title') - ->label('SEO-Titel') - ->maxLength(255), - Textarea::make('seo_description') - ->label('SEO-Beschreibung') - ->maxLength(500) - ->columnSpanFull(), - CheckboxList::make('pillars') - ->label('Fachliche Säulen') - ->options(fn (): array => Pillar::query()->orderBy('name')->pluck('name', 'id')->all()) - ->helperText('Eine veröffentlichte Seite erscheint auf den gewählten Themenbereichen der Website. Eine Seite kann mehreren Säulen zugeordnet sein.') - ->columns(1), - Repeater::make('blocks') - ->label('Bausteine') - ->schema([ - Select::make('type') - ->label('Typ') - ->options($labels) - ->required() - ->live(), - TextInput::make('heading') - ->label('Überschrift') - ->visible(fn (Get $get): bool => in_array($get('type'), ['heading', 'call_to_action'], true)), - Textarea::make('intro') - ->label('Einleitung') - ->visible(fn (Get $get): bool => $get('type') === 'heading'), - Textarea::make('body') - ->label('Text') - ->visible(fn (Get $get): bool => in_array($get('type'), ['prose', 'image_text'], true)) - ->columnSpanFull(), - FileUpload::make('image') - ->label('Bild') - ->disk('cms_incoming') - ->directory('cms') - ->image() - ->visible(fn (Get $get): bool => $get('type') === 'image_text'), - TextInput::make('alt') - ->label('Alternativtext') - ->visible(fn (Get $get): bool => $get('type') === 'image_text'), - Textarea::make('text') - ->label('Text') - ->visible(fn (Get $get): bool => $get('type') === 'call_to_action'), - TextInput::make('label') - ->label('Beschriftung der Aktion') - ->visible(fn (Get $get): bool => $get('type') === 'call_to_action'), - TextInput::make('url') - ->label('Adresse') - ->visible(fn (Get $get): bool => $get('type') === 'call_to_action'), - Repeater::make('items') - ->label('Einträge') - ->visible(fn (Get $get): bool => in_array($get('type'), ['cards', 'faq'], true)) - ->schema([ - TextInput::make('title')->label('Titel')->visible(fn (Get $get): bool => $get('../../type') === 'cards'), - Textarea::make('text')->label('Text')->visible(fn (Get $get): bool => $get('../../type') === 'cards'), - TextInput::make('url')->label('Adresse')->visible(fn (Get $get): bool => $get('../../type') === 'cards'), - TextInput::make('question')->label('Frage')->visible(fn (Get $get): bool => $get('../../type') === 'faq'), - Textarea::make('answer')->label('Antwort')->visible(fn (Get $get): bool => $get('../../type') === 'faq'), - ]), - ]) + Section::make('Seite und Suchmaschinen') + ->description('Adresse, Titel für Suchmaschinen und Zuordnung zu Themenbereichen.') + ->collapsible() + ->columns(2) ->columnSpanFull() - ->reorderable() - ->collapsed(), + ->schema([ + TextInput::make('path') + ->label('Pfad') + ->required() + ->maxLength(255) + ->helperText('Zum Beispiel / oder /praevention'), + TextInput::make('seo_title') + ->label('SEO-Titel') + ->maxLength(255), + Textarea::make('seo_description') + ->label('SEO-Beschreibung') + ->maxLength(500) + ->columnSpanFull(), + CheckboxList::make('pillars') + ->label('Fachliche Säulen') + ->options(fn (): array => Pillar::query()->orderBy('name')->pluck('name', 'id')->all()) + ->helperText('Eine veröffentlichte Seite erscheint auf den gewählten Themenbereichen der Website. Eine Seite kann mehreren Säulen zugeordnet sein.') + ->columns(1), + ]), + Section::make('Inhalt der Seite') + ->description('Abschnitte hinzufügen, per Klick auf die Vorschau bearbeiten, mit den Pfeilen sortieren. Speichern legt einen Entwurf an; veröffentlicht wird erst über „Veröffentlichen“.') + ->columnSpanFull() + ->schema([ + WidgetEditor::builder('blocks'), + ]), ]); } diff --git a/app/Filament/Resources/Pages/Pages/CreatePage.php b/app/Filament/Resources/Pages/Pages/CreatePage.php index f9ef2dc..5ec256c 100644 --- a/app/Filament/Resources/Pages/Pages/CreatePage.php +++ b/app/Filament/Resources/Pages/Pages/CreatePage.php @@ -5,31 +5,51 @@ use App\Domain\Cms\Page; use App\Domain\Cms\PageService; use App\Filament\Resources\Pages\PageResource; +use App\Filament\Support\WidgetEditor; use Filament\Resources\Pages\CreateRecord; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\DB; +use Illuminate\Validation\ValidationException; class CreatePage extends CreateRecord { protected static string $resource = PageResource::class; + protected static bool $canCreateAnother = false; + /** * @param array $data */ protected function handleRecordCreation(array $data): Model { $service = app(PageService::class); - $page = Page::query()->create([ - 'path' => $service->normalizePath($data['path']), - ]); + $blocks = WidgetEditor::fromBuilderState($data['blocks'] ?? []); - $service->saveRevision( - $page, - $data['blocks'] ?? [], - $data['seo_title'] ?? null, - $data['seo_description'] ?? null, - auth()->user(), - ); + try { + return DB::transaction(function () use ($service, $data, $blocks): Page { + $page = Page::query()->create([ + 'path' => $service->availablePath($data['path']), + ]); - return $page; + $service->saveRevision( + $page, + $blocks, + $data['seo_title'] ?? null, + $data['seo_description'] ?? null, + auth()->user(), + ); + + return $page; + }); + } catch (ValidationException $exception) { + throw ValidationException::withMessages( + WidgetEditor::mapErrors($exception->errors(), array_keys($this->data['blocks'] ?? [])), + ); + } + } + + protected function getRedirectUrl(): string + { + return static::getResource()::getUrl('edit', ['record' => $this->getRecord()]); } } diff --git a/app/Filament/Resources/Pages/Pages/EditPage.php b/app/Filament/Resources/Pages/Pages/EditPage.php index 078371b..913a8e2 100644 --- a/app/Filament/Resources/Pages/Pages/EditPage.php +++ b/app/Filament/Resources/Pages/Pages/EditPage.php @@ -6,9 +6,12 @@ use App\Domain\Cms\Page; use App\Domain\Cms\PageService; use App\Filament\Resources\Pages\PageResource; +use App\Filament\Support\WidgetEditor; use Filament\Actions\Action; +use Filament\Notifications\Notification; use Filament\Resources\Pages\EditRecord; use Illuminate\Database\Eloquent\Model; +use Illuminate\Validation\ValidationException; class EditPage extends EditRecord { @@ -19,27 +22,52 @@ protected function getHeaderActions(): array return [ Action::make('preview') ->label('Vorschau') + ->icon('heroicon-o-device-phone-mobile') + ->color('gray') + ->tooltip('Zuletzt gespeicherten Entwurf in Smartphone-, Tablet- und Desktopbreite ansehen') ->url(function (): string { $revision = $this->record->latestRevision; return $revision === null ? '#' - : route('pages.preview', $revision); + : route('pages.preview.devices', $revision); }) ->openUrlInNewTab(), Action::make('publish') ->label('Veröffentlichen') + ->icon('heroicon-o-globe-alt') ->requiresConfirmation() + ->modalHeading('Zuletzt gespeicherten Entwurf veröffentlichen?') + ->modalDescription(fn (): string => 'Veröffentlicht wird Revision Nr. '.($this->record->latestRevision?->id ?? '–').'. Noch nicht gespeicherte Änderungen werden nicht veröffentlicht.') ->visible(fn (): bool => auth()->user()?->can('publish', $this->record) ?? false) ->action(function (PageService $service): void { $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(); }), + Action::make('open') + ->label('Live-Seite') + ->icon('heroicon-o-arrow-top-right-on-square') + ->color('gray') + ->visible(fn (): bool => $this->record->isPublished()) + ->url(fn (): string => $this->record->publicUrl()) + ->openUrlInNewTab(), ]; } + 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.'; + } + /** * @param array $data * @return array @@ -47,7 +75,7 @@ protected function getHeaderActions(): array protected function mutateFormDataBeforeFill(array $data): array { $revision = $this->record->latestRevision ?? $this->record->publishedRevision; - $data['blocks'] = $revision?->blocks ?? []; + $data['blocks'] = WidgetEditor::toBuilderState($revision?->blocks); $data['seo_title'] = $revision?->seo_title; $data['seo_description'] = $revision?->seo_description; $data['pillars'] = $this->record->pillars()->pluck('pillars.id')->all(); @@ -62,19 +90,22 @@ protected function handleRecordUpdate(Model $record, array $data): Model { /** @var Page $record */ $service = app(PageService::class); + $blocks = WidgetEditor::fromBuilderState($data['blocks'] ?? []); + + try { + $path = $service->availablePath($data['path'], $record); + $service->saveRevision($record, $blocks, $data['seo_title'] ?? null, $data['seo_description'] ?? null, auth()->user()); + } catch (ValidationException $exception) { + throw ValidationException::withMessages( + WidgetEditor::mapErrors($exception->errors(), array_keys($this->data['blocks'] ?? [])), + ); + } + $record->update([ - 'path' => $service->normalizePath($data['path']), + 'path' => $path, ]); app(PillarService::class)->assignPages($record, array_map(intval(...), $data['pillars'] ?? [])); - $service->saveRevision( - $record, - $data['blocks'] ?? [], - $data['seo_title'] ?? null, - $data['seo_description'] ?? null, - auth()->user(), - ); - return $record; } } diff --git a/app/Filament/Resources/Pages/RelationManagers/RevisionsRelationManager.php b/app/Filament/Resources/Pages/RelationManagers/RevisionsRelationManager.php index f61b7c5..79c4739 100644 --- a/app/Filament/Resources/Pages/RelationManagers/RevisionsRelationManager.php +++ b/app/Filament/Resources/Pages/RelationManagers/RevisionsRelationManager.php @@ -4,7 +4,9 @@ use App\Domain\Cms\PageRevision; use App\Domain\Cms\PageService; +use App\Filament\Resources\Pages\PageResource; use Filament\Actions\Action; +use Filament\Notifications\Notification; use Filament\Resources\RelationManagers\RelationManager; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; @@ -22,11 +24,22 @@ public function table(Table $table): Table TextColumn::make('id')->label('Nr.'), TextColumn::make('created_at')->label('Gespeichert')->dateTime('d.m.Y H:i'), TextColumn::make('author.name')->label('Von'), + TextColumn::make('sections') + ->label('Abschnitte') + ->state(fn (PageRevision $record): int => count($record->widgets())), TextColumn::make('published') ->label('Live') + ->badge() + ->color(fn (string $state): string => $state === 'Ja' ? 'success' : 'gray') ->state(fn (PageRevision $record): string => $record->id === $this->getOwnerRecord()->published_revision_id ? 'Ja' : 'Nein'), ]) ->recordActions([ + Action::make('preview') + ->label('Vorschau') + ->icon('heroicon-o-eye') + ->color('gray') + ->url(fn (PageRevision $record): string => route('pages.preview.devices', $record)) + ->openUrlInNewTab(), Action::make('publish') ->label('Veröffentlichen') ->requiresConfirmation() @@ -34,13 +47,16 @@ public function table(Table $table): Table ->action(function (PageRevision $record, PageService $service): void { $service->publish($this->getOwnerRecord(), $record); $this->getOwnerRecord()->refresh(); + Notification::make()->title('Revision '.$record->id.' ist jetzt live.')->success()->send(); }), Action::make('restore') ->label('Wiederherstellen') ->requiresConfirmation() - ->modalDescription('Es entsteht eine neue Revision. Die Live-Seite bleibt unverändert, bis sie veröffentlicht wird.') + ->modalDescription('Es entsteht eine neue Revision mit diesem Stand. Die Live-Seite bleibt unverändert, bis sie veröffentlicht wird.') ->action(function (PageRevision $record, PageService $service): void { - $service->restore($this->getOwnerRecord(), $record, auth()->user()); + $restored = $service->restore($this->getOwnerRecord(), $record, auth()->user()); + Notification::make()->title('Als neue Revision '.$restored->id.' wiederhergestellt.')->success()->send(); + $this->redirect(PageResource::getUrl('edit', ['record' => $this->getOwnerRecord()])); }), ]) ->defaultSort('id', 'desc'); diff --git a/app/Filament/Support/WidgetBlock.php b/app/Filament/Support/WidgetBlock.php new file mode 100644 index 0000000..83242fc --- /dev/null +++ b/app/Filament/Support/WidgetBlock.php @@ -0,0 +1,23 @@ + $data + */ + public function renderPreview(array $data): View + { + return view('filament.cms.widget-preview', [ + 'html' => WidgetEditor::renderPreview($this->getName(), $data), + 'stylesheets' => WidgetEditor::previewStylesheets(), + ]); + } +} diff --git a/app/Filament/Support/WidgetEditor.php b/app/Filament/Support/WidgetEditor.php new file mode 100644 index 0000000..86246c1 --- /dev/null +++ b/app/Filament/Support/WidgetEditor.php @@ -0,0 +1,328 @@ +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(); + } + + public static function block(WidgetType $type): Block + { + $variants = $type->variants(); + + $schema = [Hidden::make('id')]; + + $schema[] = count($variants) > 1 + ? ToggleButtons::make('variant') + ->label('Darstellung') + ->options($variants) + ->default($type->defaultVariant()) + ->inline() + ->required() + : Hidden::make('variant')->default($type->defaultVariant()); + + if ($type->settings() !== []) { + $settings = []; + foreach ($type->settings() as $key => $options) { + $settings[] = Select::make($key)->label(Str::headline($key))->options($options); + } + $schema[] = Group::make($settings)->statePath('settings'); + } + + foreach ($type->editorSchema() as $component) { + $schema[] = $component; + } + + 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'); + } + + /** + * Gespeicherte Bausteine (Altformat oder Hülle) als Builder-Zustand. + * + * @param array|null $blocks + * @return list}> + */ + 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|null $state + * @return list> + */ + 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 $errors + * @param list $itemKeys Builder-Schlüssel in Anzeigereihenfolge + * @return array + */ + 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; + } + + /** + * Blockvorschau: dieselbe Widget-Ansicht wie öffentlich, aus dem ungespeicherten Zustand. + * + * @param array $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 '

Die Vorschau dieses Abschnitts ist noch unvollständig.

'; + } + } + + 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( + '' + .self::schematicSvg($type) + .''.e($type->label()).'' + .''.e($type->description()).'' + ); + } + + /** + * @param array $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('', $x, $y, $w, $h, $fills[$tone] ?? $fills['line']); + } + + return ''; + } + + /** + * Roh-Zustand des Formulars (Repeater mit UUID-Schlüsseln, Texteditor als Dokument) in einfache Werte. + * + * @param array $state + * @return array + */ + 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 $values + * @return array + */ + 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 $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; + } +} diff --git a/app/Http/Controllers/PageController.php b/app/Http/Controllers/PageController.php index 95c76de..3008ad1 100644 --- a/app/Http/Controllers/PageController.php +++ b/app/Http/Controllers/PageController.php @@ -5,6 +5,9 @@ use App\Domain\Catalog\Pillar; use App\Domain\Cms\Page; use App\Domain\Cms\PageRevision; +use App\Domain\Cms\PageTemplates; +use App\Domain\Cms\Widgets\RenderContext; +use App\Domain\Cms\Widgets\WidgetRenderer; use Illuminate\Contracts\View\View; use Illuminate\Http\Response; use Illuminate\Support\Facades\Gate; @@ -24,11 +27,26 @@ public function show(string $path): View public function preview(PageRevision $revision): View { $page = $revision->page; - Gate::authorize('view', $page); + Gate::forUser(auth('staff')->user())->authorize('view', $page); return $this->render($page, preview: true, revision: $revision); } + /** + * Rahmen für die Vorschau einer Revision in den Breiten Smartphone, Tablet und Desktop. + */ + public function devices(PageRevision $revision): View + { + $page = $revision->page; + Gate::forUser(auth('staff')->user())->authorize('view', $page); + + return view('public.preview-devices', [ + 'page' => $page, + 'revision' => $revision, + 'isLive' => $page->published_revision_id === $revision->id, + ]); + } + public function sitemap(): Response { $pages = Page::query()->whereNotNull('published_revision_id')->orderBy('path')->get(); @@ -44,13 +62,15 @@ private function render(Page $page, bool $preview, ?PageRevision $revision = nul $revision ??= $page->publishedRevision; abort_if($revision === null, 404); - $heading = collect($revision->blocks)->firstWhere('type', 'heading'); + $context = $preview ? RenderContext::preview() : RenderContext::publicPage(); return view('public.page', [ 'page' => $page, 'revision' => $revision, 'preview' => $preview, - 'documentTitle' => $revision->seo_title ?: ($heading['heading'] ?? config('app.name')), + 'template' => app(PageTemplates::class)->viewFor($page), + 'content' => app(WidgetRenderer::class)->renderAll($revision->blocks, $context), + 'documentTitle' => $revision->seo_title ?: ($revision->contentTitle() ?? config('app.name')), 'documentDescription' => $revision->seo_description, 'themes' => $page->path === '/' ? Pillar::query()->published()->get() : collect(), ]); diff --git a/app/Http/Controllers/PublicCatalogController.php b/app/Http/Controllers/PublicCatalogController.php index d3650f2..5cd36b4 100644 --- a/app/Http/Controllers/PublicCatalogController.php +++ b/app/Http/Controllers/PublicCatalogController.php @@ -3,30 +3,20 @@ namespace App\Http\Controllers; use App\Domain\Catalog\Composition; -use App\Domain\Catalog\CompositionDisplayRelease; use App\Domain\Catalog\CompositionStructureReader; -use App\Domain\Catalog\EditorialContentKind; +use App\Domain\Cms\Catalog\PublicCatalogReader; use Illuminate\View\View; class PublicCatalogController extends Controller { - public function index(): View + public function index(PublicCatalogReader $catalog): View { - $kind = EditorialContentKind::query()->where('slug', 'programm')->first(); - $programs = Composition::query() - ->when($kind !== null, fn ($query) => $query->where('editorial_content_kind_id', $kind->id)) - ->orderBy('designation') - ->get() - ->filter(fn (Composition $composition): bool => app(CompositionDisplayRelease::class)->highestReleasedVersion($composition) !== null); - - return view('public.programs', ['programs' => $programs]); + return view('public.programs', ['programs' => $catalog->publicPrograms()]); } - public function program(Composition $composition): View + public function program(Composition $composition, PublicCatalogReader $catalog): View { - $kind = $composition->editorialContentKind; - abort_unless($kind?->slug === 'programm', 404); - $version = app(CompositionDisplayRelease::class)->highestReleasedVersion($composition); + $version = $catalog->shownVersion($composition); abort_if($version === null, 404); return view('public.program', [ diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 87da06d..1d2887d 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -6,6 +6,7 @@ use App\Domain\Cms\NavigationItemPolicy; use App\Domain\Cms\Page; use App\Domain\Cms\PagePolicy; +use App\Domain\Cms\Widgets\WidgetRegistry; use App\Domain\Media\FfmpegFilmTranscoder; use App\Domain\Media\FilmTranscoder; use App\Filament\Support\MediaUploadLimit; @@ -22,6 +23,9 @@ class AppServiceProvider extends ServiceProvider public function register(): void { $this->app->bind(FilmTranscoder::class, FfmpegFilmTranscoder::class); + $this->app->singleton(WidgetRegistry::class, fn ($app): WidgetRegistry => new WidgetRegistry( + array_map(fn (string $class) => $app->make($class), config('cms.widgets', [])), + )); } public function boot(): void @@ -38,7 +42,7 @@ public function boot(): void View::composer('layouts.site', function ($view): void { if (! array_key_exists('navigation', $view->getData())) { - $view->with('navigation', NavigationItem::query()->with('page')->orderBy('sort_order')->orderBy('id')->get()); + $view->with('navigation', NavigationItem::query()->visible()->with('page')->orderBy('sort_order')->orderBy('id')->get()); } }); } diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php index fea2e7a..01bc41b 100644 --- a/app/Providers/Filament/AdminPanelProvider.php +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -67,6 +67,10 @@ public function panel(Panel $panel): Panel ->authMiddleware([ Authenticate::class, ]) + ->renderHook( + PanelsRenderHook::STYLES_AFTER, + fn (): string => view('filament.cms.styles')->render(), + ) ->renderHook( PanelsRenderHook::BODY_END, fn (): string => app()->environment('testing') ? '' : Blade::render("@vite('resources/js/app.js')"), diff --git a/config/cms.php b/config/cms.php new file mode 100644 index 0000000..f7c4551 --- /dev/null +++ b/config/cms.php @@ -0,0 +1,38 @@ +.blade.php, hier eintragen. Siehe docs/architektur/cms-widget-registry.md. + | Eine einmal verwendete Kennung wird nie entfernt, solange Revisionen sie enthalten. + */ + 'widgets' => [ + HeroWidget::class, + HeadingWidget::class, + ProseWidget::class, + ImageTextWidget::class, + CardsWidget::class, + CatalogCardsWidget::class, + CallToActionWidget::class, + FaqWidget::class, + ], + + /* + | Seitenvorlagen. Für diesen Ausbau gibt es eine Vorlage; weitere werden hier ergänzt. + */ + 'templates' => [ + 'standard' => 'site.templates.standard', + ], + +]; diff --git a/database/migrations/2026_11_17_100000_add_visibility_to_navigation_items.php b/database/migrations/2026_11_17_100000_add_visibility_to_navigation_items.php new file mode 100644 index 0000000..6aae70c --- /dev/null +++ b/database/migrations/2026_11_17_100000_add_visibility_to_navigation_items.php @@ -0,0 +1,25 @@ +boolean('is_visible')->default(true); + }); + } + + public function down(): void + { + Schema::table('navigation_items', function (Blueprint $table) { + $table->dropColumn('is_visible'); + }); + } +}; diff --git a/resources/css/app.css b/resources/css/app.css index a2de2c4..89089ff 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -235,9 +235,21 @@ .image-text { @media (min-width: 48rem) { .image-text { - grid-template-columns: minmax(12rem, 16rem) 1fr; + grid-template-columns: minmax(12rem, 22rem) 1fr; align-items: start; } + + .image-text-right { + grid-template-columns: 1fr minmax(12rem, 22rem); + } + + .image-text-right > img { + order: 2; + } + + .image-text-no-image { + grid-template-columns: 1fr; + } } .image-text img { @@ -245,6 +257,184 @@ .image-text img { height: auto; } +.image-text-copy > :first-child { + margin-top: 0; +} + +.prose ul, +.prose ol { + margin: 0 0 1rem; + padding-left: 1.4rem; +} + +.prose li > p { + margin: 0; +} + +/* Widgets: Einstieg (Hero). Varianten: standard, highlight. */ +.hero { + display: grid; + gap: 1.5rem; + align-items: center; +} + +.hero .lede { + font-size: 1.2rem; +} + +.hero-image { + width: 100%; + height: auto; + display: block; +} + +@media (min-width: 48rem) { + .hero-with-image { + grid-template-columns: 1.1fr 1fr; + } +} + +.hero-highlight { + background: var(--color-ink); + color: #f4f7f5; + padding: clamp(1.5rem, 4vw, 3rem); +} + +.hero-highlight h1, +.hero-highlight h2, +.hero-highlight .lede { + color: inherit; +} + +.button { + display: inline-block; + margin-top: 0.5rem; + background: var(--color-pine); + color: #ffffff; + text-decoration: none; + padding: 0.65rem 1.05rem; + font-weight: 600; +} + +.button:hover { + text-decoration: underline; +} + +.hero-highlight .button { + background: #f4f7f5; + color: var(--color-ink); +} + +/* Widgets: redaktionelle Karten. Varianten: Raster (cards-grid), kompakte Liste (cards-compact). */ +.card-image { + display: block; + width: calc(100% + 2rem); + max-width: none; + height: auto; + aspect-ratio: 16 / 9; + object-fit: cover; + margin: -1rem -1rem 0.85rem; +} + +.cards-compact { + grid-template-columns: 1fr; + gap: 0; +} + +.cards-compact .card { + border-top: 0; + border-bottom: 1px solid var(--color-line); + background: transparent; + padding: 0.85rem 0; +} + +.cards-compact .card-image { + display: none; +} + +.cards-compact .card h3 { + font-size: 1.15rem; +} + +/* Widgets: Programm- und Modulkarten. Inhalte kommen aus den Fachdaten. */ +.catalog-list { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); + gap: 1rem; + list-style: none; + padding: 0; + margin: 1rem 0 0; +} + +.catalog-card { + background: white; + border: 1px solid var(--color-line); + display: flex; + flex-direction: column; +} + +.catalog-card-visual { + background: var(--color-paper); + border-bottom: 3px solid var(--color-pine); + min-height: 6rem; + display: flex; + align-items: flex-end; + padding: 0.75rem 1rem; +} + +.catalog-card-visual span { + font-family: var(--font-serif); + font-size: 1.1rem; + color: var(--color-pine); +} + +.catalog-card-body { + padding: 0.9rem 1rem 1.1rem; +} + +.catalog-card-body h3 { + font-family: var(--font-serif); + font-size: 1.35rem; + margin: 0 0 0.4rem; +} + +.catalog-card-body p { + margin: 0 0 0.5rem; +} + +.catalog-card-kind { + font-size: 0.85rem; + text-transform: uppercase; + letter-spacing: 0.06em; + color: #3f5248; +} + +.catalog-cards-compact .catalog-list { + grid-template-columns: 1fr; + gap: 0; +} + +.catalog-cards-compact .catalog-card { + border-width: 0 0 1px; + background: transparent; +} + +.catalog-cards-compact .catalog-card-body { + padding: 0.75rem 0; +} + +.catalog-card-internal { + border-style: dashed; +} + +.preview-note { + background: #fff4d6; + color: #3d2e04; + font-size: 0.9rem; + padding: 0.5rem 0.75rem; + margin: 0.5rem 0 0; +} + .faq { margin: 0; } @@ -382,9 +572,26 @@ .site-footer { padding: 2rem 0 3rem; } +.site-footer-inner { + display: flex; + flex-wrap: wrap; + gap: 1rem 2rem; + align-items: baseline; + justify-content: space-between; +} + +.wordmark-compact { + padding-top: 0; +} + +.wordmark-compact strong { + font-size: 1.5rem; +} + .site-footer nav { display: flex; - gap: 1rem; + flex-wrap: wrap; + gap: 0.5rem 1rem; } .site-footer a { diff --git a/resources/views/components/site/brand.blade.php b/resources/views/components/site/brand.blade.php new file mode 100644 index 0000000..15f37ed --- /dev/null +++ b/resources/views/components/site/brand.blade.php @@ -0,0 +1,10 @@ +{{-- + Markenzeichen der Website. Solange keine freigegebene Wortmarke als Datei vorliegt + (docs/Brand-UI-Kit/README.md, Abschnitt Markenleitlinien Nr. 5), bleibt es die Textwortmarke. + Eine freigegebene Datei wird ausschließlich hier eingesetzt. +--}} +@props(['compact' => false]) +
class(['wordmark', 'wordmark-compact' => $compact]) }}> + Lara & Felix + Stark im Alltag +
diff --git a/resources/views/components/site/footer.blade.php b/resources/views/components/site/footer.blade.php new file mode 100644 index 0000000..6f790e3 --- /dev/null +++ b/resources/views/components/site/footer.blade.php @@ -0,0 +1,13 @@ +@props(['navigation']) +
+ +
diff --git a/resources/views/components/site/header.blade.php b/resources/views/components/site/header.blade.php new file mode 100644 index 0000000..f0917cf --- /dev/null +++ b/resources/views/components/site/header.blade.php @@ -0,0 +1,18 @@ +@props(['navigation', 'page' => null]) +
+
+ + +
+
diff --git a/resources/views/filament/cms/styles.blade.php b/resources/views/filament/cms/styles.blade.php new file mode 100644 index 0000000..7140f42 --- /dev/null +++ b/resources/views/filament/cms/styles.blade.php @@ -0,0 +1,9 @@ + diff --git a/resources/views/filament/cms/widget-preview.blade.php b/resources/views/filament/cms/widget-preview.blade.php new file mode 100644 index 0000000..d7a29a8 --- /dev/null +++ b/resources/views/filament/cms/widget-preview.blade.php @@ -0,0 +1,22 @@ +{{-- + Blockvorschau im Seiteneditor. Das Widget wird mit derselben Ansicht wie auf der öffentlichen Seite gerendert + und in einem eigenen Dokument angezeigt, damit Website- und Verwaltungsstile sich nicht überlagern. +--}} +@php + $document = '' + .$stylesheets + .'' + .'
'.$html.'
'; +@endphp +@if (trim($html) === '') +

Dieser Abschnitt zeigt öffentlich nichts an. Bitte Inhalte ergänzen.

+@else + +@endif diff --git a/resources/views/layouts/site.blade.php b/resources/views/layouts/site.blade.php index 4b5c4eb..18be3f0 100644 --- a/resources/views/layouts/site.blade.php +++ b/resources/views/layouts/site.blade.php @@ -15,42 +15,13 @@ -
-
-
- Lara & Felix - Stark im Alltag -
- -
-
+
@if (session('status'))

{{ session('status') }}

@endif @yield('content')
-
- -
+ diff --git a/resources/views/public/blocks/call_to_action.blade.php b/resources/views/public/blocks/call_to_action.blade.php deleted file mode 100644 index c56f916..0000000 --- a/resources/views/public/blocks/call_to_action.blade.php +++ /dev/null @@ -1,7 +0,0 @@ -
-

{{ $block['heading'] }}

- @if (filled($block['text'] ?? null)) -

{{ $block['text'] }}

- @endif - {{ $block['label'] }} -
diff --git a/resources/views/public/blocks/cards.blade.php b/resources/views/public/blocks/cards.blade.php deleted file mode 100644 index d0b0e6b..0000000 --- a/resources/views/public/blocks/cards.blade.php +++ /dev/null @@ -1,19 +0,0 @@ - diff --git a/resources/views/public/blocks/faq.blade.php b/resources/views/public/blocks/faq.blade.php deleted file mode 100644 index 0231187..0000000 --- a/resources/views/public/blocks/faq.blade.php +++ /dev/null @@ -1,6 +0,0 @@ -
- @foreach ($block['items'] as $item) -
{{ $item['question'] }}
-
{{ $item['answer'] }}
- @endforeach -
diff --git a/resources/views/public/blocks/heading.blade.php b/resources/views/public/blocks/heading.blade.php deleted file mode 100644 index b39ea6d..0000000 --- a/resources/views/public/blocks/heading.blade.php +++ /dev/null @@ -1,8 +0,0 @@ -@if (! empty($first)) -

{{ $block['heading'] }}

-@else -

{{ $block['heading'] }}

-@endif -@if (filled($block['intro'] ?? null)) -

{{ $block['intro'] }}

-@endif diff --git a/resources/views/public/blocks/image_text.blade.php b/resources/views/public/blocks/image_text.blade.php deleted file mode 100644 index caf6891..0000000 --- a/resources/views/public/blocks/image_text.blade.php +++ /dev/null @@ -1,10 +0,0 @@ -
- @if (filled($block['image'] ?? null)) - {{ $block['alt'] }} - @endif -
- @foreach (preg_split("/\n\s*\n/", trim($block['body'])) as $paragraph) -

{{ $paragraph }}

- @endforeach -
-
diff --git a/resources/views/public/blocks/prose.blade.php b/resources/views/public/blocks/prose.blade.php deleted file mode 100644 index 2961886..0000000 --- a/resources/views/public/blocks/prose.blade.php +++ /dev/null @@ -1,5 +0,0 @@ -
- @foreach (preg_split("/\n\s*\n/", trim($block['body'])) as $paragraph) -

{{ $paragraph }}

- @endforeach -
diff --git a/resources/views/public/page.blade.php b/resources/views/public/page.blade.php index 30f665a..acb61c9 100644 --- a/resources/views/public/page.blade.php +++ b/resources/views/public/page.blade.php @@ -8,15 +8,5 @@ @if ($preview)

Vorschau einer unveröffentlichten Revision. Die öffentliche Seite bleibt unverändert.

@endif - @foreach ($revision->blocks as $block) -
- @include('public.blocks.'.$block['type'], ['block' => $block, 'first' => $loop->first]) -
- @endforeach - @if ($page->path === '/' && ($themes ?? collect())->isNotEmpty()) -
-

Themenbereiche

- @include('public.themes.list', ['themes' => $themes]) -
- @endif + @include($template, ['content' => $content, 'page' => $page, 'themes' => $themes ?? collect()]) @endsection diff --git a/resources/views/public/preview-devices.blade.php b/resources/views/public/preview-devices.blade.php new file mode 100644 index 0000000..dadeee2 --- /dev/null +++ b/resources/views/public/preview-devices.blade.php @@ -0,0 +1,58 @@ + + + + + + + Vorschau {{ $page->path }} · Revision {{ $revision->id }} + + + +
+ Vorschau {{ $page->path }} +

Revision {{ $revision->id }} · {{ $isLive ? 'veröffentlicht' : 'nicht veröffentlicht' }}

+
+ + + +
+

Ohne Rahmen öffnen

+
+
+

Desktop, 1440 px

+
+ +
+
+ + + diff --git a/resources/views/site/templates/standard.blade.php b/resources/views/site/templates/standard.blade.php new file mode 100644 index 0000000..d67b73e --- /dev/null +++ b/resources/views/site/templates/standard.blade.php @@ -0,0 +1,10 @@ +{{-- Seitenvorlage „standard“: Widgets in voller Inhaltsbreite untereinander. --}} +
+ {{ $content }} + @if ($page->path === '/' && $themes->isNotEmpty()) +
+

Themenbereiche

+ @include('public.themes.list', ['themes' => $themes]) +
+ @endif +
diff --git a/resources/views/widgets/call_to_action.blade.php b/resources/views/widgets/call_to_action.blade.php new file mode 100644 index 0000000..107e8ec --- /dev/null +++ b/resources/views/widgets/call_to_action.blade.php @@ -0,0 +1,9 @@ +
+

{{ $data['heading'] ?? '' }}

+ @if (filled($data['text'] ?? null)) +

{{ $data['text'] }}

+ @endif + @if (\App\Domain\Cms\Widgets\Support\SafeUrl::isSafe($data['url'] ?? null)) + {{ $data['label'] ?? '' }} + @endif +
diff --git a/resources/views/widgets/cards.blade.php b/resources/views/widgets/cards.blade.php new file mode 100644 index 0000000..0e5107c --- /dev/null +++ b/resources/views/widgets/cards.blade.php @@ -0,0 +1,27 @@ +@if ($items !== []) + +@endif diff --git a/resources/views/widgets/catalog_cards.blade.php b/resources/views/widgets/catalog_cards.blade.php new file mode 100644 index 0000000..a473871 --- /dev/null +++ b/resources/views/widgets/catalog_cards.blade.php @@ -0,0 +1,39 @@ +@if ($entries !== [] || $context->preview) +
+ @if (filled($data['heading'] ?? null)) +

{{ $data['heading'] }}

+ @endif + @if (filled($data['intro'] ?? null)) +

{{ $data['intro'] }}

+ @endif + @if ($entries === []) +

Noch kein Programm oder Modul gewählt, oder keines ist öffentlich sichtbar. Öffentlich erscheint dieser Abschnitt nicht.

+ @else +
    + @foreach ($entries as $entry) +
  • + @if ($variant !== 'compact') + + @endif +
    +

    {{ $entry->kindLabel }}

    +

    + @if ($entry->url) + {{ $entry->title }} + @else + {{ $entry->title }} + @endif +

    + @if ($variant !== 'compact' && filled($entry->summary)) +

    {{ $entry->summary }}

    + @endif + @unless ($entry->public) +

    Nur in der Redaktionsvorschau sichtbar: Für diese Inhaltsart gibt es noch keine öffentliche Freigabe (öffentliches Profil, ADR-29).

    + @endunless +
    +
  • + @endforeach +
+ @endif +
+@endif diff --git a/resources/views/widgets/faq.blade.php b/resources/views/widgets/faq.blade.php new file mode 100644 index 0000000..435e11d --- /dev/null +++ b/resources/views/widgets/faq.blade.php @@ -0,0 +1,6 @@ +
+ @foreach ($data['items'] ?? [] as $item) +
{{ $item['question'] ?? '' }}
+
{{ $item['answer'] ?? '' }}
+ @endforeach +
diff --git a/resources/views/widgets/heading.blade.php b/resources/views/widgets/heading.blade.php new file mode 100644 index 0000000..68c03f4 --- /dev/null +++ b/resources/views/widgets/heading.blade.php @@ -0,0 +1,8 @@ +@if (! empty($first)) +

{{ $data['heading'] ?? '' }}

+@else +

{{ $data['heading'] ?? '' }}

+@endif +@if (filled($data['intro'] ?? null)) +

{{ $data['intro'] }}

+@endif diff --git a/resources/views/widgets/hero.blade.php b/resources/views/widgets/hero.blade.php new file mode 100644 index 0000000..ddeba34 --- /dev/null +++ b/resources/views/widgets/hero.blade.php @@ -0,0 +1,18 @@ +
+
+ @if (! empty($first)) +

{{ $data['heading'] ?? '' }}

+ @else +

{{ $data['heading'] ?? '' }}

+ @endif + @if (filled($data['text'] ?? null)) +

{{ $data['text'] }}

+ @endif + @if ($action) + {{ $action['label'] }} + @endif +
+ @if ($imageUrl) + {{ $data['alt'] ?? '' }} + @endif +
diff --git a/resources/views/widgets/image_text.blade.php b/resources/views/widgets/image_text.blade.php new file mode 100644 index 0000000..bd0ea01 --- /dev/null +++ b/resources/views/widgets/image_text.blade.php @@ -0,0 +1,15 @@ +
+ @if ($imageUrl) + {{ $data['alt'] ?? '' }} + @endif +
+ @if (filled($data['title'] ?? null)) + @if (! empty($first)) +

{{ $data['title'] }}

+ @else +

{{ $data['title'] }}

+ @endif + @endif +
{!! $body !!}
+
+
diff --git a/resources/views/widgets/prose.blade.php b/resources/views/widgets/prose.blade.php new file mode 100644 index 0000000..5ed6931 --- /dev/null +++ b/resources/views/widgets/prose.blade.php @@ -0,0 +1,7 @@ +@if (filled($data['body'] ?? null)) +
+ @foreach (preg_split("/\n\s*\n/", trim($data['body'])) as $paragraph) +

{{ $paragraph }}

+ @endforeach +
+@endif diff --git a/routes/web.php b/routes/web.php index 2cdb59d..9151f4c 100644 --- a/routes/web.php +++ b/routes/web.php @@ -36,6 +36,14 @@ Route::post('/abmelden', [SessionController::class, 'destroy'])->middleware('auth')->name('logout'); +Route::get('/redaktion/vorschau/{revision}', [PageController::class, 'preview']) + ->middleware('auth:staff') + ->whereNumber('revision') + ->name('pages.preview'); +Route::get('/redaktion/vorschau/{revision}/geraete', [PageController::class, 'devices']) + ->middleware('auth:staff') + ->whereNumber('revision') + ->name('pages.preview.devices'); Route::get('/redaktion/aufbau/{composition}/entwurf', [EditorialPreviewController::class, 'draft']) ->middleware('auth:staff') ->name('editorial.draft-preview'); @@ -69,7 +77,6 @@ Route::post('/email/erneut', [EmailVerificationController::class, 'send']) ->middleware('throttle:6,1') ->name('verification.send'); - Route::get('/redaktion/vorschau/{revision}', [PageController::class, 'preview'])->name('pages.preview'); }); Route::middleware(['auth', 'verified'])->prefix('bereich')->name('member.')->group(function () { diff --git a/tests/Feature/CmsEditorTest.php b/tests/Feature/CmsEditorTest.php new file mode 100644 index 0000000..ce7ea56 --- /dev/null +++ b/tests/Feature/CmsEditorTest.php @@ -0,0 +1,274 @@ +composition('Programm Abstand', 'programm'); + $editor = $this->editor(); + + Livewire::actingAs($editor, 'staff') + ->test(CreatePage::class) + ->fillForm([ + 'path' => '/themen-test', + 'seo_title' => 'Themenseite', + 'blocks' => $this->keyed([ + ['type' => 'hero', 'data' => ['variant' => 'highlight', 'data' => ['heading' => 'Stark im Alltag', 'text' => 'Einstieg']]], + ['type' => 'image_text', 'data' => ['variant' => 'image_right', 'data' => ['title' => 'Worum es geht', 'body' => '

Text mit Betonung

'], 'refs' => []]], + ['type' => 'cards', 'data' => ['variant' => 'compact', 'data' => ['items' => $this->keyed([['title' => 'Prävention', 'url' => '/praevention']])]]], + ['type' => 'catalog_cards', 'data' => ['variant' => 'standard', 'data' => ['heading' => 'Programme'], 'refs' => ['items' => $this->keyed([['type' => 'composition', 'id' => $program->composition_id]])]]], + ]), + ]) + ->call('create') + ->assertHasNoFormErrors(); + + $page = Page::query()->where('path', '/themen-test')->firstOrFail(); + $blocks = $page->latestRevision->blocks; + + $this->assertNull($page->published_revision_id); + $this->assertSame(['hero', 'image_text', 'cards', 'catalog_cards'], array_column($blocks, 'type')); + $this->assertSame(['highlight', 'image_right', 'compact', 'standard'], array_column($blocks, 'variant')); + $this->assertSame([2], array_values(array_unique([$blocks[1]['v']]))); + $this->assertStringContainsString('Betonung', $blocks[1]['data']['body']); + $this->assertSame([['title' => 'Prävention', 'text' => null, 'url' => '/praevention', 'image' => null]], $blocks[2]['data']['items']); + $this->assertSame([['type' => 'composition', 'id' => $program->composition_id]], $blocks[3]['refs']['items']); + $this->get('/themen-test')->assertNotFound(); + } + + public function test_existing_page_opens_in_the_editor_and_saves_without_changing_the_live_page(): void + { + $page = Page::query()->where('path', '/')->firstOrFail(); + $live = $page->published_revision_id; + $before = $this->mainText($this->get('/')->getContent()); + + $component = Livewire::actingAs($this->editor(), 'staff') + ->test(EditPage::class, ['record' => $page->id]); + + $state = $component->get('data.blocks'); + $this->assertSame(['heading', 'prose', 'cards', 'call_to_action'], array_column(array_values($state), 'type')); + + $component->call('save')->assertHasNoFormErrors(); + + $page->refresh(); + $this->assertSame($live, $page->published_revision_id); + $this->assertNotSame($live, $page->latestRevision->id); + $this->assertSame(['heading', 'prose', 'cards', 'call_to_action'], array_column($page->latestRevision->blocks, 'type')); + $this->assertSame($before, $this->mainText($this->get('/')->getContent())); + + Livewire::actingAs($this->editor(), 'staff') + ->test(EditPage::class, ['record' => $page->id]) + ->callAction('publish'); + + $this->assertSame( + trim(file_get_contents(base_path('tests/Fixtures/legacy-pages/home.txt'))), + $this->mainText($this->get('/')->getContent()), + 'Nach dem Speichern im neuen Format zeigt die Seite denselben Text.', + ); + } + + public function test_editor_reorders_and_duplicates_sections(): void + { + $page = Page::query()->where('path', '/')->firstOrFail(); + $component = Livewire::actingAs($this->editor(), 'staff')->test(EditPage::class, ['record' => $page->id]); + + $state = $component->get('data.blocks'); + $keys = array_keys($state); + $reordered = [$keys[3] => $state[$keys[3]], $keys[0] => $state[$keys[0]], $keys[1] => $state[$keys[1]], $keys[2] => $state[$keys[2]]]; + $copy = $state[$keys[1]]; + $reordered[(string) Str::uuid()] = $copy; + + $component->set('data.blocks', $reordered)->call('save')->assertHasNoFormErrors(); + + $blocks = $page->fresh()->latestRevision->blocks; + $this->assertSame(['call_to_action', 'heading', 'prose', 'cards', 'prose'], array_column($blocks, 'type')); + $this->assertCount(5, array_unique(array_column($blocks, 'id')), 'Ein dupliziertes Widget erhält eine eigene Kennung.'); + } + + public function test_unsafe_link_is_reported_at_the_section_and_nothing_is_saved(): void + { + $page = Page::query()->where('path', '/')->firstOrFail(); + $revisions = $page->revisions()->count(); + + $component = Livewire::actingAs($this->editor(), 'staff')->test(EditPage::class, ['record' => $page->id]); + $key = array_keys($component->get('data.blocks'))[3]; + + $component->set("data.blocks.$key.data.data.url", 'javascript:alert(1)') + ->call('save') + ->assertHasErrors(["data.blocks.$key.data.data.url"]); + + $this->assertSame($revisions, $page->revisions()->count()); + } + + public function test_invalid_or_taken_paths_are_shown_at_the_path_field(): void + { + Livewire::actingAs($this->editor(), 'staff') + ->test(CreatePage::class) + ->fillForm(['path' => '/praevention', 'blocks' => []]) + ->call('create') + ->assertHasErrors(['data.path']); + + Livewire::actingAs($this->editor(), 'staff') + ->test(CreatePage::class) + ->fillForm(['path' => 'C:/Program Files/x', 'blocks' => []]) + ->call('create') + ->assertHasErrors(['data.path']); + + $this->assertSame(1, Page::query()->where('path', '/praevention')->count()); + } + + public function test_block_preview_uses_the_public_widget_view_with_unsaved_state(): void + { + $html = WidgetEditor::renderPreview('image_text', [ + 'variant' => 'image_right', + 'data' => [ + 'title' => 'Ungespeichert', + 'body' => ['type' => 'doc', 'content' => [['type' => 'paragraph', 'content' => [['type' => 'text', 'text' => 'Vorschautext']]]]], + ], + 'refs' => ['image' => null, '_upload' => []], + ]); + + $this->assertStringContainsString('image-text image-text-right', $html); + $this->assertStringContainsString('

Ungespeichert

', $html); + $this->assertStringContainsString('Vorschautext', $html); + + $cards = WidgetEditor::renderPreview('cards', [ + 'variant' => 'standard', + 'data' => ['items' => [(string) Str::uuid() => ['title' => 'Karte A'], (string) Str::uuid() => ['title' => 'Karte B']]], + ]); + $this->assertStringContainsString('Karte A', $cards); + $this->assertStringContainsString('Karte B', $cards); + } + + public function test_editor_offers_every_registered_widget_with_description(): void + { + $page = Page::query()->where('path', '/')->firstOrFail(); + + Livewire::actingAs($this->editor(), 'staff') + ->test(EditPage::class, ['record' => $page->id]) + ->assertSee('Einstieg (Hero)') + ->assertSee('Programm- und Modulkarten') + ->assertSee('Titel und Beschreibung kommen automatisch aus den Fachdaten') + ->assertSee('Entwurf speichern'); + } + + public function test_preview_with_device_widths_is_only_available_to_staff(): void + { + $revision = Page::query()->where('path', '/')->firstOrFail()->latestRevision; + + $this->get(route('pages.preview.devices', $revision))->assertRedirect(); + $this->actingAs(User::factory()->create())->get(route('pages.preview', $revision))->assertRedirect(); + $this->actingAs(User::factory()->create(), 'staff')->get(route('pages.preview', $revision))->assertForbidden(); + auth('web')->logout(); + + $this->actingAs($this->editor(), 'staff') + ->get(route('pages.preview.devices', $revision)) + ->assertOk() + ->assertSee('data-width="390"', false) + ->assertSee('data-width="768"', false) + ->assertSee('data-width="1440"', false) + ->assertSee(route('pages.preview', $revision), false); + + $this->actingAs($this->editor(), 'staff') + ->get(route('pages.preview', $revision)) + ->assertOk() + ->assertSee('Vorschau einer unveröffentlichten Revision') + ->assertSee('Registrieren') + ->assertDontSee('Mitgliederbereich', false); + } + + public function test_navigation_items_can_be_edited_hidden_reordered_and_removed(): void + { + $editor = $this->editor(); + $start = NavigationItem::query()->where('label', 'Start')->firstOrFail(); + $about = NavigationItem::query()->where('label', 'Über das Projekt')->firstOrFail(); + + Livewire::actingAs($editor, 'staff') + ->test(ManageNavigationItems::class) + ->assertCanSeeTableRecords([$start, $about]) + ->callAction(TestAction::make('edit')->table($about), ['label' => 'Über uns']) + ->assertHasNoFormErrors() + ->callAction(TestAction::make('toggleVisibility')->table($start)); + + $this->assertSame('Über uns', $about->fresh()->label); + $this->assertFalse($start->fresh()->is_visible); + $this->get('/praevention')->assertSee('Über uns')->assertDontSee('>Start<', false); + + $order = NavigationItem::query()->orderByDesc('sort_order')->pluck('id')->map(fn ($id) => (string) $id)->all(); + Livewire::actingAs($editor, 'staff')->test(ManageNavigationItems::class)->call('reorderTable', $order); + $this->assertSame((int) $order[0], NavigationItem::query()->orderBy('sort_order')->first()->id); + + Livewire::actingAs($editor, 'staff') + ->test(ManageNavigationItems::class) + ->callAction(TestAction::make('delete')->table($about)); + $this->assertNull($about->fresh()); + $this->assertNotNull(Page::query()->where('path', '/ueber')->first(), 'Die Seite bleibt bestehen.'); + } + + public function test_navigation_rejects_script_addresses(): void + { + Livewire::actingAs($this->editor(), 'staff') + ->test(ManageNavigationItems::class) + ->callAction('create', ['label' => 'Böse', 'placement' => 'header', 'url' => 'javascript:alert(1)', 'sort_order' => 9, 'is_visible' => true]) + ->assertHasFormErrors(['url']); + + NavigationItem::query()->create(['label' => 'Alt', 'url' => 'javascript:alert(1)', 'placement' => 'footer', 'sort_order' => 99]); + $this->get('/praevention')->assertDontSee('javascript:alert(1)', false); + } + + private function editor(): User + { + $editor = User::factory()->redakteur()->create(); + $editor->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP'); + + return $editor; + } + + /** + * @param list> $items + * @return array> + */ + private function keyed(array $items): array + { + $keyed = []; + foreach ($items as $item) { + $keyed[(string) Str::uuid()] = $item; + } + + return $keyed; + } + + private function mainText(string $html): string + { + preg_match('#]*>(.*)#s', $html, $match); + $text = html_entity_decode(strip_tags(str_replace('<', ' <', $match[1] ?? '')), ENT_QUOTES | ENT_HTML5, 'UTF-8'); + + return trim(preg_replace('/\s+/u', ' ', $text)); + } +} diff --git a/tests/Feature/CmsWidgetRenderingTest.php b/tests/Feature/CmsWidgetRenderingTest.php new file mode 100644 index 0000000..76b4c54 --- /dev/null +++ b/tests/Feature/CmsWidgetRenderingTest.php @@ -0,0 +1,237 @@ + 'home', '/praevention' => 'praevention', '/materialien' => 'materialien', '/angebote' => 'angebote', '/trainer' => 'trainer', '/ueber' => 'ueber', '/impressum' => 'impressum', '/datenschutz' => 'datenschutz']; + + foreach ($pages as $path => $fixture) { + $html = $this->get($path)->assertOk()->getContent(); + + $this->assertSame( + trim(file_get_contents(base_path("tests/Fixtures/legacy-pages/$fixture.txt"))), + $this->mainText($html), + "Abweichung auf $path", + ); + } + } + + public function test_legacy_revisions_stored_in_the_flat_format_still_render(): void + { + $page = Page::query()->create(['path' => '/alt']); + $revision = $page->revisions()->create([ + 'blocks' => [ + ['type' => 'heading', 'heading' => 'Alte Seite', 'intro' => 'Einleitung'], + ['type' => 'image_text', 'image' => 'cms/alt.jpg', 'alt' => 'Altes Bild', 'body' => "Absatz eins.\n\nAbsatz ."], + ['type' => 'faq', 'items' => [['question' => 'Frage?', 'answer' => 'Antwort.']]], + ['type' => 'cards', 'items' => [['title' => 'Karte', 'text' => 'Text', 'url' => '/praevention']]], + ['type' => 'call_to_action', 'heading' => 'Los', 'text' => null, 'label' => 'Anmelden', 'url' => '/anmelden'], + ], + ]); + app(PageService::class)->publish($page, $revision); + + $this->get('/alt') + ->assertOk() + ->assertSee('Alte Seite', false) + ->assertSee('

Alte Seite

', false) + ->assertSee('alt="Altes Bild"', false) + ->assertSee('

Absatz eins.

Absatz <zwei>.

', false) + ->assertSee('
Frage?
', false) + ->assertSee('href="/praevention"', false) + ->assertSee('href="/anmelden"', false); + + $this->assertSame('heading', $revision->fresh()->blocks[0]['type']); + $this->assertArrayNotHasKey('v', $revision->fresh()->blocks[0], 'Die gespeicherte Altrevision bleibt unverändert.'); + } + + public function test_restoring_a_legacy_revision_keeps_its_stored_blocks(): void + { + $page = Page::query()->where('path', '/')->firstOrFail(); + $legacy = $page->publishedRevision; + $service = app(PageService::class); + + $service->saveRevision($page, [['type' => 'heading', 'v' => 1, 'data' => ['heading' => 'Neu']]], null, null, null); + $restored = $service->restore($page, $legacy, null); + + $this->assertSame($legacy->blocks, $restored->blocks); + } + + public function test_new_revisions_are_stored_as_widget_envelopes(): void + { + $page = Page::query()->create(['path' => '/neu']); + + $revision = app(PageService::class)->saveRevision($page, [ + ['type' => 'prose', 'body' => 'Altes Eingabeformat'], + ['type' => 'hero', 'v' => 1, 'variant' => 'highlight', 'data' => ['heading' => 'Einstieg']], + ], null, null, null); + + $this->assertSame(['id', 'type', 'v', 'variant', 'settings', 'data', 'refs'], array_keys($revision->blocks[0])); + $this->assertSame('prose', $revision->blocks[0]['type']); + $this->assertSame(['body' => 'Altes Eingabeformat'], $revision->blocks[0]['data']); + $this->assertSame('highlight', $revision->blocks[1]['variant']); + $this->assertNull($page->fresh()->published_revision_id, 'Speichern veröffentlicht nicht.'); + } + + public function test_reference_widgets_render_their_variants(): void + { + $page = Page::query()->create(['path' => '/varianten']); + $revision = app(PageService::class)->saveRevision($page, [ + ['type' => 'hero', 'v' => 1, 'variant' => 'highlight', 'data' => ['heading' => 'Stark im Alltag', 'text' => 'Einstieg', 'cta_label' => 'Mehr', 'cta_url' => '/praevention']], + ['type' => 'image_text', 'v' => 2, 'variant' => 'image_right', 'data' => ['title' => 'Bild rechts', 'body' => '

Text betont

', 'alt' => 'Beschreibung'], 'refs' => ['image' => 'cms/beispiel.jpg']], + ['type' => 'cards', 'v' => 1, 'variant' => 'compact', 'data' => ['items' => [['title' => 'Eins', 'url' => '/a'], ['title' => 'Zwei']]]], + ], null, null, null); + app(PageService::class)->publish($page, $revision); + + $this->get('/varianten') + ->assertOk() + ->assertSee('hero hero-highlight', false) + ->assertSee('

Stark im Alltag

', false) + ->assertSee('class="button" href="/praevention"', false) + ->assertSee('image-text image-text-right', false) + ->assertSee('

Bild rechts

', false) + ->assertSee('betont', false) + ->assertSee(route('media.public', ['path' => 'cms/beispiel.jpg']), false) + ->assertSee('cards cards-compact', false); + } + + public function test_media_of_any_widget_are_published_through_the_queue(): void + { + Queue::fake(); + $page = Page::query()->create(['path' => '/medien']); + + app(PageService::class)->saveRevision($page, [ + ['type' => 'hero', 'v' => 1, 'data' => ['heading' => 'A', 'alt' => 'Bild'], 'refs' => ['image' => 'cms/hero.jpg']], + ['type' => 'cards', 'v' => 1, 'data' => ['items' => [['title' => 'K', 'image' => 'cms/karte.jpg']]]], + ], null, null, null); + + Queue::assertPushed(PublishPublicMedia::class, fn ($job) => $job->path === 'cms/hero.jpg'); + Queue::assertPushed(PublishPublicMedia::class, fn ($job) => $job->path === 'cms/karte.jpg'); + } + + public function test_catalog_cards_show_released_programs_from_the_master_data_only(): void + { + $program = $this->composition('Programm Abstand', 'programm', summary: 'Kurzbeschreibung aus den Fachdaten'); + $module = $this->composition('Modul Nein sagen', 'modul'); + $page = Page::query()->create(['path' => '/thema']); + + $revision = app(PageService::class)->saveRevision($page, [[ + 'type' => 'catalog_cards', + 'v' => 1, + 'data' => ['heading' => 'Passende Angebote'], + 'refs' => ['items' => [ + ['type' => 'composition', 'id' => $module->composition_id], + ['type' => 'composition', 'id' => $program->composition_id], + ]], + ]], null, null, null); + app(PageService::class)->publish($page, $revision); + + $this->assertSame( + ['items' => [['type' => 'composition', 'id' => $module->composition_id], ['type' => 'composition', 'id' => $program->composition_id]]], + $revision->blocks[0]['refs'], + ); + $this->assertStringNotContainsString('Programm Abstand', json_encode($revision->blocks), 'Keine Stammdaten im CMS.'); + + $this->get('/thema') + ->assertOk() + ->assertSee('Passende Angebote') + ->assertSee('Programm Abstand') + ->assertSee('Kurzbeschreibung aus den Fachdaten') + ->assertSee(route('public.program', $program->composition_id), false) + ->assertDontSee('Modul Nein sagen') + ->assertDontSee('Redaktionsvorschau'); + + $program->composition->update(['display_title' => 'Programm „Abstand halten“']); + $this->get('/thema')->assertSee('Programm „Abstand halten“'); + } + + public function test_catalog_cards_show_modules_only_in_the_protected_preview(): void + { + $module = $this->composition('Modul Nein sagen', 'modul'); + $page = Page::query()->create(['path' => '/modulseite']); + $revision = app(PageService::class)->saveRevision($page, [ + ['type' => 'heading', 'v' => 1, 'data' => ['heading' => 'Module']], + ['type' => 'catalog_cards', 'v' => 1, 'data' => [], 'refs' => ['items' => [['type' => 'composition', 'id' => $module->composition_id]]]], + ], null, null, null); + app(PageService::class)->publish($page, $revision); + + $this->get('/modulseite')->assertOk()->assertDontSee('Modul Nein sagen')->assertDontSee('catalog-cards'); + + $editor = User::factory()->redakteur()->create(); + $this->actingAs($editor, 'staff') + ->get(route('pages.preview', $revision)) + ->assertOk() + ->assertSee('Modul Nein sagen') + ->assertSee('Nur in der Redaktionsvorschau sichtbar'); + } + + public function test_revoking_the_display_release_removes_the_card_without_editing_the_page(): void + { + $program = $this->composition('Programm Rückzug', 'programm'); + $page = Page::query()->create(['path' => '/rueckzug']); + $revision = app(PageService::class)->saveRevision($page, [ + ['type' => 'heading', 'v' => 1, 'data' => ['heading' => 'Rückzug']], + ['type' => 'catalog_cards', 'v' => 1, 'refs' => ['items' => [['type' => 'composition', 'id' => $program->composition_id]]]], + ], null, null, null); + app(PageService::class)->publish($page, $revision); + $this->get('/rueckzug')->assertSee('Programm Rückzug'); + + $program->displayEvents()->update(['occurred_at' => now()->subMinute()]); + app(CompositionDisplayRelease::class)->revoke($program, User::factory()->create()); + + $this->get('/rueckzug')->assertOk()->assertDontSee('Programm Rückzug'); + } + + public function test_unreleased_or_foreign_objects_cannot_be_referenced(): void + { + $draft = $this->composition('Programm Entwurf', 'programm', released: false); + $page = Page::query()->create(['path' => '/entwurf']); + + $this->expectException(ValidationException::class); + + app(PageService::class)->saveRevision($page, [ + ['type' => 'catalog_cards', 'v' => 1, 'refs' => ['items' => [['type' => 'composition', 'id' => $draft->composition_id]]]], + ], null, null, null); + } + + public function test_public_program_list_uses_the_same_public_rule(): void + { + $this->composition('Programm Öffentlich', 'programm'); + $this->composition('Programm Intern', 'programm', released: false); + $this->composition('Modul Freigegeben', 'modul'); + + $this->get('/programme') + ->assertOk() + ->assertSee('Programm Öffentlich') + ->assertDontSee('Programm Intern') + ->assertDontSee('Modul Freigegeben'); + } + + private function mainText(string $html): string + { + preg_match('#]*>(.*)#s', $html, $match); + $text = html_entity_decode(strip_tags(str_replace('<', ' <', $match[1] ?? '')), ENT_QUOTES | ENT_HTML5, 'UTF-8'); + + return trim(preg_replace('/\s+/u', ' ', $text)); + } +} diff --git a/tests/Fixtures/legacy-pages/angebote.txt b/tests/Fixtures/legacy-pages/angebote.txt new file mode 100644 index 0000000..604a22e --- /dev/null +++ b/tests/Fixtures/legacy-pages/angebote.txt @@ -0,0 +1 @@ +Angebote Umfang, Rechte und Preise eines Angebots kommen aus dem Katalog. Sie werden hier nicht als freier Text ersetzt. Es sind noch keine Angebote veröffentlicht. Sobald ein Angebot aktiv ist, zeigt diese Seite seinen Umfang aus dem gespeicherten Stand. diff --git a/tests/Fixtures/legacy-pages/datenschutz.txt b/tests/Fixtures/legacy-pages/datenschutz.txt new file mode 100644 index 0000000..7240d9e --- /dev/null +++ b/tests/Fixtures/legacy-pages/datenschutz.txt @@ -0,0 +1 @@ +Datenschutz Die Datenschutzerklärung wird hier gepflegt und ist noch nicht eingesetzt. Profilangaben sind standardmäßig nicht öffentlich. Geschützte Medien werden nicht über einen öffentlichen Dateipfad ausgeliefert. diff --git a/tests/Fixtures/legacy-pages/home.txt b/tests/Fixtures/legacy-pages/home.txt new file mode 100644 index 0000000..4cb7f29 --- /dev/null +++ b/tests/Fixtures/legacy-pages/home.txt @@ -0,0 +1 @@ +Stark im Alltag Lara & Felix ist eine Plattform für Gewaltprävention, Selbstbehauptung und gewaltpräventive Bildungsarbeit. Sie unterstützt Erwachsene, die solche Angebote vorbereiten und durchführen. Die Lerninhalte richten sich unter anderem an Kinder. Kinder sind keine Benutzerinnen und Benutzer der Plattform und brauchen kein eigenes Konto. Die Filme „Lara & Felix“ sind die erste Produktreihe. Übungen, Programme und weitere Materialien lassen sich in derselben Struktur verwalten, ohne die Plattform auf eine einzelne Episode festzulegen. Prävention Worum es in der Bildungsarbeit geht. Materialien Filme und Begleitmaterial, sobald sie veröffentlicht sind. Für Trainer und Einrichtungen Wer die Plattform nutzt. Mitgliederbereich Nach der Anmeldung sehen Sie die Materialien, für die eine Berechtigung vorliegt. Anmelden diff --git a/tests/Fixtures/legacy-pages/impressum.txt b/tests/Fixtures/legacy-pages/impressum.txt new file mode 100644 index 0000000..458d2d4 --- /dev/null +++ b/tests/Fixtures/legacy-pages/impressum.txt @@ -0,0 +1 @@ +Impressum Die gesetzlich erforderlichen Angaben werden hier veröffentlicht, sobald sie feststehen. Diese Seite ist redaktionell pflegbar. Sie enthält noch keine Angaben zu einer verantwortlichen Stelle. diff --git a/tests/Fixtures/legacy-pages/materialien.txt b/tests/Fixtures/legacy-pages/materialien.txt new file mode 100644 index 0000000..4796065 --- /dev/null +++ b/tests/Fixtures/legacy-pages/materialien.txt @@ -0,0 +1 @@ +Filme und Lernmaterialien Hier erscheinen veröffentlichte Inhalte aus dem Katalog. Die Seite kopiert keine Produkttexte und nennt keine Preise. Solange noch kein Lizenzartikel veröffentlicht ist, bleibt diese Übersicht leer. Dieselbe Stelle zeigt später Filme, Übungen und Begleitmaterial aus den maßgeblichen Datensätzen. diff --git a/tests/Fixtures/legacy-pages/praevention.txt b/tests/Fixtures/legacy-pages/praevention.txt new file mode 100644 index 0000000..52ee89b --- /dev/null +++ b/tests/Fixtures/legacy-pages/praevention.txt @@ -0,0 +1 @@ +Prävention im Alltag Die Plattform stellt Materialien bereit, mit denen Trainerinnen, Trainer und pädagogische Fachkräfte Präventionsangebote durchführen. Es geht um Selbstbehauptung, das Erkennen von Grenzverletzungen und um Handlungsfähigkeit in konkreten Situationen. Die Durchführung bleibt bei den Erwachsenen vor Ort. Eine Entscheidungspause in einem Film ist eine Markierung für den Präsenzkurs. Daraus wird kein digitales Quiz und keine eigenständige Lernanwendung für Kinder. diff --git a/tests/Fixtures/legacy-pages/trainer.txt b/tests/Fixtures/legacy-pages/trainer.txt new file mode 100644 index 0000000..4db8976 --- /dev/null +++ b/tests/Fixtures/legacy-pages/trainer.txt @@ -0,0 +1 @@ +Für Trainer und Einrichtungen Die Plattform ist für Erwachsene, die geeignete Präventionsangebote durchführen. Dazu gehören Gewaltschutztrainer, Trainer und Übungsleiter, pädagogische Fachkräfte sowie Vereine und Bildungseinrichtungen. Ein Konto allein öffnet keine Materialien. Sichtbar wird, was eine konkrete Berechtigung erlaubt. Organisationen können später eigene Lizenzen halten. Eine persönliche Freischaltung ist keine Organisationslizenz. diff --git a/tests/Fixtures/legacy-pages/ueber.txt b/tests/Fixtures/legacy-pages/ueber.txt new file mode 100644 index 0000000..1e87c10 --- /dev/null +++ b/tests/Fixtures/legacy-pages/ueber.txt @@ -0,0 +1 @@ +Über das Projekt Lara & Felix – Stark im Alltag ist eine eigenständige Plattform für Gewaltprävention, Selbstbehauptung und gewaltpräventive Bildungsarbeit. Die erste Produktreihe sind die vorhandenen Filme. Das Fachmodell bleibt offen für weitere Medienarten, Übungen und Programme. diff --git a/tests/Support/BuildsCatalog.php b/tests/Support/BuildsCatalog.php new file mode 100644 index 0000000..f3bc7c7 --- /dev/null +++ b/tests/Support/BuildsCatalog.php @@ -0,0 +1,36 @@ +where('slug', $kind)->firstOrFail()->id; + + $version = $content->publishComposition( + tap($content->createComposition($designation), function ($composition) use ($kindId, $summary): void { + $composition->editorial_content_kind_id = $kindId; + $composition->summary = $summary; + $composition->save(); + }), + [['role' => 'Text', 'target' => $content->publishElementVersion($content->createElement('text', 'text', $designation.' Blatt'), 'Inhalt')]], + ); + + if ($released) { + app(CompositionDisplayRelease::class)->release($version, User::factory()->create()); + } + + return $version; + } +} diff --git a/tests/Unit/BlockRegistryTest.php b/tests/Unit/BlockRegistryTest.php deleted file mode 100644 index e9dbab8..0000000 --- a/tests/Unit/BlockRegistryTest.php +++ /dev/null @@ -1,33 +0,0 @@ -expectException(ValidationException::class); - - app(BlockRegistry::class)->normalize([ - ['type' => 'image_text', 'body' => 'Text', 'image' => 'cms/bild.jpg'], - ]); - } - - public function test_action_links_reject_script_urls(): void - { - $this->expectException(ValidationException::class); - - app(BlockRegistry::class)->normalize([ - [ - 'type' => 'call_to_action', - 'heading' => 'Weiter', - 'label' => 'Öffnen', - 'url' => 'javascript:alert(1)', - ], - ]); - } -} diff --git a/tests/Unit/WidgetRegistryTest.php b/tests/Unit/WidgetRegistryTest.php new file mode 100644 index 0000000..d34a6a3 --- /dev/null +++ b/tests/Unit/WidgetRegistryTest.php @@ -0,0 +1,318 @@ +registry()->all(); + + $this->assertSame( + ['hero', 'heading', 'prose', 'image_text', 'cards', 'catalog_cards', 'call_to_action', 'faq'], + array_keys($types), + ); + + foreach ($types as $key => $type) { + $this->assertSame($key, $type->key()); + $this->assertNotSame('', $type->label()); + $this->assertNotSame('', $type->description()); + $this->assertGreaterThanOrEqual(1, $type->version()); + $this->assertNotEmpty($type->variants()); + $this->assertArrayHasKey($type->defaultVariant(), $type->variants()); + $this->assertNotEmpty($type->dataRules()); + $this->assertNotEmpty($type->editorSchema()); + $this->assertTrue(view()->exists($type->view()), "Ansicht für $key fehlt"); + } + } + + public function test_reference_widgets_offer_at_least_two_variants(): void + { + foreach (['hero', 'image_text', 'cards', 'catalog_cards'] as $key) { + $this->assertGreaterThanOrEqual(2, count($this->registry()->get($key)->variants()), $key); + } + + $this->assertSame(['image_left', 'image_right'], array_keys($this->registry()->get('image_text')->variants())); + } + + public function test_registration_rejects_duplicate_and_invalid_keys(): void + { + $registry = new WidgetRegistry([$this->customWidget('teaser')]); + + $this->expectException(InvalidArgumentException::class); + $registry->register($this->customWidget('teaser')); + } + + public function test_registration_rejects_keys_that_are_not_stable_identifiers(): void + { + $this->expectException(InvalidArgumentException::class); + + new WidgetRegistry([$this->customWidget('Teaser Box')]); + } + + public function test_a_new_widget_type_works_through_the_contract_alone(): void + { + $registry = new WidgetRegistry([$this->customWidget('teaser')]); + $this->app->instance(WidgetRegistry::class, $registry); + + $stored = $registry->normalize([ + ['type' => 'teaser', 'v' => 1, 'variant' => 'wide', 'data' => ['heading' => 'Neu']], + ]); + + $this->assertSame('teaser', $stored[0]['type']); + $this->assertSame('wide', $stored[0]['variant']); + $this->assertSame(['heading' => 'Neu'], $stored[0]['data']); + + $html = app(WidgetRenderer::class)->renderAll($stored, RenderContext::publicPage())->toHtml(); + $this->assertStringContainsString('

Neu

', $html); + $this->assertStringContainsString('widget-variant-wide', $html); + + $block = WidgetEditor::block($registry->get('teaser')); + $this->assertSame('teaser', $block->getName()); + $this->assertSame('Teaser · Breit – Neu', (string) $block->getLabel(['variant' => 'wide', 'data' => ['heading' => 'Neu']])); + } + + public function test_unknown_type_and_unregistered_variant_are_rejected(): void + { + try { + $this->registry()->normalize([['type' => 'html', 'v' => 1, 'data' => ['markup' => '']]]); + $this->fail('Unbekannte Art wurde angenommen.'); + } catch (ValidationException $exception) { + $this->assertArrayHasKey('blocks.0.type', $exception->errors()); + } + + try { + $this->registry()->normalize([['type' => 'hero', 'v' => 1, 'variant' => 'gross-und-bunt', 'data' => ['heading' => 'X']]]); + $this->fail('Unbekannte Variante wurde angenommen.'); + } catch (ValidationException $exception) { + $this->assertArrayHasKey('blocks.0.variant', $exception->errors()); + } + } + + public function test_free_settings_are_rejected(): void + { + $this->expectException(ValidationException::class); + + $this->registry()->normalize([ + ['type' => 'heading', 'v' => 1, 'settings' => ['class' => 'bg-red-500'], 'data' => ['heading' => 'X']], + ]); + } + + public function test_image_text_requires_an_alternative_text_when_an_image_is_set(): void + { + try { + $this->registry()->normalize([ + ['type' => 'image_text', 'v' => 2, 'data' => ['body' => '

Text

'], 'refs' => ['image' => 'cms/bild.jpg']], + ]); + $this->fail('Bild ohne Alternativtext wurde angenommen.'); + } catch (ValidationException $exception) { + $this->assertArrayHasKey('blocks.0.data.alt', $exception->errors()); + } + + $stored = $this->registry()->normalize([ + ['type' => 'image_text', 'v' => 2, 'data' => ['body' => '

Ohne Bild

'], 'refs' => []], + ]); + $this->assertNull($stored[0]['refs']['image']); + } + + public function test_links_reject_script_urls_in_every_widget(): void + { + $cases = [ + ['type' => 'call_to_action', 'heading' => 'Weiter', 'label' => 'Öffnen', 'url' => 'javascript:alert(1)'], + ['type' => 'cards', 'v' => 1, 'data' => ['items' => [['title' => 'A', 'url' => 'javascript:alert(1)']]]], + ['type' => 'hero', 'v' => 1, 'data' => ['heading' => 'A', 'cta_label' => 'Los', 'cta_url' => '//fremd.example/x']], + ]; + + foreach ($cases as $case) { + try { + $this->registry()->normalize([$case]); + $this->fail('Unsichere Adresse wurde angenommen: '.$case['type']); + } catch (ValidationException) { + $this->addToAssertionCount(1); + } + } + } + + public function test_images_must_come_from_the_public_website_area(): void + { + $this->expectException(ValidationException::class); + + $this->registry()->normalize([ + ['type' => 'hero', 'v' => 1, 'data' => ['heading' => 'A', 'alt' => 'Bild'], 'refs' => ['image' => 'bibliothek/geschuetzt.jpg']], + ]); + } + + public function test_formatted_text_is_sanitized_when_saved(): void + { + $stored = $this->registry()->normalize([[ + 'type' => 'image_text', + 'v' => 2, + 'data' => ['body' => '

Hallo Welt böse gut

'], + ]]); + + $body = $stored[0]['data']['body']; + $this->assertStringNotContainsString('script', $body); + $this->assertStringNotContainsString('onclick', $body); + $this->assertStringNotContainsString('javascript:', $body); + $this->assertStringNotContainsString('iframe', $body); + $this->assertStringContainsString('Welt', $body); + $this->assertStringContainsString('href="/praevention"', $body); + } + + public function test_legacy_blocks_are_read_as_version_one_envelopes(): void + { + $widget = $this->registry()->upcast(['type' => 'heading', 'heading' => 'Alt', 'intro' => 'Einleitung']); + + $this->assertSame([ + 'id' => null, + 'type' => 'heading', + 'v' => 1, + 'variant' => 'standard', + 'settings' => [], + 'data' => ['heading' => 'Alt', 'intro' => 'Einleitung'], + 'refs' => [], + ], $widget); + } + + public function test_legacy_image_text_is_upgraded_to_version_two_on_read(): void + { + $legacy = ['type' => 'image_text', 'image' => 'cms/alt.jpg', 'alt' => 'Kinder im Kreis', 'body' => "Erster Absatz & mehr.\n\nZweiter ."]; + + $widget = $this->registry()->upcast($legacy); + + $this->assertSame(2, $widget['v']); + $this->assertSame('image_left', $widget['variant']); + $this->assertSame(['image' => 'cms/alt.jpg'], $widget['refs']); + $this->assertSame('Kinder im Kreis', $widget['data']['alt']); + $this->assertNull($widget['data']['title']); + $this->assertSame('

Erster Absatz & mehr.

Zweiter <Absatz>.

', $widget['data']['body']); + } + + public function test_stored_version_one_envelope_is_upgraded_as_well(): void + { + $widget = $this->registry()->upcast([ + 'id' => 'abc', 'type' => 'image_text', 'v' => 1, 'variant' => 'standard', + 'data' => ['image' => null, 'alt' => 'x', 'body' => 'Nur Text'], 'refs' => [], + ]); + + $this->assertSame(2, $widget['v']); + $this->assertSame('abc', $widget['id']); + $this->assertSame('image_left', $widget['variant']); + $this->assertSame('

Nur Text

', $widget['data']['body']); + } + + public function test_widgets_from_a_newer_schema_cannot_be_saved(): void + { + $this->expectException(ValidationException::class); + + $this->registry()->normalize([['type' => 'heading', 'v' => 99, 'data' => ['heading' => 'Zukunft']]]); + } + + public function test_read_skips_unknown_types_without_failing(): void + { + $widgets = $this->registry()->read([ + ['type' => 'gibt_es_nicht', 'v' => 1], + ['type' => 'prose', 'body' => 'Bleibt lesbar'], + ]); + + $this->assertCount(1, $widgets); + $this->assertSame('prose', $widgets[0]['type']); + } + + public function test_ids_are_kept_and_duplicates_get_new_ids(): void + { + $stored = $this->registry()->normalize([ + ['id' => 'erster', 'type' => 'heading', 'v' => 1, 'data' => ['heading' => 'A']], + ['id' => 'erster', 'type' => 'heading', 'v' => 1, 'data' => ['heading' => 'Kopie']], + ['type' => 'prose', 'body' => 'Ohne Kennung'], + ]); + + $this->assertSame('erster', $stored[0]['id']); + $this->assertNotSame('erster', $stored[1]['id']); + $this->assertNotEmpty($stored[2]['id']); + $this->assertNotSame($stored[1]['id'], $stored[2]['id']); + } + + public function test_only_declared_fields_are_stored(): void + { + $stored = $this->registry()->normalize([[ + 'type' => 'cards', + 'v' => 1, + 'data' => ['items' => [['title' => 'A', 'price' => '99 €', 'url' => '/a']], 'license' => 'alle'], + 'refs' => ['offer' => 7], + ]]); + + $this->assertSame(['items' => [['title' => 'A', 'text' => null, 'url' => '/a', 'image' => null]]], $stored[0]['data']); + $this->assertSame([], $stored[0]['refs']); + } + + public function test_rich_text_from_plain_text_escapes_markup(): void + { + $this->assertSame('

<b>fett</b>

', RichText::fromPlainText('fett')); + $this->assertSame('', RichText::fromPlainText(" \n ")); + } + + private function customWidget(string $key): WidgetType + { + return new class($key) extends WidgetType + { + public function __construct(private readonly string $widgetKey) {} + + public function key(): string + { + return $this->widgetKey; + } + + public function label(): string + { + return 'Teaser'; + } + + public function description(): string + { + return 'Testwidget'; + } + + public function variants(): array + { + return ['standard' => 'Standard', 'wide' => 'Breit']; + } + + public function dataRules(): array + { + return ['heading' => ['required', 'string', 'max:50']]; + } + + public function dataFields(): array + { + return [TextInput::make('heading')]; + } + + public function view(): string + { + return 'widgets.heading'; + } + + public function summary(array $widget): string + { + return (string) ($widget['data']['heading'] ?? ''); + } + }; + } +}