Files
laraundfelix/app/Domain/Design/DesignPalette.php
T
LarsandClaude Sonnet 5.5 2b00905f00
CI Feature / test (push) Failing after 5m29s
Ergänze Farbe aus der Palette und Schriftgrößen je Widget
Gemeinsamer Vertrag in WidgetType (typography(), paletteTarget()) mit den
Einstellungen heading_size, text_size und palette; WidgetAppearance setzt
Klassen und Eigenschaften an der Hülle, nur wenn ein Wert gewählt ist.
Eine absolute Größenskala aus den Designwerten gilt in jedem Widget gleich;
ohne Wahl bleibt die bisherige Größe. Die Palettenfarbe färbt je Art die
Fläche des Widgets (hull) oder dessen eigene Fläche (face).

Der Verwendungsnachweis der Palette zählt jetzt auch Widgets, damit die
Bestätigung einer Farbänderung und die Sperre beim Entfernen greifen.
Der Vertragstest für Einstellungsgruppen nimmt die gemeinsamen Schlüssel
bewusst aus, weil sie eigene Gruppen im Editor haben.

ADR-68, Abnahme unter docs/ux/verwaltung/abnahme/widget-flaeche-schrift.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-30 09:50:16 +01:00

340 lines
12 KiB
PHP

<?php
namespace App\Domain\Design;
use App\Domain\Cms\Page;
use App\Domain\Cms\Sections\SectionStyle;
use App\Models\User;
use Illuminate\Support\Facades\Cache;
use Throwable;
/**
* Zentrale Farbpalette der Website (ADR-67, Schlüssel „design.palette“ in site_settings): bis zu zehn benannte Farben, jede
* mit Hintergrund- und Schriftfarbe. Abschnitte verweisen auf eine Farbe (style.background = „palette“, style.palette_slot =
* Kennung); die Farbwerte stehen nur hier.
*
* - Die Kennung („c1“, „c2“ …) wird nie wieder vergeben, auch nicht nach dem Entfernen einer Farbe.
* - Eine Änderung der Farbwerte wirkt sofort auf alle Abschnitte mit dieser Farbe, auch auf veröffentlichten Seiten
* (die Revisionen speichern nur den Verweis). Darum zeigt die Verwaltung die betroffenen Seiten vor dem Speichern
* (usage), und eine Farbe in Verwendung lässt sich nicht entfernen.
* - Neue und geänderte Farben müssen für normalen Text 4,5:1 erreichen (WCAG 2.2 AA).
* - Die öffentliche Ausgabe hängt nie am Erfolg dieser Klasse: Fehlt die Tabelle, ist die Datenbank nicht erreichbar oder
* sind die Daten beschädigt, gibt es keine Farben, und Abschnitte mit Verweis erscheinen ohne eigene Fläche.
*/
final class DesignPalette
{
public const KEY = 'design.palette';
public const MAX_SLOTS = 10;
public const MAX_NAME = 40;
private const CACHE_KEY = 'design.palette.v1';
/** @var array{next: int, slots: list<array{id: string, name: string, bg: string, fg: string}>}|null */
private static ?array $memo = null;
/**
* Fest vorgegebene Markenflächen der Abschnitte. Sie sind Teil des Designsystems (tokens.css), keine Palettenfarben,
* und bleiben unverändert, damit bestehende Seiten gleich aussehen.
*
* @return list<array{key: string, label: string, bg: string, fg: string, border: bool}>
*/
public static function builtIns(): array
{
return [
['key' => 'default', 'label' => SectionStyle::BACKGROUNDS['default'], 'bg' => '#ffffff', 'fg' => '#15243a', 'border' => true],
['key' => 'light', 'label' => SectionStyle::BACKGROUNDS['light'], 'bg' => '#f7f6f2', 'fg' => '#15243a', 'border' => true],
['key' => 'dark', 'label' => SectionStyle::BACKGROUNDS['dark'], 'bg' => '#032551', 'fg' => '#f4f6f8', 'border' => false],
['key' => 'accent', 'label' => SectionStyle::BACKGROUNDS['accent'], 'bg' => '#3b7b09', 'fg' => '#ffffff', 'border' => false],
];
}
/**
* @return list<array{id: string, name: string, bg: string, fg: string}>
*/
public static function slots(): array
{
return self::state()['slots'];
}
/**
* @return array{id: string, name: string, bg: string, fg: string}|null
*/
public static function find(mixed $id): ?array
{
if (! is_string($id)) {
return null;
}
foreach (self::slots() as $slot) {
if ($slot['id'] === $id) {
return $slot;
}
}
return null;
}
/** Anzahl noch freier Plätze. */
public static function free(): int
{
return max(0, self::MAX_SLOTS - count(self::slots()));
}
/**
* Prüft eine Farbe. Gibt Fehlermeldungen je Feld zurück („name“, „bg“, „fg“, „slot“); leer, wenn sie zulässig ist.
*
* @return array<string, string>
*/
public static function errors(?string $id, mixed $name, mixed $bg, mixed $fg): array
{
$errors = [];
$name = is_string($name) ? trim(preg_replace('/\s+/u', ' ', $name) ?? '') : '';
if ($name === '') {
$errors['name'] = 'Bitte einen Namen eingeben, zum Beispiel „Markengrün“.';
} elseif (mb_strlen($name) > self::MAX_NAME) {
$errors['name'] = 'Der Name darf höchstens '.self::MAX_NAME.' Zeichen lang sein.';
} else {
foreach (self::slots() as $slot) {
if ($slot['id'] !== $id && mb_strtolower($slot['name']) === mb_strtolower($name)) {
$errors['name'] = 'Eine Farbe mit diesem Namen gibt es schon.';
}
}
}
$background = ColorContrast::normalize($bg);
$text = ColorContrast::normalize($fg);
if ($background === null) {
$errors['bg'] = 'Bitte einen HEX-Wert angeben, zum Beispiel #3b7b09.';
}
if ($text === null) {
$errors['fg'] = 'Bitte einen HEX-Wert angeben, zum Beispiel #ffffff.';
}
if ($background !== null && $text !== null) {
$ratio = ColorContrast::ratio($text, $background);
if ($ratio < ColorContrast::NORMAL_TEXT) {
$errors['fg'] = 'Der Kontrast beträgt nur '.self::number($ratio).' : 1. Für lesbaren Text sind mindestens 4,5 : 1 nötig (WCAG 2.2 AA). Empfehlung: '.ColorContrast::suggestText($background).'.';
}
}
if ($id === null && count(self::slots()) >= self::MAX_SLOTS) {
$errors['slot'] = 'Die Palette ist voll. Es sind höchstens '.self::MAX_SLOTS.' Farben möglich.';
}
if ($id !== null && self::find($id) === null) {
$errors['slot'] = 'Diese Farbe gibt es nicht mehr.';
}
return $errors;
}
/**
* Legt eine Farbe an ($id = null) oder ändert sie.
*
* @return array<string, string> Fehlermeldungen je Feld; leer bei Erfolg
*/
public static function save(?string $id, mixed $name, mixed $bg, mixed $fg, ?User $by = null): array
{
$errors = self::errors($id, $name, $bg, $fg);
if ($errors !== []) {
return $errors;
}
$state = self::state();
$entry = [
'name' => trim(preg_replace('/\s+/u', ' ', (string) $name) ?? ''),
'bg' => (string) ColorContrast::normalize($bg),
'fg' => (string) ColorContrast::normalize($fg),
];
if ($id === null) {
$entry = ['id' => 'c'.$state['next']] + $entry;
$state['next']++;
$state['slots'][] = $entry;
} else {
foreach ($state['slots'] as $index => $slot) {
if ($slot['id'] === $id) {
$state['slots'][$index] = ['id' => $id] + $entry;
}
}
}
self::write($state, $by);
return [];
}
/**
* Entfernt eine Farbe. Solange ein Abschnitt (veröffentlicht oder im Entwurf) sie verwendet, bleibt sie bestehen.
*
* @return array<string, string> Fehlermeldung unter „slot“; leer bei Erfolg
*/
public static function remove(string $id, ?User $by = null): array
{
if (self::find($id) === null) {
return ['slot' => 'Diese Farbe gibt es nicht mehr.'];
}
$uses = self::usage()[$id] ?? [];
if ($uses !== []) {
return ['slot' => 'Die Farbe wird noch verwendet ('.count($uses).' '.(count($uses) === 1 ? 'Seite' : 'Seiten').'). Wählen Sie dort zuerst eine andere Fläche.'];
}
$state = self::state();
$state['slots'] = array_values(array_filter($state['slots'], static fn (array $slot): bool => $slot['id'] !== $id));
self::write($state, $by);
return [];
}
/**
* Verwendung der Farben: je Kennung die Seiten mit Abschnitten dieser Farbe, getrennt nach veröffentlichtem Stand und
* Entwurf (neuester Stand, der noch nicht veröffentlicht ist). Ältere Revisionen zählen nicht; sie zeigen beim
* Wiederherstellen die aktuelle Farbe.
*
* @return array<string, list<array{page_id: int, path: string, title: string, published: int, draft: int}>>
*/
public static function usage(): array
{
$uses = [];
foreach (Page::query()->with(['publishedRevision', 'latestRevision'])->orderBy('path')->get() as $page) {
$published = $page->publishedRevision;
$latest = $page->latestRevision;
$draft = $latest !== null && $latest->id !== $published?->id ? $latest : null;
$countPublished = self::countSections($published?->sections);
$countDraft = self::countSections($draft?->sections);
foreach (array_unique([...array_keys($countPublished), ...array_keys($countDraft)]) as $slotId) {
$uses[$slotId][] = [
'page_id' => $page->id,
'path' => $page->path,
'title' => $published !== null ? $page->publicTitle() : ($latest?->contentTitle() ?? $page->path),
'published' => $countPublished[$slotId] ?? 0,
'draft' => $countDraft[$slotId] ?? 0,
];
}
}
return $uses;
}
public static function flush(): void
{
self::$memo = null;
try {
Cache::forget(self::CACHE_KEY);
} catch (Throwable) {
// Der Zwischenspeicher ist nur Beschleunigung.
}
}
/** Zahl mit Komma für Meldungen: 4,05. */
public static function number(float $value): string
{
return rtrim(rtrim(number_format($value, 2, ',', ''), '0'), ',');
}
/**
* @param array<int|string, mixed>|null $sections
* @return array<string, int> Kennung => Anzahl Abschnitte
*/
private static function countSections(?array $sections): array
{
$count = [];
foreach ($sections ?? [] as $section) {
$style = is_array($section) && is_array($section['style'] ?? null) ? $section['style'] : [];
if (($style['background'] ?? null) === 'palette' && is_string($style['palette_slot'] ?? null)) {
$count[$style['palette_slot']] = ($count[$style['palette_slot']] ?? 0) + 1;
}
// Farbe eines Widgets (ADR-68): settings.palette im Platz.
foreach (is_array($section) && is_array($section['slots'] ?? null) ? $section['slots'] : [] as $widget) {
$slotId = is_array($widget) && is_array($widget['settings'] ?? null) ? ($widget['settings']['palette'] ?? null) : null;
if (is_string($slotId)) {
$count[$slotId] = ($count[$slotId] ?? 0) + 1;
}
}
}
return $count;
}
/**
* @return array{next: int, slots: list<array{id: string, name: string, bg: string, fg: string}>}
*/
private static function state(): array
{
if (self::$memo !== null) {
return self::$memo;
}
try {
$stored = Cache::rememberForever(self::CACHE_KEY, static function (): array {
$row = SiteSetting::query()->find(self::KEY);
return $row === null ? [] : (array) $row->value;
});
} catch (Throwable) {
$stored = [];
}
return self::$memo = self::read($stored);
}
/**
* Lesepfad: Beschädigtes oder Unvollständiges entfällt, nie ein Fehler.
*
* @param array<int|string, mixed> $stored
* @return array{next: int, slots: list<array{id: string, name: string, bg: string, fg: string}>}
*/
private static function read(array $stored): array
{
$slots = [];
$highest = 0;
foreach (is_array($stored['slots'] ?? null) ? $stored['slots'] : [] as $slot) {
if (! is_array($slot) || ! is_string($slot['id'] ?? null) || preg_match('/^c([1-9][0-9]*)$/', $slot['id'], $match) !== 1) {
continue;
}
$bg = ColorContrast::normalize($slot['bg'] ?? null);
$fg = ColorContrast::normalize($slot['fg'] ?? null);
$name = is_string($slot['name'] ?? null) ? trim($slot['name']) : '';
if ($bg === null || $fg === null || $name === '' || count($slots) >= self::MAX_SLOTS) {
continue;
}
$highest = max($highest, (int) $match[1]);
$slots[] = ['id' => $slot['id'], 'name' => mb_substr($name, 0, self::MAX_NAME), 'bg' => $bg, 'fg' => $fg];
}
$next = is_int($stored['next'] ?? null) ? $stored['next'] : 1;
return ['next' => max($next, $highest + 1, 1), 'slots' => $slots];
}
/**
* @param array{next: int, slots: list<array{id: string, name: string, bg: string, fg: string}>} $state
*/
private static function write(array $state, ?User $by): void
{
SiteSetting::query()->updateOrCreate(['key' => self::KEY], ['value' => $state, 'updated_by' => $by?->getKey()]);
self::flush();
}
}