['padding-top', 0, 128], 'pr' => ['padding-right', 0, 128],
'pb' => ['padding-bottom', 0, 128], 'pl' => ['padding-left', 0, 128],
'mt' => ['margin-top', -128, 128], 'mr' => ['margin-right', -128, 128],
'mb' => ['margin-bottom', -128, 128], 'ml' => ['margin-left', -128, 128],
'size' => ['font-size', 8, 144],
'letter' => ['letter-spacing', -5, 24],
'line' => ['line-height', 8, 30],
];
private const TYPOGRAPHY = [
'weight-bold' => 'font-weight:700', 'weight-normal' => 'font-weight:400',
'slant-italic' => 'font-style:italic', 'slant-normal' => 'font-style:normal',
'strike-on' => 'text-decoration-line:line-through', 'strike-off' => 'text-decoration-line:none',
];
private const PREFIX = 'studio-style-';
private const IMAGE_SIZES = [
'cover' => 'cover', 'contain' => 'contain', 'stretch' => '100% 100%', 'original' => 'auto', 'tile' => 'auto',
];
private const IMAGE_POSITIONS = [
'c' => 'center', 'tl' => 'left top', 'tc' => 'center top', 'tr' => 'right top',
'ml' => 'left center', 'mr' => 'right center', 'bl' => 'left bottom', 'bc' => 'center bottom', 'br' => 'right bottom',
];
public static function encode(array $presentation): string
{
return $presentation === [] ? '{}' : Database::json($presentation);
}
public static function stylesheetUrl(): string
{
static $version;
$version ??= hash_file('xxh64', __FILE__);
return '/canvas-style.css?v=' . $version;
}
public static function normalize(mixed $input, array $roles): array
{
if (!is_array($input) || count($input) > count($roles) + 50) {
throw new RuntimeException('画布样式无效。');
}
$styles = [];
foreach ($input as $role => $style) {
if ($roles === self::PAGE && $role === 'breadcrumbLinks') {
if (!is_string($style)) {
throw new RuntimeException('面包屑无效。');
}
$styles[$role] = SiteDesign::linkText(SiteDesign::parseLinks($style));
continue;
}
if ($roles === self::PAGE && $role === 'heroEyebrow') {
if (!is_string($style) || mb_strlen($style) > 100) {
throw new RuntimeException('首屏眉题过长。');
}
$styles[$role] = $style;
continue;
}
if ($roles === self::PAGE && $role === 'heroHtml') {
if (!is_string($style) || strlen($style) > 300000) {
throw new RuntimeException('首屏 HTML 无效或过长。');
}
$styles[$role] = Html::sanitize($style);
continue;
}
if ((!in_array($role, $roles, true) && !($roles === self::PAGE && is_string($role)
&& preg_match('/^(?:action-[0-7]|(?:nav|crumb)-(?:[0-9]|1[0-9]))$/D', $role))) || !is_array($style)) {
throw new RuntimeException('画布样式无效。');
}
$classes = self::classList($style['classes'] ?? '');
$runs = $style['runs'] ?? [];
if (!is_array($runs) || !array_is_list($runs) || count($runs) > 1024) {
throw new RuntimeException('文字格式过多。');
}
$textLength = 0;
$cleanRuns = [];
foreach ($runs as $run) {
if (!is_array($run) || !array_is_list($run) || count($run) !== 2 || !is_string($run[0])
|| ($textLength += strlen($run[0])) > 2400 || !mb_check_encoding($run[0], 'UTF-8')) {
throw new RuntimeException('文字格式无效。');
}
$cleanRuns[] = [self::lineBreaks($run[0]), self::classList($run[1], textOnly: true)];
}
if ($classes !== '' || $cleanRuns !== []) {
$styles[$role] = ['classes' => $classes, 'runs' => $cleanRuns];
}
}
return $styles;
}
private static function classList(mixed $value, bool $textOnly = false): string
{
if (!is_string($value) || strlen($value) > 1800) {
throw new RuntimeException('画布样式无效。');
}
$classes = [];
foreach (explode(' ', $value) as $class) {
if (!str_starts_with($class, self::PREFIX)) {
continue;
}
$token = substr($class, strlen(self::PREFIX));
[$property, $size] = array_pad(explode('-', $token, 2), 2, '');
if (isset(self::TYPOGRAPHY[$token])) {
$classes[$property] = $class;
} elseif ($property === 'color' && ($size === 'theme' || preg_match('/^[a-f0-9]{6}$/D', $size))) {
$classes[$property] = $class;
} elseif (!$textOnly && $property === 'fill' && self::fill($size) !== null) {
$classes[$property] = $class;
} elseif (!$textOnly && $property === 'display' && in_array($size, ['block', 'inline', 'inline-block'], true)) {
$classes[$property] = $class;
} elseif ((!$textOnly || in_array($property, ['size', 'letter', 'line'], true)) && isset(self::PROPERTIES[$property])
&& preg_match('/^(?:0|-?[1-9]\d{0,2})$/D', $size)) {
[, $min, $max] = self::PROPERTIES[$property];
if ((int) $size >= $min && (int) $size <= $max) {
$classes[$property] = $class;
}
}
}
return implode(' ', $classes);
}
public static function classes(array $styles, string $role): string
{
$classes = $styles[$role]['classes'] ?? '';
return $classes === '' ? '' : ' ' . View::escape($classes);
}
public static function remapSlots(array $styles, string $prefix, array $indexes): array
{
$result = array_filter($styles, static fn (string $key): bool => !str_starts_with($key, $prefix), ARRAY_FILTER_USE_KEY);
foreach ($indexes as $next => $previous) {
if (isset($styles[$prefix . $previous])) {
$result[$prefix . $next] = $styles[$prefix . $previous];
}
}
return $result;
}
public static function lineBreaks(string $text): string
{
return str_replace(["\r\n", "\r"], "\n", $text);
}
public static function text(array $styles, string $role, string $plain): string
{
$plain = self::lineBreaks($plain);
$runs = $styles[$role]['runs'] ?? [];
if ($runs === [] || self::lineBreaks(trim(implode('', array_column($runs, 0)))) !== $plain) {
return str_replace("\n", '
', View::escape($plain));
}
$markup = '';
foreach ($runs as [$text, $class]) {
$escaped = str_replace("\n", '
', View::escape(self::lineBreaks($text)));
$markup .= $class === '' ? $escaped : '' . $escaped . '';
}
return $markup;
}
private static function fill(string $token): ?string
{
if (preg_match('/^solid-([a-f0-9]{6})$/D', $token, $parts)) {
return 'background:#' . $parts[1] . '!important';
}
if (preg_match('/^gradient-(0|[1-9]\d{0,2})-([a-f0-9]{6})-([a-f0-9]{6})$/D', $token, $parts) && (int) $parts[1] <= 360) {
return "background:linear-gradient({$parts[1]}deg,#{$parts[2]},#{$parts[3]})!important";
}
if (str_starts_with($token, 'gradient-')) {
return self::gradient(substr($token, strlen('gradient-')));
}
$size = 'cover';
$position = 'c';
if (preg_match('/^image-v2-([a-z]+)-([a-z]+)-([A-Za-z0-9_-]{1,1334})$/D', $token, $parts)) {
[, $size, $position, $encoded] = $parts;
} elseif (preg_match('/^image-([A-Za-z0-9_-]{1,1334})$/D', $token, $parts)) {
$encoded = $parts[1];
} else {
return null;
}
if (!isset(self::IMAGE_SIZES[$size], self::IMAGE_POSITIONS[$position])) {
return null;
}
$url = base64_decode(strtr($encoded, '-_', '+/'), true);
if ($url === false || strlen($url) > 1000 || !mb_check_encoding($url, 'UTF-8') || !Html::url($url, true)
|| rtrim(strtr(base64_encode($url), '+/', '-_'), '=') !== $encoded) {
return null;
}
// Quote the URL for CSS and keep the result safe inside a raw-text HTML style element.
$escaped = str_replace(['"', '<', '>'], ['\\22 ', '\\3c ', '\\3e '], $url);
$repeat = $size === 'tile' ? 'repeat' : 'no-repeat';
return 'background-image:url("' . $escaped . '")!important;background-position:' . self::IMAGE_POSITIONS[$position]
. '!important;background-size:' . self::IMAGE_SIZES[$size] . '!important;background-repeat:' . $repeat . '!important';
}
private static function gradient(string $token): ?string
{
$parts = explode('-', $token, 15);
$type = array_shift($parts);
if ($type === 'linear') {
$angle = array_shift($parts);
if ($angle === null || !preg_match('/^(0|[1-9]\d{0,2})$/D', $angle) || (int) $angle > 360) {
return null;
}
$direction = $angle . 'deg';
} elseif ($type === 'radial') {
$direction = 'circle at center';
} else {
return null;
}
if (count($parts) < 2 || count($parts) > 12) {
return null;
}
$last = 0;
$stops = [];
foreach ($parts as $stop) {
if (!preg_match('/^(0|[1-9]\d?|100)_([a-f0-9]{6})$/D', $stop, $color) || (int) $color[1] < $last) {
return null;
}
$last = (int) $color[1];
$stops[] = "#{$color[2]} {$last}%";
}
return "background:{$type}-gradient($direction," . implode(',', $stops) . ')!important';
}
public static function dynamicRules(string $markup): string
{
preg_match_all('/\bstudio-style-(color|fill)-([A-Za-z0-9_-]+)(?![\w-])/', $markup, $matches, PREG_SET_ORDER);
$css = '';
$seen = [];
foreach ($matches as [$class, $property, $value]) {
if (isset($seen[$class])) {
continue;
}
$seen[$class] = true;
if ($property === 'color') {
$rule = preg_match('/^[a-f0-9]{6}$/D', $value) ? "color:#{$value}!important" : null;
} else {
$rule = self::fill($value);
}
if ($rule !== null) {
$css .= ".$class" . '{' . $rule . "}\n";
}
}
return $css;
}
public static function stylesheet(): string
{
$css = '';
foreach (self::PROPERTIES as $key => $definition) {
[$property, $min, $max] = $definition;
for ($value = $min; $value <= $max; $value++) {
$length = $key === 'line' ? $value / 10 : $value . 'px';
$css .= '.' . self::PREFIX . "$key-$value{{$property}:{$length}!important}\n";
}
}
for ($width = self::MIN_MEDIA_SCALE; $width <= 100; $width++) {
$css .= ".studio-media-{$width}{--studio-media-factor:calc({$width} / 100)}\n";
}
foreach (self::TYPOGRAPHY as $key => $value) {
$css .= '.' . self::PREFIX . "$key{{$value}!important}\n";
}
return $css . 'span.studio-style-strike-off {display:inline-block}';
}
}