feat: lit/divi-colors-set legt globale Farben an, ändert und deaktiviert sie (Probelauf, design_rev, Snapshot)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Jan-Niclas Loosen
2026-10-19 14:07:23 +02:00
co-authored by Claude Sonnet 5.5
parent c1f77d2017
commit 337b87b572
2 changed files with 645 additions and 0 deletions
@@ -0,0 +1,342 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Integrations\Divi\Design;
use Closure;
use InvalidArgumentException;
use LIT\MCP\Abilities\Ability;
use LIT\MCP\Abilities\Annotations;
use LIT\MCP\Abilities\Errors;
use LIT\MCP\Integrations\Divi\Library\GlobalUsages;
use LIT\MCP\Integrations\Divi\Release\DiviFeature;
use LIT\MCP\Integrations\Divi\Release\RequiresDiviFeatures;
use WP_Error;
defined('ABSPATH') || exit;
/**
* lit/divi-colors-set (spec §7.1, rulings V3–V5, V8): creates and changes global colors through the change pipeline
* (ColorArea). An item names an existing color in id (ID, label, alias primary … or option name accent_color …) or
* creates one from label and color. Colors are never deleted, only deactivated; the five main colors only change
* their value. The dry run lists the posts that reference a changed, deactivated or activated color
* (ReferenceUsageQuery).
*/
final class DiviColorsSetAbility implements Ability, RequiresDiviFeatures
{
public const MAX_ITEMS = 50;
private const LABEL_MAX = 100;
private const LABEL_RULE = 'Name: 1–100 Zeichen, ohne HTML';
private const STATUSES = ['active', 'inactive'];
private const MAIN_COLOR_RULE = 'Hauptfarben ändern nur color, nicht label, folder oder status';
/** A color as Divi stores it (formats §1); new colors start from it. */
private const NEW_ENTRY = ['color' => '', 'folder' => '', 'label' => '', 'lastUpdated' => '', 'status' => 'active',
'usedInPosts' => []];
/** @param (Closure(int): string)|null $random Random characters for new IDs (ColorBook::newId(); tests). */
public function __construct(
private DesignSystemWriter $writer,
private GlobalColorsAdapter $colors,
private DesignChange $change,
private GlobalUsages $usages,
private ?Closure $random = null
) {
}
public function name(): string
{
return 'lit/divi-colors-set';
}
public function label(): string
{
return 'Globale Divi-Farben anlegen und ändern';
}
public function description(): string
{
return 'Legt globale Farben an oder ändert sie. items: id nennt eine vorhandene Farbe (ID, Name, Alias '
. 'primary, secondary, heading, body, link oder Optionsname wie accent_color); ohne id entsteht eine neue '
. 'Farbe aus '
. 'label und color. color: Hex, rgb()/rgba()/hsl()/hsla(), Farbname oder {{color:<Name>}} mit relative '
. '(hue, saturation, lightness, opacity). status inactive deaktiviert (Farben werden nie gelöscht); die '
. 'fünf Hauptfarben ändern nur color. Wirkt auf alle Seiten: zuerst Probelauf (diff, betroffene Seiten, '
. 'Warnungen, design_rev), nach Rückfrage beim Nutzer confirm: true mit design_rev. Vorher wird ein '
. 'Snapshot angelegt (lit/divi-design-restore).';
}
public function inputSchema(): array
{
$number = ['type' => 'number'];
return [
'type' => 'object',
'properties' => [
'items' => [
'type' => 'array',
'minItems' => 1,
'maxItems' => self::MAX_ITEMS,
'items' => [
'type' => 'object',
'properties' => [
'id' => [
'type' => 'string',
'description' => 'Vorhandene Farbe: ID, Name, Alias oder Optionsname.',
],
'label' => ['type' => 'string', 'description' => 'Name einer neuen Farbe oder umbenennen.'],
'color' => ['type' => 'string'],
'relative' => [
'type' => 'object',
'properties' => [
'hue' => $number,
'saturation' => $number,
'lightness' => $number,
'opacity' => $number,
],
],
'folder' => ['type' => 'string'],
'status' => ['type' => 'string', 'description' => 'active oder inactive.'],
],
],
],
] + DesignChange::inputProperties(),
'required' => ['items'],
'additionalProperties' => false,
];
}
public function outputSchema(): ?array
{
return DesignChange::outputSchema();
}
public function annotations(): array
{
return Annotations::destructive(false);
}
public function isDirect(): bool
{
return false;
}
/** Reads and writes the global colors; the warnings read the presets (DesignRead). */
public function diviFeatures(array $input): array
{
return [DiviFeature::DesignRead, DiviFeature::ColorWrite];
}
public function permission(array $input): bool|WP_Error
{
return DesignRights::colors($this->writer) ?? true;
}
public function execute(array $input): mixed
{
$refusal = DesignRights::colors($this->writer);
if ($refusal !== null) {
return $refusal;
}
$items = $input['items'] ?? null;
if (! is_array($items) || ! array_is_list($items) || $items === [] || count($items) > self::MAX_ITEMS) {
return Errors::invalidInput(
'items fehlt oder ist zu lang; nichts wurde gespeichert.',
['items' => sprintf('1 bis %d Einträge', self::MAX_ITEMS)]
);
}
return $this->change->run(
$this->name(),
new ColorArea($this->colors),
$input,
fn (array $raw): DesignPlan|WP_Error => $this->plan(ColorBook::fromDivi($raw), $items)
);
}
/** @param list<mixed> $items */
private function plan(ColorBook $before, array $items): DesignPlan|WP_Error
{
$book = $before;
$errors = [];
foreach ($items as $index => $item) {
$field = sprintf('items[%d]', $index);
if (! is_array($item)) {
$errors[$field] = 'Objekt erwartet';
continue;
}
$book = $this->apply($book, $item, $field, $errors);
}
if ($errors !== []) {
return Errors::invalidInput('Ungültige Farb-Angaben; nichts wurde gespeichert.', $errors);
}
$diff = ColorDiff::between($before, $book);
$touched = [];
foreach ($diff as $row) {
if ($row['action'] !== 'added') {
$touched[] = (string) $row['id'];
}
}
$touched = array_values(array_unique($touched));
return new DesignPlan(
$book->data(),
$diff,
ColorDiff::summary($diff),
$touched === [] ? null : $this->usages->reportFor(new ReferenceUsageQuery($touched))
);
}
/**
* $book with the color of $item created or changed; problems go to $errors and leave $book as it was.
*
* @param array<array-key, mixed> $item
* @param array<string, string> $errors
*/
private function apply(ColorBook $book, array $item, string $field, array &$errors): ColorBook
{
$known = count($errors);
$id = array_key_exists('id', $item) ? self::existing($book, $item['id'], $field . '.id', $errors) : null;
if (count($errors) > $known) {
return $book;
}
$main = $id !== null && $book->isCustomizer($id);
$entry = $id === null ? self::NEW_ENTRY : (array) $book->entry($id);
foreach (['label', 'folder', 'status', 'color'] as $key) {
if (! array_key_exists($key, $item)) {
if ($id === null && ($key === 'label' || $key === 'color')) {
$errors[$field . '.' . $key] = 'Pflicht für eine neue Farbe';
}
continue;
}
if ($main && $key !== 'color') {
$errors[$field . '.' . $key] = self::MAIN_COLOR_RULE;
continue;
}
try {
$entry[$key] = match ($key) {
'label' => self::cleanLabel($book, $item['label'], $id),
'folder' => self::folder($item['folder']),
'status' => self::status($item['status']),
default => self::value($item),
};
} catch (InvalidArgumentException $e) {
$errors[$field . '.' . $key] = $e->getMessage();
}
}
if (count($errors) > $known || ($id !== null && $entry === $book->entry($id))) {
return $book;
}
if (! $main) {
// Ruling V3: the main colors' lastUpdated stays "" (ColorBook ignores it).
$entry['lastUpdated'] = ColorBook::now();
}
return $book->with($id ?? $this->newId($book), $entry);
}
/** @param array<string, string> $errors */
private static function existing(ColorBook $book, mixed $needle, string $field, array &$errors): ?string
{
if (! is_string($needle) || trim($needle) === '') {
$errors[$field] = 'ID, Name, Alias oder Optionsname der Farbe erwartet';
return null;
}
try {
$id = $book->find($needle);
} catch (InvalidArgumentException $e) {
$errors[$field] = $e->getMessage();
return null;
}
if ($id === null) {
$errors[$field] = sprintf('unbekannte Farbe „%s“', $needle);
}
return $id;
}
/**
* A label no other color has as name, ID or alias (it would make {{color:…}} ambiguous).
*
* @throws InvalidArgumentException
*/
private static function cleanLabel(ColorBook $book, mixed $label, ?string $id): string
{
$clean = is_string($label) && strlen($label) <= self::LABEL_MAX * 4 ? sanitize_text_field($label) : '';
if ($clean === '' || mb_strlen($clean) > self::LABEL_MAX) {
throw new InvalidArgumentException(self::LABEL_RULE);
}
try {
$taken = $book->find($clean);
} catch (InvalidArgumentException) {
$taken = ''; // several colors share the name already
}
if ($taken !== null && $taken !== $id) {
throw new InvalidArgumentException(sprintf(
'Name schon vergeben (%s); zum Ändern id angeben oder einen anderen Namen wählen',
$taken === '' ? 'mehrfach' : $taken
));
}
return $clean;
}
/** @throws InvalidArgumentException */
private static function folder(mixed $folder): string
{
$clean = is_string($folder) && strlen($folder) <= self::LABEL_MAX * 4 ? sanitize_text_field($folder) : null;
if ($clean === null || mb_strlen($clean) > self::LABEL_MAX || $clean === 'customizer') {
throw new InvalidArgumentException('Ordner: bis 100 Zeichen ohne HTML, nicht „customizer“');
}
return $clean;
}
/** @throws InvalidArgumentException */
private static function status(mixed $status): string
{
if (! is_string($status) || ! in_array($status, self::STATUSES, true)) {
throw new InvalidArgumentException('active oder inactive');
}
return $status;
}
/**
* @param array<array-key, mixed> $item
* @throws InvalidArgumentException
*/
private static function value(array $item): string
{
$color = $item['color'];
if (! is_string($color)) {
throw new InvalidArgumentException('Farbwert als Text erwartet');
}
$color = trim($color);
$problem = ColorValue::check($color);
if ($problem !== null) {
throw new InvalidArgumentException($problem);
}
return $color;
}
private function newId(ColorBook $book): string
{
do {
$id = ColorBook::newId($this->random);
} while ($book->entry($id) !== null);
return $id;
}
}