Offers by their own rules, seasonal photos per section, theme authoring tooling

- Special offers: kinds (rule, fixed dates, gap filler), package price, priority, highlight;
  GapFinder detects calendar gaps (optionally waiving the minimum stay); OfferShowcase decides
  what the website advertises and prices fixed dates/gaps with PriceCalculator; offers section
  shows them side by side, as a list or rotating; hero can show the top offer. Appearances no
  longer carry a featured offer.
- Sections get stable ids; appearances set photos per section ("Bilder je Baustein") and
  sections can be limited to appearances. Photo pickers show thumbnails everywhere.
- Themes: themes:make (scaffold, never overwrites), themes:check (contract, build, markup,
  colours, external resources, WCAG contrast), themes:preview (signed links per page and
  appearance), signed ?theme= preview and preview action in the site form, inherited colour
  tokens in the admin. Base CSS split into theme.css + reusable theme-base.css.
- docs/THEME-ERSTELLUNG.md: binding guide for building additional themes elsewhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lars StommerandClaude Opus 5.5 committed 2026-10-22 18:51:38 +02:00
1 parent bc77b64ea7
commit 7d0bc93abc
50 files changed
+2805 -259

No files matched your search

+47 -3
View File
@@ -2,13 +2,19 @@
namespace App\Themes;
use App\Models\Appearance;
use App\Themes\Sections\Section;
use Filament\Forms\Components\Builder\Block;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Select;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\View as ViewFactory;
/**
* The section catalogue from config/themes.php: builder blocks for the admin and rendering for the website.
*
* Every placed section carries data.id (a stable UUID, see Page::assignSectionIds) so appearances can
* address it, and data.appearances (appearance ids; empty = always shown).
*/
class SectionRegistry
{
@@ -36,13 +42,33 @@ public function blocks(): array
{
return array_values(array_map(
fn (string $class): Block => Block::make($class::key())
->label($class::label())
->label(fn (?array $state): string => $this->blockLabel($class, $state))
->icon($class::icon())
->schema($class::schema()),
->schema([
Hidden::make('id'),
...$class::schema(),
Select::make('appearances')
->label('Nur anzeigen im Erscheinungsbild')
->helperText('Leer = immer anzeigen. Z. B. ein Weihnachts-Baustein nur im Erscheinungsbild „Weihnachten“.')
->options(fn (): array => Appearance::query()->orderByDesc('is_default')->orderBy('name')->pluck('name', 'id')->all())
->multiple(),
]),
$this->all(),
));
}
/**
* Whether a placed section is shown with the active appearance.
*
* @param array<string, mixed> $data
*/
public function isVisible(Theme $theme, array $data): bool
{
$appearances = array_map('intval', array_filter((array) ($data['appearances'] ?? [])));
return $appearances === [] || ($theme->appearance !== null && in_array($theme->appearance->id, $appearances, true));
}
/**
* Renders the stored sections of a page; unknown or failing types are skipped (and reported),
* so a page never breaks because of one section.
@@ -55,7 +81,7 @@ public function render(Theme $theme, ?array $sections): array
$views = [];
foreach ($sections ?? [] as $index => $stored) {
$section = $this->get($stored['type'] ?? '');
if ($section === null || ! ViewFactory::exists($section->view())) {
if ($section === null || ! ViewFactory::exists($section->view()) || ! $this->isVisible($theme, $stored['data'] ?? [])) {
continue;
}
@@ -68,4 +94,22 @@ public function render(Theme $theme, ?array $sections): array
return $views;
}
/**
* "Text mit Bild · Ihr Zuhause an der Ostsee · nur: Winter" for the collapsed builder item.
*
* @param class-string<Section> $class
* @param array<string, mixed>|null $state
*/
private function blockLabel(string $class, ?array $state): string
{
if ($state === null) {
return $class::label();
}
$appearances = array_filter((array) ($state['appearances'] ?? []));
$only = $appearances === [] ? null : 'nur: '.Appearance::query()->whereKey($appearances)->pluck('name')->implode(', ');
return collect([$class::label(), $class::summary($state), $only])->filter()->implode(' · ');
}
}
+6 -1
View File
@@ -38,12 +38,17 @@ public static function schema(): array
];
}
public static function photoSlots(): array
{
return ['photo_id' => ['label' => 'Hintergrundfoto', 'type' => self::SLOT_SINGLE]];
}
public function data(Theme $theme, array $data): array
{
return [
'title' => $theme->text('cta.title', $data['title'] ?? null),
'text' => $theme->text('cta.text', $data['text'] ?? null),
'photo' => isset($data['photo_id']) ? Photo::find($data['photo_id']) : null,
'photo' => $this->seasonalPhoto($theme, $data, 'photo_id') ?? (isset($data['photo_id']) ? Photo::find($data['photo_id']) : null),
'buttonLabel' => $data['button_label'] ?? 'Belegung & Preise',
'buttonUrl' => $this->pageUrl($data['button_page'] ?? null) ?? route('booking.create'),
];
+7 -2
View File
@@ -37,16 +37,21 @@ public static function schema(): array
];
}
public static function photoSlots(): array
{
return ['photo_ids' => ['label' => 'Galerie', 'type' => self::SLOT_COLLECTION]];
}
public function data(Theme $theme, array $data): array
{
$category = PhotoCategory::tryFrom($data['category'] ?? '');
return [
'heading' => $data['heading'] ?? null,
'photos' => Photo::query()->published()->with('media')
'photos' => $this->withSeasonalPhotos($theme, $data, 'photo_ids', Photo::query()->published()->with('media')
->when($category, fn ($query) => $query->where('category', $category))
->when(filled($data['limit'] ?? null), fn ($query) => $query->limit((int) $data['limit']))
->get(),
->get()),
];
}
}
+15 -1
View File
@@ -3,6 +3,7 @@
namespace App\Themes\Sections;
use App\Models\Photo;
use App\Pricing\OfferShowcase;
use App\Themes\Theme;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
@@ -36,18 +37,31 @@ public static function schema(): array
Textarea::make('text')->label('Text')->rows(2)->maxLength(400),
static::photoSelect('photo_id', 'Foto (wenn das Erscheinungsbild keins vorgibt)'),
Toggle::make('show_search')->label('Verfügbarkeitssuche anzeigen')->default(true),
Toggle::make('show_offer')
->label('Hervorgehobenes Sonderangebot im Titelbereich zeigen')
->helperText('Das wichtigste als „hervorgehoben“ markierte Angebot, sofern gerade eins gilt.')
->default(true),
];
}
public static function photoSlots(): array
{
return ['photo_id' => ['label' => 'Foto', 'type' => self::SLOT_SINGLE]];
}
public function data(Theme $theme, array $data): array
{
$fallback = isset($data['photo_id']) ? Photo::find($data['photo_id']) : Photo::query()->published()->first();
$featuredOffer = ($data['show_offer'] ?? true) && $theme->property()
? app(OfferShowcase::class)->current($theme->property(), limit: 1, featuredOnly: true)->first()
: null;
return [
'eyebrow' => $theme->text('hero.eyebrow', $data['eyebrow'] ?? null),
'title' => $theme->text('hero.title', $data['title'] ?? $theme->site->name),
'text' => $theme->text('hero.text', $data['text'] ?? null),
'photo' => $theme->heroPhoto($fallback),
'photo' => $this->seasonalPhoto($theme, $data, 'photo_id') ?? $theme->heroPhoto($fallback),
'featuredOffer' => $featuredOffer,
'showSearch' => (bool) ($data['show_search'] ?? true),
'property' => $theme->property(),
];
+6 -1
View File
@@ -39,6 +39,11 @@ public static function schema(): array
];
}
public static function photoSlots(): array
{
return ['photo_ids' => ['label' => 'Bilder der Umgebung', 'type' => self::SLOT_COLLECTION]];
}
public function data(Theme $theme, array $data): array
{
$address = $theme->property()?->address;
@@ -50,7 +55,7 @@ public function data(Theme $theme, array $data): array
'address' => $address,
'mapUrl' => $address ? 'https://www.openstreetmap.org/search?query='.rawurlencode($address) : null,
'photos' => ($data['show_photos'] ?? true)
? Photo::query()->published()->with('media')->where('category', PhotoCategory::Area)->limit(6)->get()
? $this->withSeasonalPhotos($theme, $data, 'photo_ids', Photo::query()->published()->with('media')->where('category', PhotoCategory::Area)->limit(6)->get())
: collect(),
];
}
+19 -15
View File
@@ -2,15 +2,24 @@
namespace App\Themes\Sections;
use App\Models\SpecialOffer;
use App\Pricing\OfferShowcase;
use App\Themes\Theme;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
/**
* Public special offers (active, promoted, without code); the appearance's featured offer comes first.
* The offers OfferShowcase advertises right now (independent of the appearance), shown side by side,
* as a list or one after another (rotating). The section disappears when there is no current offer.
*/
class OffersSection extends Section
{
public const DISPLAYS = [
'grid' => 'Nebeneinander (Kacheln)',
'list' => 'Untereinander (Liste)',
'rotating' => 'Rollierend (eins nach dem anderen)',
];
public static function key(): string
{
return 'offers';
@@ -30,27 +39,22 @@ public static function schema(): array
{
return [
TextInput::make('heading')->label('Überschrift')->default('Aktuelle Angebote')->maxLength(120),
Radio::make('display')->label('Darstellung, wenn mehrere Angebote gelten')->options(self::DISPLAYS)->default('grid'),
TextInput::make('limit')->label('Höchstens anzeigen')->integer()->minValue(1)->maxValue(12)->default(6),
Toggle::make('featured_only')->label('Nur hervorgehobene Angebote')->default(false),
];
}
public function data(Theme $theme, array $data): array
{
$offers = $theme->property()?->specialOffers()
->active()
->where('is_public', true)
->whereNull('code')
->where(fn ($query) => $query->whereNull('bookable_until')->orWhere('bookable_until', '>=', now()))
->get() ?? collect();
$featured = $theme->appearance?->featuredOffer;
if ($featured) {
$offers = $offers->reject(fn (SpecialOffer $offer): bool => $offer->is($featured))->prepend($featured);
}
$property = $theme->property();
return [
'heading' => $data['heading'] ?? null,
'offers' => $offers,
'featuredId' => $featured?->id,
'display' => array_key_exists($data['display'] ?? '', self::DISPLAYS) ? $data['display'] : 'grid',
'offers' => $property
? app(OfferShowcase::class)->current($property, limit: (int) ($data['limit'] ?? 6) ?: 6, featuredOnly: (bool) ($data['featured_only'] ?? false))
: collect(),
];
}
}
+84 -5
View File
@@ -2,6 +2,7 @@
namespace App\Themes\Sections;
use App\Filament\Forms\Components\PhotoSelect;
use App\Models\Page;
use App\Models\Photo;
use App\Themes\Theme;
@@ -17,6 +18,15 @@
*/
abstract class Section
{
/** One photo (field holds a photo id). */
public const SLOT_SINGLE = 'single';
/** Several chosen photos (field holds a list of ids). */
public const SLOT_MULTIPLE = 'multiple';
/** Photos picked automatically (e.g. by category); an appearance may replace or precede them. */
public const SLOT_COLLECTION = 'collection';
abstract public static function key(): string;
abstract public static function label(): string;
@@ -39,6 +49,28 @@ public static function schema(): array
return [];
}
/**
* Photo places an appearance can fill with seasonal photos ("Bilder je Baustein").
*
* @return array<string, array{label: string, type: string, max?: int}>
*/
public static function photoSlots(): array
{
return [];
}
/**
* Short text identifying a placed section in admin lists, e.g. its heading.
*
* @param array<string, mixed> $data
*/
public static function summary(array $data): ?string
{
$text = $data['heading'] ?? $data['title'] ?? null;
return filled($text) ? str(strip_tags((string) $text))->replace('*', '')->limit(50)->toString() : null;
}
/**
* Variables for the view.
*
@@ -75,6 +107,55 @@ protected function photos(?array $ids): Collection
return new Collection(array_values(array_filter(array_map(fn ($id) => $photos->get((int) $id), $ids))));
}
/**
* The seasonal photo the active appearance sets for a single slot of this placed section.
*
* @param array<string, mixed> $data
*/
protected function seasonalPhoto(Theme $theme, array $data, string $slot): ?Photo
{
return $this->seasonalPhotos($theme, $data, $slot)?->first();
}
/**
* The seasonal photos the active appearance sets for a slot of this placed section, null if none.
*
* @param array<string, mixed> $data
* @return Collection<int, Photo>|null
*/
protected function seasonalPhotos(Theme $theme, array $data, string $slot): ?Collection
{
$ids = $theme->sectionPhotoIds($data['id'] ?? null, $slot);
if ($ids === []) {
return null;
}
$photos = $this->photos($ids);
return $photos->isEmpty() ? null : $photos;
}
/**
* Photos of a collection slot: the automatic photos, replaced or preceded by the seasonal ones.
*
* @param array<string, mixed> $data
* @param Collection<int, Photo> $automatic
* @return Collection<int, Photo>
*/
protected function withSeasonalPhotos(Theme $theme, array $data, string $slot, Collection $automatic): Collection
{
$seasonal = $this->seasonalPhotos($theme, $data, $slot);
if ($seasonal === null) {
return $automatic;
}
if ($theme->sectionPhotoMode($data['id'] ?? null) === 'prepend') {
return $seasonal->merge($automatic)->unique('id')->values();
}
return $seasonal;
}
protected function pageUrl(?string $slug): ?string
{
if (blank($slug)) {
@@ -85,15 +166,13 @@ protected function pageUrl(?string $slug): ?string
}
/**
* Select field listing the website photos.
* Select field listing the website photos with thumbnails.
*/
protected static function photoSelect(string $name, string $label, bool $multiple = false): Select
{
return Select::make($name)
return PhotoSelect::make($name)
->label($label)
->options(fn (): array => Photo::query()->orderBy('category')->orderBy('sort_order')->pluck('alt_text', 'id')->all())
->multiple($multiple)
->searchable();
->multiple($multiple);
}
/**
+6 -1
View File
@@ -40,13 +40,18 @@ public static function schema(): array
];
}
public static function photoSlots(): array
{
return ['photo_ids' => ['label' => 'Bilder', 'type' => self::SLOT_MULTIPLE, 'max' => 3]];
}
public function data(Theme $theme, array $data): array
{
return [
'eyebrow' => $data['eyebrow'] ?? null,
'heading' => $data['heading'] ?? '',
'text' => $this->html($data['text'] ?? null),
'photos' => $this->photos($data['photo_ids'] ?? []),
'photos' => $this->seasonalPhotos($theme, $data, 'photo_ids') ?? $this->photos($data['photo_ids'] ?? []),
'imagePosition' => $data['image_position'] ?? 'right',
'linkLabel' => $data['link_label'] ?? null,
'linkUrl' => $this->pageUrl($data['link_page'] ?? null),
+27
View File
@@ -34,6 +34,7 @@ public function activate(): self
{
$paths = array_map(fn (ThemeManifest $theme): string => $theme->viewsPath(), $this->chain());
View::replaceNamespace('theme', $paths);
View::getFinder()->flush();
return $this;
}
@@ -96,6 +97,32 @@ public function heroPhoto(?Photo $fallback = null): ?Photo
return $this->appearance?->heroPhoto ?? $fallback;
}
/**
* Photo ids the active appearance sets for a slot of a placed section ("Bilder je Baustein").
*
* @return list<int>
*/
public function sectionPhotoIds(?string $sectionId, string $slot): array
{
if (blank($sectionId) || $this->appearance === null) {
return [];
}
$ids = $this->appearance->section_photos[$sectionId][$slot] ?? null;
return array_values(array_map('intval', array_filter((array) $ids)));
}
/**
* Whether seasonal photos replace the automatic photos of a section ('replace') or come first ('prepend').
*/
public function sectionPhotoMode(?string $sectionId): string
{
$mode = $sectionId ? ($this->appearance?->section_photos[$sectionId]['mode'] ?? null) : null;
return $mode === 'prepend' ? 'prepend' : 'replace';
}
public function appearanceKey(): string
{
return $this->appearance ? str($this->appearance->name)->slug()->toString() : 'standard';
+334
View File
@@ -0,0 +1,334 @@
<?php
namespace App\Themes;
use App\Models\Appearance;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\Finder\Finder;
/**
* Checks a theme against the theme contract (docs/THEME-ERSTELLUNG.md) so a theme built elsewhere – e.g. by a
* design session – can be verified before it is selected: manifest, inheritance, build entry points, required
* markup of overridden views, token-only colours, no external resources and WCAG contrast of the colour tokens
* (theme defaults and every appearance).
*/
class ThemeChecker
{
/** Pairs [text token, background token] that must reach WCAG AA for normal text (4.5:1). */
public const CONTRAST_PAIRS = [
['ink', 'ground'], ['muted', 'ground'], ['accent', 'ground'],
['ink', 'surface'], ['muted', 'surface'], ['accent', 'surface'],
['accent-ink', 'accent'], ['band-ink', 'band'], ['band-muted', 'band'], ['banner-ink', 'banner'],
];
public const MIN_CONTRAST = 4.5;
/** View files a theme may provide besides sections/<key> (custom partials are allowed in partials/). */
private const KNOWN_VIEWS = ['layouts/app', 'page', 'partials/banner', 'partials/header', 'partials/footer', 'partials/image', 'partials/mobile-booking-bar'];
/**
* Markup an overridden view must keep, with the reason shown when it is missing.
*
* @var array<string, array<string, string>>
*/
private const REQUIRED_MARKUP = [
'layouts/app' => [
"@yield('content')" => 'Seiteninhalt fehlt (@yield(\'content\')).',
"@stack('head')" => 'Bausteine können nichts in <head> ergänzen (JSON-LD) – @stack(\'head\') fehlt.',
'$theme->assets()' => 'CSS/JS werden nicht geladen – @vite($theme->assets()) fehlt.',
'$theme->cssVariables()' => 'Farb-Tokens werden nicht ausgegeben – $theme->cssVariables() fehlt.',
'@livewireStyles' => 'Buchungsformular braucht @livewireStyles.',
'@livewireScripts' => 'Buchungsformular braucht @livewireScripts.',
'noindex' => 'Vorschau und Testbetrieb müssen noindex setzen.',
'id="lightbox"' => 'Galerie-Lightbox fehlt (<dialog id="lightbox"> mit img, [data-caption], [data-close]).',
'data-appearance' => 'data-appearance am <html> fehlt (saisonale CSS-Regeln).',
],
'page' => [
'$sections' => 'Die Bausteine der Seite werden nicht ausgegeben.',
'$structuredData' => 'JSON-LD der Startseite fehlt ($structuredData).',
],
'partials/header' => ["menu('main')" => 'Hauptmenü fehlt ($theme->menu(\'main\')).'],
'partials/footer' => ["menu('footer')" => 'Fußmenü (Impressum/Datenschutz) fehlt ($theme->menu(\'footer\')).'],
'sections/hero' => [
'name="anreise"' => 'Verfügbarkeitssuche: Feld name="anreise" fehlt.',
'name="abreise"' => 'Verfügbarkeitssuche: Feld name="abreise" fehlt.',
"route('booking.create')" => 'Verfügbarkeitssuche muss an route(\'booking.create\') senden.',
],
'sections/booking' => ['livewire:booking-request' => 'Kalender/Anfrage fehlt (<livewire:booking-request :property="$property" />).'],
'sections/gallery' => ['data-lightbox' => 'Galerie-Links brauchen data-lightbox und data-alt.'],
'sections/faq' => ['application/ld+json' => 'FAQ-JSON-LD fehlt.'],
'sections/reviews' => ['nur Gäste' => 'Pflichthinweis zur Echtheit der Bewertungen (§ 5b UWG) fehlt.'],
'sections/offers' => ['$display' => 'Darstellung (nebeneinander/Liste/rollierend) wird nicht berücksichtigt.'],
];
public function __construct(private ThemeRegistry $registry) {}
/**
* @return array{errors: list<string>, warnings: list<string>}
*/
public function check(ThemeManifest $theme): array
{
$errors = [];
$warnings = [];
$this->checkManifest($theme, $errors, $warnings);
$this->checkAssets($theme, $errors, $warnings);
$this->checkViews($theme, $errors, $warnings);
$this->checkContrast($theme, $errors, $warnings);
return ['errors' => $errors, 'warnings' => $warnings];
}
/**
* WCAG contrast ratio of two hex colours (1 … 21).
*/
public static function contrast(string $foreground, string $background): float
{
$luminance = function (string $hex): float {
$hex = ltrim($hex, '#');
if (strlen($hex) === 3) {
$hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
}
$channels = array_map(function (string $pair): float {
$value = hexdec($pair) / 255;
return $value <= 0.03928 ? $value / 12.92 : (($value + 0.055) / 1.055) ** 2.4;
}, str_split(substr($hex, 0, 6), 2));
return 0.2126 * $channels[0] + 0.7152 * $channels[1] + 0.0722 * $channels[2];
};
[$lighter, $darker] = [max($luminance($foreground), $luminance($background)), min($luminance($foreground), $luminance($background))];
return round(($lighter + 0.05) / ($darker + 0.05), 2);
}
/**
* @param list<string> $errors
* @param list<string> $warnings
*/
private function checkManifest(ThemeManifest $theme, array &$errors, array &$warnings): void
{
if (! preg_match('/^[a-z0-9]+(-[a-z0-9]+)*$/', $theme->key)) {
$errors[] = "Key „{$theme->key}“: nur Kleinbuchstaben, Ziffern und Bindestriche.";
}
if (basename($theme->path) !== $theme->key) {
$errors[] = 'Ordnername ('.basename($theme->path).") und key ({$theme->key}) müssen gleich sein – sonst baut Vite die Assets nicht.";
}
if (! preg_match('/^\d+\.\d+\.\d+$/', $theme->version)) {
$errors[] = "version „{$theme->version}“ ist keine Versionsnummer (z. B. 0.1.0).";
}
if (blank($theme->description)) {
$warnings[] = 'description fehlt – sie wird im Admin bei der Theme-Auswahl angezeigt.';
}
if ($theme->parent !== null) {
if ($theme->parent === $theme->key) {
$errors[] = 'parent verweist auf das Theme selbst.';
} elseif (! isset($this->registry->all()[$theme->parent])) {
$errors[] = "Eltern-Theme „{$theme->parent}“ ist nicht installiert.";
}
}
foreach ($theme->tokens as $key => $token) {
if (! is_array($token) || blank($token['label'] ?? null) || ! preg_match('/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', (string) ($token['default'] ?? ''))) {
$errors[] = "Token „{$key}“ braucht label und default als Hex-Farbe (#RRGGBB).";
}
}
$missing = array_diff(array_keys($this->registry->tokens(config('themes.base'))), array_keys($this->registry->tokens($theme->key)));
if ($missing !== []) {
$errors[] = 'Basis-Tokens fehlen in der Theme-Kette: '.implode(', ', $missing).' (die Basis-Vorlagen und Formulare nutzen sie).';
}
}
/**
* @param list<string> $errors
* @param list<string> $warnings
*/
private function checkAssets(ThemeManifest $theme, array &$errors, array &$warnings): void
{
$css = $theme->assets['css'] ?? null;
$js = $theme->assets['js'] ?? null;
if ($css === null && $js === null) {
if (is_dir($theme->viewsPath()) && Finder::create()->files()->name('*.blade.php')->in($theme->viewsPath())->hasResults()) {
$errors[] = 'Eigene Vorlagen ohne eigene Assets: deren Tailwind-Klassen werden nicht gebaut – theme.css/theme.js anlegen (themes:make macht das) und in assets eintragen.';
}
return;
}
$folder = str_replace('\\', '/', ltrim(substr($theme->path, strlen(base_path())), '/\\'));
if (! str_starts_with($folder, 'resources/themes/')) {
$warnings[] = 'Theme liegt nicht unter resources/themes – vite.config.js baut seine Assets dort nicht automatisch.';
}
foreach (['css' => 'theme.css', 'js' => 'theme.js'] as $type => $file) {
$expected = "{$folder}/{$file}";
$declared = $theme->assets[$type] ?? null;
if ($declared === null) {
$errors[] = "assets.{$type} fehlt: Ein Theme mit eigenen Assets ersetzt CSS und JS des Eltern-Themes vollständig – {$file} anlegen (darf das Eltern-Theme importieren).";
} elseif ($declared !== $expected) {
$errors[] = "assets.{$type} muss „{$expected}“ heißen – nur diese Datei baut Vite (vite.config.js).";
} elseif (! is_file(base_path($declared))) {
$errors[] = "{$declared} fehlt.";
}
}
$cssFile = $css !== null ? base_path($css) : null;
if ($cssFile !== null && is_file($cssFile)) {
$content = (string) file_get_contents($cssFile);
$resolved = $this->withLocalImports($cssFile);
if (preg_match("~@import\s+['\"]\.\./[a-z0-9-]+/theme\.css['\"]~", $content)) {
$warnings[] = 'theme.css importiert das theme.css eines anderen Themes – besser dessen theme-base.css importieren und die Quellen selbst angeben (siehe Anleitung).';
}
if (! str_contains($content, "@import 'tailwindcss'") && ! str_contains($content, '@import "tailwindcss"')) {
$errors[] = "theme.css muss mit @import 'tailwindcss'; beginnen.";
}
foreach ($this->registry->chain($theme->key) as $ancestor) {
$source = ThemeManifest::relativePath($theme->path, $ancestor->viewsPath());
if ($ancestor->key !== $theme->key && ! str_contains($resolved, $source)) {
$errors[] = "theme.css scannt die Vorlagen von „{$ancestor->key}“ nicht (@source '{$source}') – geerbte Bausteine wären ungestylt.";
}
}
if (is_dir($theme->viewsPath()) && ! preg_match("~@source\s+['\"]\./views['\"]~", $content)) {
$errors[] = "theme.css scannt die eigenen Vorlagen nicht (@source './views').";
}
if (! str_contains($resolved, 'views/livewire')) {
$errors[] = "theme.css scannt die Buchungsformulare nicht (@source '".ThemeManifest::relativePath($theme->path, resource_path('views/livewire'))."').";
}
foreach (array_keys($this->registry->tokens($theme->key)) as $token) {
if (! str_contains($resolved, "--color-{$token}:")) {
$errors[] = "Token „{$token}“ ist nicht gemappt (@theme inline { --color-{$token}: var(--{$token}); }) – Klassen wie bg-{$token} fehlen.";
}
}
$this->scanExternal($resolved, 'theme.css', $errors);
}
$jsFile = $js !== null ? base_path($js) : null;
if ($jsFile !== null && is_file($jsFile)) {
$content = (string) file_get_contents($jsFile);
if (! preg_match("~import\s+['\"]\.\./[a-z0-9-]+/theme\.js['\"]~", $content) && ! str_contains($content, 'data-rotator')) {
$warnings[] = "theme.js importiert kein anderes Theme (import '../ostsee-licht/theme.js') – Lightbox, Suche und rollierende Angebote müssen dann selbst umgesetzt sein.";
}
$this->scanExternal($content, 'theme.js', $errors);
}
}
/**
* @param list<string> $errors
* @param list<string> $warnings
*/
private function checkViews(ThemeManifest $theme, array &$errors, array &$warnings): void
{
if (! is_dir($theme->viewsPath())) {
return;
}
$sections = array_keys(app(SectionRegistry::class)->all());
foreach (Finder::create()->files()->in($theme->viewsPath()) as $file) {
$name = str_replace('\\', '/', $file->getRelativePathname());
if (! str_ends_with($name, '.blade.php')) {
if ($name !== '.gitkeep') {
$warnings[] = "views/{$name}: keine Blade-Datei (wird ignoriert).";
}
continue;
}
$view = substr($name, 0, -strlen('.blade.php'));
$isSection = str_starts_with($view, 'sections/');
if ($isSection && ! in_array(substr($view, 9), $sections, true)) {
$errors[] = "views/{$name}: unbekannter Baustein (erlaubt: ".implode(', ', $sections).').';
} elseif (! $isSection && ! in_array($view, self::KNOWN_VIEWS, true) && ! str_starts_with($view, 'partials/')) {
$warnings[] = "views/{$name}: wird vom System nicht aufgerufen (nur eigene Includes).";
}
$content = $file->getContents();
foreach (self::REQUIRED_MARKUP[$view] ?? [] as $needle => $reason) {
if (str_contains($content, $needle)) {
continue;
}
if ($view === 'sections/offers') {
$warnings[] = "views/{$name}: {$reason}";
} else {
$errors[] = "views/{$name}: {$reason}";
}
}
if ($isSection && ! str_contains($content, '$sectionId')) {
$warnings[] = "views/{$name}: \$sectionId nicht genutzt (eindeutige IDs für aria-labelledby).";
}
if (preg_match('/\b(?:bg|text|border|ring|fill|stroke|from|via|to|outline|decoration|divide|shadow)-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|[1-9]00|950)\b|-\[(?:#|rgb)/', $content, $match)) {
$errors[] = "views/{$name}: feste Farbe „{$match[0]}“ – nur Token-Klassen verwenden (bg-accent, text-muted …), sonst wirken Erscheinungsbilder nicht.";
}
if (preg_match('/style="[^"]*(?:#[0-9a-fA-F]{3,8}\b|rgba?\()/', $content)) {
$errors[] = "views/{$name}: feste Farbe im style-Attribut – var(--token) verwenden.";
}
if (str_contains($content, '<iframe')) {
$warnings[] = "views/{$name}: <iframe> eingebettet – Drittanbieter brauchen ein Einwilligungskonzept (DSGVO).";
}
$this->scanExternal($content, "views/{$name}", $errors);
}
}
/**
* @param list<string> $errors
* @param list<string> $warnings
*/
private function checkContrast(ThemeManifest $theme, array &$errors, array &$warnings): void
{
$defaults = array_map(fn (array $token): string => (string) ($token['default'] ?? ''), $this->registry->tokens($theme->key));
$variants = ['Theme-Standard' => $defaults];
if (Schema::hasTable('appearances')) {
foreach (Appearance::query()->where('is_active', true)->get() as $appearance) {
$variants["Erscheinungsbild „{$appearance->name}“"] = [...$defaults, ...array_filter($appearance->tokens ?? [], fn ($value): bool => is_string($value) && preg_match('/^#[0-9a-fA-F]{3,8}$/', $value) === 1)];
}
}
foreach ($variants as $label => $tokens) {
foreach (self::CONTRAST_PAIRS as [$text, $background]) {
if (! isset($tokens[$text], $tokens[$background]) || ! preg_match('/^#/', $tokens[$text]) || ! preg_match('/^#/', $tokens[$background])) {
continue;
}
$ratio = self::contrast($tokens[$text], $tokens[$background]);
if ($ratio < self::MIN_CONTRAST) {
$message = "{$label}: Kontrast {$text} auf {$background} nur {$ratio}:1 (mind. ".self::MIN_CONTRAST.':1).';
if ($label === 'Theme-Standard') {
$errors[] = $message;
} else {
$warnings[] = $message;
}
}
}
}
}
/**
* The CSS file with its relative @imports (theme-base.css etc.) inlined, for checks across files.
*/
private function withLocalImports(string $file, int $depth = 0): string
{
$content = (string) file_get_contents($file);
if ($depth > 3) {
return $content;
}
return preg_replace_callback("~@import\s+['\"](\.{1,2}/[^'\"]+\.css)['\"]\s*;~", function (array $match) use ($file, $depth): string {
$imported = dirname($file).DIRECTORY_SEPARATOR.$match[1];
return is_file($imported) ? $this->withLocalImports($imported, $depth + 1) : $match[0];
}, $content) ?? $content;
}
/**
* @param list<string> $errors
*/
private function scanExternal(string $content, string $file, array &$errors): void
{
if (preg_match('~https?://(?:fonts\.googleapis|fonts\.gstatic|use\.typekit|[a-z0-9.-]*cdn[a-z0-9.-]*|unpkg\.com|cdnjs)[^\s"\')]*~i', $content, $match)) {
$errors[] = "{$file}: externe Quelle „{$match[0]}“ – Schriften und Skripte selbst hosten (DSGVO, kein Cookie-Banner).";
}
if (preg_match('~<script[^>]+src=["\']https?://~i', $content)) {
$errors[] = "{$file}: externes Skript – nicht erlaubt.";
}
}
}
+11 -5
View File
@@ -18,22 +18,28 @@ public function __construct(private ThemeRegistry $registry) {}
public function forRequest(Request $request): Theme
{
$site = $this->site($request->getHost());
$isSigned = ($request->query('vorschau') || $request->query('theme')) && $request->hasValidSignature();
$preview = null;
if ($request->query('vorschau') && $request->hasValidSignature()) {
$preview = $site->appearances()->find($request->query('vorschau'));
$preview = $isSigned && $request->query('vorschau') ? $site->appearances()->find($request->query('vorschau')) : null;
// Theme preview: the site is shown with another installed theme without changing it (not saved).
$previewTheme = $isSigned ? (string) $request->query('theme') : '';
if ($previewTheme !== '' && isset($this->registry->all()[$previewTheme])) {
$site = (clone $site)->setAttribute('theme', $previewTheme);
return $this->forSite($site, $preview, isPreview: true);
}
return $this->forSite($site, $preview);
}
public function forSite(Site $site, ?Appearance $preview = null): Theme
public function forSite(Site $site, ?Appearance $preview = null, bool $isPreview = false): Theme
{
return new Theme(
$this->registry,
$site,
$preview ?? ($site->exists ? $site->appearanceOn(today()) : null),
isPreview: $preview !== null,
isPreview: $isPreview || $preview !== null,
);
}
+18
View File
@@ -48,4 +48,22 @@ public function viewsPath(): string
{
return $this->path.DIRECTORY_SEPARATOR.'views';
}
/**
* Relative path with forward slashes from one directory to another, as used in CSS @import/@source
* and JS imports, e.g. "../ostsee-licht/views".
*/
public static function relativePath(string $fromDirectory, string $to): string
{
$normalise = fn (string $path): array => array_values(array_filter(explode('/', str_replace('\\', '/', realpath($path) ?: $path)), fn (string $part): bool => $part !== ''));
$from = $normalise($fromDirectory);
$target = $normalise($to);
while ($from !== [] && $target !== [] && strcasecmp($from[0], $target[0]) === 0) {
array_shift($from);
array_shift($target);
}
return implode('/', [...array_fill(0, count($from), '..'), ...$target]) ?: '.';
}
}
+15
View File
@@ -57,6 +57,21 @@ public function chain(string $key): array
return array_values($chain);
}
/**
* Colour tokens of a theme including the inherited ones (base first, the theme's own definitions win).
*
* @return array<string, array{label: string, default: string}>
*/
public function tokens(string $key): array
{
$tokens = [];
foreach (array_reverse($this->chain($key)) as $theme) {
$tokens = [...$tokens, ...$theme->tokens];
}
return $tokens;
}
/**
* @return array<string, string>
*/