Add live canvas layers, element styles and undo history

This commit is contained in:
2026-11-23 19:36:55 +08:00
parent bd1890c0dd
commit 3e842aa35c
21 changed files with 906 additions and 104 deletions
+3
View File
@@ -32,6 +32,7 @@ php start.php start
## 页面与站点设计 ## 页面与站点设计
- 在「页面」新建空白草稿或从整页模板创建。画布支持编辑、媒体拖拽调整宽度、移动端预览、区块复制与删除。 - 在「页面」新建空白草稿或从整页模板创建。画布支持编辑、媒体拖拽调整宽度、移动端预览、区块复制与删除。
- 「图层」中可定位、移动或移除独立区块,保存页面后生效。选中元素可编辑四边的内外边距。选择一段文字后可修改字号、粗体、斜体和删除线。Enter 或 Shift+Enter 在原区块内换行。画布支持撤销与重做,快捷键为 Ctrl/⌘+Z 和 Ctrl/⌘+Shift+Z。
- 选中按钮后可复制。在「属性」中选择纯色填充、线框、下划线或无样式,并选择是否在新标签页打开。首屏支持最多八个按钮。 - 选中按钮后可复制。在「属性」中选择纯色填充、线框、下划线或无样式,并选择是否在新标签页打开。首屏支持最多八个按钮。
- 「站点设计」中可以保存多套页头、页脚和配色。选择布局模板后,可以勾选并排序标识、导航、按钮、文字、版权或用户区组件,填入各组件内容。页头和页脚可以设为站点默认。每页可覆盖这两个默认项、选择配色,或独立隐藏页头和页脚。 - 「站点设计」中可以保存多套页头、页脚和配色。选择布局模板后,可以勾选并排序标识、导航、按钮、文字、版权或用户区组件,填入各组件内容。页头和页脚可以设为站点默认。每页可覆盖这两个默认项、选择配色,或独立隐藏页头和页脚。
- 媒体库和媒体选择器只列出用户上传文件。编辑器图标、示例资产、字体、模板缩略图和产品标识随程序发布。 - 媒体库和媒体选择器只列出用户上传文件。编辑器图标、示例资产、字体、模板缩略图和产品标识随程序发布。
@@ -97,6 +98,8 @@ bin/update.sh v1.1.0 /srv/backups/pre-update.tar
从 v1.0.0 升级时,让执行迁移的进程能读到原先填写的 `LAYSITE_OAUTH_*` 值。升级会将这些密钥转存到 SQLite,成功后即可移除旧变量。若迁移时缺少某个旧值,在对应会员页头补填密钥即可启用登录。 从 v1.0.0 升级时,让执行迁移的进程能读到原先填写的 `LAYSITE_OAUTH_*` 值。升级会将这些密钥转存到 SQLite,成功后即可移除旧变量。若迁移时缺少某个旧值,在对应会员页头补填密钥即可启用登录。
从 v1.1.0 更新画布功能时,更新脚本会添加页面和区块的样式字段。手动更新源码后,运行 `php bin/install.php` 再启动 Webman。
## 生产反代 ## 生产反代
在 `.env` 配置 `LAYSITE_SITE_URL=https://example.com` 和 `LAYSITE_SECURE_COOKIES=1`。下列示例假定代理和 Webman 在同一主机。代理应以实际访客来源覆盖 `X-Real-IP`,并将项目文件、数据库和媒体存储保持在公开根目录之外。 在 `.env` 配置 `LAYSITE_SITE_URL=https://example.com` 和 `LAYSITE_SECURE_COOKIES=1`。下列示例假定代理和 Webman 在同一主机。代理应以实际访客来源覆盖 `X-Real-IP`,并将项目文件、数据库和媒体存储保持在公开根目录之外。
+1 -1
View File
@@ -1 +1 @@
1.1.0 1.2.0
+135
View File
@@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
namespace App\Content;
use RuntimeException;
final class CanvasStyle
{
public const PAGE = ['hero', 'heading', 'accent', 'lead', 'image', 'actions', 'navigation'];
public const SECTION = ['section', 'title', 'lead', 'body'];
private const PROPERTIES = [
'pt' => ['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],
];
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-';
public static function normalize(mixed $input, array $roles): array
{
if (!is_array($input) || count($input) > count($roles) + 28) {
throw new RuntimeException('画布样式无效。');
}
$styles = [];
foreach ($input as $role => $style) {
if ((!in_array($role, $roles, true) && !($roles === self::PAGE && is_string($role)
&& preg_match('/^(?:action-[0-7]|nav-(?:[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[] = [$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) > 320) {
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 ((!$textOnly || $property === 'size') && 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 text(array $styles, string $role, string $plain): string
{
$runs = $styles[$role]['runs'] ?? [];
if ($runs === [] || trim(implode('', array_column($runs, 0))) !== $plain) {
return str_replace(["\r\n", "\r", "\n"], '<br>', View::escape($plain));
}
$markup = '';
foreach ($runs as [$text, $class]) {
$escaped = str_replace("\n", '<br>', View::escape($text));
$markup .= $class === '' ? $escaped : '<span class="' . View::escape($class) . '">' . $escaped . '</span>';
}
return $markup;
}
public static function stylesheet(): string
{
$css = '';
foreach (self::PROPERTIES as $key => [$property, $min, $max]) {
for ($value = $min; $value <= $max; $value++) {
$css .= '.' . self::PREFIX . "$key-$value{{$property}:{$value}px!important}\n";
}
}
foreach (self::TYPOGRAPHY as $key => $value) {
$css .= '.' . self::PREFIX . "$key{{$value}!important}\n";
}
return $css . 'span.studio-style-strike-off {display:inline-block}';
}
}
+9 -1
View File
@@ -11,7 +11,7 @@ use Throwable;
final class Database final class Database
{ {
private const SCHEMA_VERSION = 2; private const SCHEMA_VERSION = 3;
// Avoid reusing a deleted ID that may still be open in an editing form. // Avoid reusing a deleted ID that may still be open in an editing form.
public const NEXT_ARTICLE_ID = 'MAX(COALESCE((SELECT MAX(id) FROM articles), 0), public const NEXT_ARTICLE_ID = 'MAX(COALESCE((SELECT MAX(id) FROM articles), 0),
COALESCE((SELECT MAX(article_id) FROM article_deletions), 0)) + 1'; COALESCE((SELECT MAX(article_id) FROM article_deletions), 0)) + 1';
@@ -54,6 +54,14 @@ final class Database
throw new RuntimeException('当前 SQLite 数据库需要更新版本的 LaySite。'); throw new RuntimeException('当前 SQLite 数据库需要更新版本的 LaySite。');
} }
$pdo->exec(file_get_contents($root . '/resources/schema.sql')); $pdo->exec(file_get_contents($root . '/resources/schema.sql'));
if ($version < 3) {
foreach (['pages', 'sections'] as $table) {
$columns = $pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll();
if (!in_array('presentation', array_column($columns, 'name'), true)) {
$pdo->exec("ALTER TABLE $table ADD COLUMN presentation TEXT NOT NULL DEFAULT '{}'");
}
}
}
$pdo->prepare('INSERT OR IGNORE INTO site_settings (id, payload) VALUES (1, ?)')->execute([self::json(['name' => '我的网站'])]); $pdo->prepare('INSERT OR IGNORE INTO site_settings (id, payload) VALUES (1, ?)')->execute([self::json(['name' => '我的网站'])]);
$pdo->prepare("INSERT OR IGNORE INTO pages $pdo->prepare("INSERT OR IGNORE INTO pages
(slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks) (slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
+6 -3
View File
@@ -16,11 +16,11 @@ final class Html
private const TAGS = [ private const TAGS = [
'a' => ['href', 'target', 'rel'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [], 'a' => ['href', 'target', 'rel'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [],
'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'], 'button' => [], 'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
'dl' => [], 'dt' => [], 'em' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [], 'dl' => [], 'dt' => [], 'em' => [], 'figure' => [], 'figcaption' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [],
'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'], 'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'],
'li' => [], 'ol' => [], 'p' => [], 'pre' => [], 'progress' => ['max', 'value'], 's' => [], 'li' => [], 'ol' => [], 'p' => [], 'pre' => [], 'progress' => ['max', 'value'], 's' => [],
'small' => [], 'source' => ['src', 'type'], 'span' => [], 'strong' => [], 'summary' => [], 'section' => [], 'small' => [], 'source' => ['src', 'type'], 'span' => [], 'strong' => [], 'summary' => [],
'table' => [], 'tbody' => [], 'td' => ['colspan', 'rowspan'], 'tfoot' => [], 'table' => [], 'tbody' => [], 'td' => ['colspan', 'rowspan'], 'tfoot' => [],
'th' => ['scope', 'colspan', 'rowspan'], 'thead' => [], 'tr' => [], 'ul' => [], 'th' => ['scope', 'colspan', 'rowspan'], 'thead' => [], 'tr' => [], 'ul' => [],
'video' => ['src', 'controls', 'muted', 'playsinline', 'poster', 'preload'], 'video' => ['src', 'controls', 'muted', 'playsinline', 'poster', 'preload'],
@@ -154,6 +154,9 @@ final class Html
$element->removeAttribute('rel'); $element->removeAttribute('rel');
} }
} }
if ($element->tagName === 'button') {
$element->setAttribute('type', 'button');
}
self::sanitizeChildren($element); self::sanitizeChildren($element);
} }
} }
+9 -2
View File
@@ -37,7 +37,11 @@ final class PageDraft
$key = $kind . '_id'; $key = $kind . '_id';
$page[$key] = array_key_exists($key, $input) ? DesignLibrary::selection($kind, $input[$key]) : ($page[$key] ?? null); $page[$key] = array_key_exists($key, $input) ? DesignLibrary::selection($kind, $input[$key]) : ($page[$key] ?? null);
} }
$page['actions'] = Buttons::validate($input['actions'] ?? $page['actions']); $actions = Buttons::validate($input['actions'] ?? $page['actions']);
if (array_key_exists('actions', $input) && $actions !== Buttons::validate($page['actions'])) {
$page['presentation'] = CanvasStyle::remapSlots($page['presentation'] ?? [], 'action-', []);
}
$page['actions'] = $actions;
if (array_key_exists('visibility', $input)) { if (array_key_exists('visibility', $input)) {
if (!is_array($input['visibility'])) { if (!is_array($input['visibility'])) {
throw new RuntimeException('页面显示选项无效。'); throw new RuntimeException('页面显示选项无效。');
@@ -55,8 +59,11 @@ final class PageDraft
$page['sections'] = self::sections($input['sections']); $page['sections'] = self::sections($input['sections']);
if (!array_key_exists('actions', $input)) { if (!array_key_exists('actions', $input)) {
$removed = array_map(static fn (string $key): string => '#' . $key, array_diff($oldKeys, array_column($page['sections'], 'key'))); $removed = array_map(static fn (string $key): string => '#' . $key, array_diff($oldKeys, array_column($page['sections'], 'key')));
$page['actions'] = array_values(array_filter($page['actions'], static fn (array $button): bool => !in_array($button[0], $removed, true))); $kept = array_filter($page['actions'], static fn (array $button): bool => !in_array($button[0], $removed, true));
$page['presentation'] = CanvasStyle::remapSlots($page['presentation'] ?? [], 'action-', array_keys($kept));
$page['actions'] = array_values($kept);
} }
$page['presentation'] = CanvasStyle::remapSlots($page['presentation'] ?? [], 'nav-', []);
$page['quicklinks'] = array_map(static fn (array $section): array => ['#' . $section['key'], $section['title']], array_slice($page['sections'], 0, 20)); $page['quicklinks'] = array_map(static fn (array $section): array => ['#' . $section['key'], $section['title']], array_slice($page['sections'], 0, 20));
} }
+43 -18
View File
@@ -62,7 +62,7 @@ final class Repository
if (!$page) { if (!$page) {
return null; return null;
} }
foreach (['actions', 'quicklinks', 'alignments', 'visibility'] as $key) { foreach (['actions', 'quicklinks', 'alignments', 'visibility', 'presentation'] as $key) {
$page[$key] = json_decode($page[$key], true, flags: JSON_THROW_ON_ERROR); $page[$key] = json_decode($page[$key], true, flags: JSON_THROW_ON_ERROR);
} }
$query = $this->pdo->prepare('SELECT * FROM sections WHERE page_slug = ? ORDER BY position, key'); $query = $this->pdo->prepare('SELECT * FROM sections WHERE page_slug = ? ORDER BY position, key');
@@ -84,15 +84,16 @@ final class Repository
WHERE pages.slug = ? AND pages.status = 'published' AND sections.key = ? AND sections.feed IS NOT NULL", [$page, $key]); WHERE pages.slug = ? AND pages.status = 'published' AND sections.key = ? AND sections.feed IS NOT NULL", [$page, $key]);
} }
public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false): void public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false, ?array $sectionOrder = null): void
{ {
Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections): void { Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections, $sectionOrder): void {
$query = $pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?, $query = $pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?,
image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, visibility = ?, header_id = ?, footer_id = ?, palette_id = ?, status = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?'); image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, visibility = ?, header_id = ?, footer_id = ?, palette_id = ?, status = ?, updated_at = ?, presentation = COALESCE(?, presentation), version = version + 1 WHERE slug = ? AND version = ?');
$query->execute([ $query->execute([
$data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'], $data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'],
$data['image'], $data['alt'], $data['image_scale'], Database::json($data['alignments']), Database::json($data['actions']), Database::json($data['quicklinks']), $data['image'], $data['alt'], $data['image_scale'], Database::json($data['alignments']), Database::json($data['actions']), Database::json($data['quicklinks']),
Database::json($data['visibility']), $data['header_id'], $data['footer_id'], $data['palette_id'], $data['status'], self::now(), $slug, $version, Database::json($data['visibility']), $data['header_id'], $data['footer_id'], $data['palette_id'], $data['status'], self::now(),
isset($data['presentation']) ? Database::json($data['presentation']) : null, $slug, $version,
]); ]);
self::checkVersion($query->rowCount()); self::checkVersion($query->rowCount());
if ($replaceDraftSections) { if ($replaceDraftSections) {
@@ -107,6 +108,9 @@ final class Repository
self::updateSection($pdo, $slug, $section['key'], $section, $section['version']); self::updateSection($pdo, $slug, $section['key'], $section, $section['version']);
} }
} }
if ($sectionOrder !== null) {
self::writeSectionOrder($pdo, $slug, $sectionOrder);
}
}); });
} }
@@ -120,9 +124,9 @@ final class Repository
private static function updateSection(PDO $pdo, string $page, string $key, array $data, int $version): void private static function updateSection(PDO $pdo, string $page, string $key, array $data, int $version): void
{ {
$query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, feed = ?, alignments = COALESCE(?, alignments), version = version + 1 $query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, feed = ?, alignments = COALESCE(?, alignments), presentation = COALESCE(?, presentation), version = version + 1
WHERE page_slug = ? AND key = ? AND version = ?'); WHERE page_slug = ? AND key = ? AND version = ?');
$query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $data['feed'] ?? null, $data['alignments'] ?? null, $page, $key, $version]); $query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $data['feed'] ?? null, $data['alignments'] ?? null, $data['presentation'] ?? null, $page, $key, $version]);
self::checkVersion($query->rowCount()); self::checkVersion($query->rowCount());
} }
@@ -136,9 +140,9 @@ final class Repository
private static function insertSection(PDO $pdo, string $page, string $key, array $data): void private static function insertSection(PDO $pdo, string $page, string $key, array $data): void
{ {
$query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, alignments, position) $query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, alignments, presentation, position)
SELECT ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?'); SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?');
$query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $data['alignments'] ?? '{}', $page]); $query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $data['alignments'] ?? '{}', $data['presentation'] ?? '{}', $page]);
if ($query->rowCount() !== 1) { if ($query->rowCount() !== 1) {
throw new RuntimeException('此区块锚点已被使用。'); throw new RuntimeException('此区块锚点已被使用。');
} }
@@ -149,10 +153,20 @@ final class Repository
$query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?'); $query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?');
$query->execute([$page, $key, $version]); $query->execute([$page, $key, $version]);
self::checkVersion($query->rowCount()); self::checkVersion($query->rowCount());
$pdo->prepare("UPDATE pages SET $query = $pdo->prepare('SELECT actions, quicklinks, presentation FROM pages WHERE slug = ?');
quicklinks = (SELECT json_group_array(json(value)) FROM json_each(quicklinks) WHERE json_extract(value, '$[0]') <> :anchor), $query->execute([$page]);
actions = (SELECT json_group_array(json(value)) FROM json_each(actions) WHERE json_extract(value, '$[0]') <> :anchor) $row = $query->fetch();
WHERE slug = :slug")->execute(['anchor' => '#' . $key, 'slug' => $page]); $styles = json_decode($row['presentation'], true, flags: JSON_THROW_ON_ERROR);
foreach (['actions' => 'action-', 'quicklinks' => 'nav-'] as $column => $prefix) {
$links = json_decode($row[$column], true, flags: JSON_THROW_ON_ERROR);
$kept = array_filter($links, static fn (array $link): bool => $link[0] !== '#' . $key);
if (count($kept) !== count($links)) {
$row[$column] = Database::json(array_values($kept));
$styles = CanvasStyle::remapSlots($styles, $prefix, array_keys($kept));
}
}
$pdo->prepare('UPDATE pages SET actions = ?, quicklinks = ?, presentation = ? WHERE slug = ?')
->execute([$row['actions'], $row['quicklinks'], Database::json($styles), $page]);
} }
public function arrangeSection(string $page, string $key, string $operation, int $version, int $pageVersion): void public function arrangeSection(string $page, string $key, string $operation, int $version, int $pageVersion): void
@@ -182,14 +196,25 @@ final class Repository
return; return;
} }
[$keys[$index], $keys[$other]] = [$keys[$other], $keys[$index]]; [$keys[$index], $keys[$other]] = [$keys[$other], $keys[$index]];
$query = $pdo->prepare('UPDATE sections SET position = ? WHERE page_slug = ? AND key = ?'); self::writeSectionOrder($pdo, $page, $keys);
foreach ($keys as $position => $section) {
$query->execute([$position, $page, $section]);
}
self::touchPage($pdo, $page, structureChanged: true); self::touchPage($pdo, $page, structureChanged: true);
}); });
} }
private static function writeSectionOrder(PDO $pdo, string $slug, array $keys): void
{
$query = $pdo->prepare("SELECT key FROM sections WHERE page_slug = ? AND style <> 'hero-links'");
$query->execute([$slug]);
$available = $query->fetchAll(PDO::FETCH_COLUMN);
if (count($available) !== count($keys) || array_diff($available, $keys)) {
throw new RuntimeException('区块顺序已变更,请重新打开编辑页。');
}
$query = $pdo->prepare('UPDATE sections SET position = ? WHERE page_slug = ? AND key = ?');
foreach ($keys as $position => $key) {
$query->execute([$position, $slug, $key]);
}
}
private static function touchPage(PDO $pdo, string $slug, bool $structureChanged = false): void private static function touchPage(PDO $pdo, string $slug, bool $structureChanged = false): void
{ {
$revision = $structureChanged ? ', version = version + 1' : ''; $revision = $structureChanged ? ', version = version + 1' : '';
+2
View File
@@ -185,6 +185,7 @@ final class SiteBackup
$row['quicklinks'] = Database::json(Buttons::validate(self::decode($row['quicklinks'] ?? '[]'), 20)); $row['quicklinks'] = Database::json(Buttons::validate(self::decode($row['quicklinks'] ?? '[]'), 20));
$row['visibility'] = Database::json(array_intersect_key(self::decode($row['visibility'] ?? '{}'), array_flip(['header', 'hero', 'footer']))); $row['visibility'] = Database::json(array_intersect_key(self::decode($row['visibility'] ?? '{}'), array_flip(['header', 'hero', 'footer'])));
$row['alignments'] = Database::json(self::decode($row['alignments'] ?? '{}')); $row['alignments'] = Database::json(self::decode($row['alignments'] ?? '{}'));
$row['presentation'] = Database::json(CanvasStyle::normalize(self::decode($row['presentation'] ?? '{}'), CanvasStyle::PAGE));
if (($row['theme'] ?? '') !== '' && !isset(PageTemplates::groups()[$row['theme']])) { if (($row['theme'] ?? '') !== '' && !isset(PageTemplates::groups()[$row['theme']])) {
$row['theme'] = ''; $row['theme'] = '';
} }
@@ -199,6 +200,7 @@ final class SiteBackup
throw new RuntimeException('备份包含未知区块样式。'); throw new RuntimeException('备份包含未知区块样式。');
} }
$row['body'] = Html::sanitize($row['body'] ?? ''); $row['body'] = Html::sanitize($row['body'] ?? '');
$row['presentation'] = Database::json(CanvasStyle::normalize(self::decode($row['presentation'] ?? '{}'), CanvasStyle::SECTION));
if (isset($row['feed'])) { if (isset($row['feed'])) {
$feed = self::decode($row['feed']); $feed = self::decode($row['feed']);
if (!in_array($feed['mode'] ?? '', ['merged', 'tabs', 'network', 'catalog'], true) if (!in_array($feed['mode'] ?? '', ['merged', 'tabs', 'network', 'catalog'], true)
+19 -2
View File
@@ -6,6 +6,7 @@ namespace App\Controller;
use App\Content\BlockTemplates; use App\Content\BlockTemplates;
use App\Content\Buttons; use App\Content\Buttons;
use App\Content\CanvasStyle;
use App\Content\DesignLibrary; use App\Content\DesignLibrary;
use App\Content\Database; use App\Content\Database;
use App\Content\Html; use App\Content\Html;
@@ -285,6 +286,9 @@ class AdminController
$data['alignments'] = $request->post('alignments') === null ? $page['alignments'] $data['alignments'] = $request->post('alignments') === null ? $page['alignments']
: $this->alignmentMap(json_decode($this->input($request, 'alignments'), true), ['heading', 'lead', 'actions', 'image']); : $this->alignmentMap(json_decode($this->input($request, 'alignments'), true), ['heading', 'lead', 'actions', 'image']);
$page['alignments'] = $data['alignments']; $page['alignments'] = $data['alignments'];
$data['presentation'] = $request->post('canvas_presentation') === null ? $page['presentation']
: CanvasStyle::normalize(json_decode($this->input($request, 'canvas_presentation'), true), CanvasStyle::PAGE);
$page['presentation'] = $data['presentation'];
$data['quicklinks'] = $request->post('quicklinks') === null ? $page['quicklinks'] : SiteDesign::parseLinks($this->input($request, 'quicklinks')); $data['quicklinks'] = $request->post('quicklinks') === null ? $page['quicklinks'] : SiteDesign::parseLinks($this->input($request, 'quicklinks'));
if ($data['name'] === '' || mb_strlen($data['name']) > 100 || !in_array($data['status'], ['draft', 'published'], true) if ($data['name'] === '' || mb_strlen($data['name']) > 100 || !in_array($data['status'], ['draft', 'published'], true)
|| $data['title'] === '' || mb_strlen($data['title']) > 160 || || $data['title'] === '' || mb_strlen($data['title']) > 160 ||
@@ -296,7 +300,15 @@ class AdminController
throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。'); throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。');
} }
$sections = $this->canvasSections($request->post('canvas_sections', ''), $page['sections'], $repo->categories()); $sections = $this->canvasSections($request->post('canvas_sections', ''), $page['sections'], $repo->categories());
$repo->savePage($slug, $data, $this->version($request), $sections); $order = $request->post('canvas_order', '');
if ($order !== '') {
$order = is_string($order) ? json_decode($order, true) : null;
if (!is_array($order) || !array_is_list($order) || count($order) > count($page['sections']) + 50
|| count(array_filter($order, 'is_string')) !== count($order)) {
throw new RuntimeException('区块顺序无效。');
}
}
$repo->savePage($slug, $data, $this->version($request), $sections, sectionOrder: $order === '' ? null : $order);
return $this->success($request, '/admin/pages/' . $slug . '?saved=1'); return $this->success($request, '/admin/pages/' . $slug . '?saved=1');
} catch (RuntimeException $exception) { } catch (RuntimeException $exception) {
@@ -366,10 +378,12 @@ class AdminController
$version = $change['version'] ?? null; $version = $change['version'] ?? null;
$fields = $change['fields'] ?? []; $fields = $change['fields'] ?? [];
$alignments = $change['alignments'] ?? null; $alignments = $change['alignments'] ?? null;
$presentation = $change['presentation'] ?? null;
$feed = $change['feed'] ?? null; $feed = $change['feed'] ?? null;
$delete = ($change['delete'] ?? false) === true; $delete = ($change['delete'] ?? false) === true;
$isNew = is_array($change) && array_key_exists('version', $change) && $version === null; $isNew = is_array($change) && array_key_exists('version', $change) && $version === null;
if (!is_string($key) || isset($updates[$key]) || !is_array($fields) || (!$delete && $fields === [] && $alignments === null && $feed === null) if (!is_string($key) || isset($updates[$key]) || !is_array($fields)
|| (!$delete && $fields === [] && $alignments === null && $presentation === null && $feed === null)
|| ($isNew ? (isset($available[$key]) || !preg_match('/^block-[a-f0-9]{32}$/D', $key)) || ($isNew ? (isset($available[$key]) || !preg_match('/^block-[a-f0-9]{32}$/D', $key))
: (!isset($available[$key]) || !is_int($version) || $version !== (int) $available[$key]['version']))) { : (!isset($available[$key]) || !is_int($version) || $version !== (int) $available[$key]['version']))) {
throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。'); throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。');
@@ -419,6 +433,9 @@ class AdminController
if ($alignments !== null) { if ($alignments !== null) {
$section['alignments'] = Database::json($this->alignmentMap($alignments, ['title', 'lead'])); $section['alignments'] = Database::json($this->alignmentMap($alignments, ['title', 'lead']));
} }
if ($presentation !== null) {
$section['presentation'] = Database::json(CanvasStyle::normalize($presentation, CanvasStyle::SECTION));
}
$this->checkSection($section, $section['style']); $this->checkSection($section, $section['style']);
if (isset($fields['body'])) { if (isset($fields['body'])) {
$section['body'] = Html::sanitize($section['body']); $section['body'] = Html::sanitize($section['body']);
+10
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Controller; namespace App\Controller;
use App\Content\Assets; use App\Content\Assets;
use App\Content\CanvasStyle;
use App\Content\Html; use App\Content\Html;
use App\Content\Repository; use App\Content\Repository;
use App\Content\View; use App\Content\View;
@@ -223,6 +224,15 @@ final class SiteController
return View::redirect(Assets::DEFAULT_ICON, 301); return View::redirect(Assets::DEFAULT_ICON, 301);
} }
public function canvasStyle(Request $request): Response
{
static $css;
$css ??= CanvasStyle::stylesheet();
return new Response(200, ['Content-Type' => 'text/css; charset=utf-8',
'Cache-Control' => 'public, max-age=3600', 'X-Content-Type-Options' => 'nosniff'], $css);
}
public function missing(Request $request): Response public function missing(Request $request): Response
{ {
$path = $request->path(); $path = $request->path();
+29 -2
View File
@@ -41,11 +41,20 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
<div class="editor-toolbar studio-canvas-toolbar" data-canvas-toolbar hidden aria-label="正文工具"> <div class="editor-toolbar studio-canvas-toolbar" data-canvas-toolbar hidden aria-label="正文工具">
<div> <div>
<button type="button" data-canvas-command="heading">小标题</button> <button type="button" data-canvas-command="heading">小标题</button>
<button type="button" data-canvas-command="bold">粗体</button>
<button type="button" data-canvas-command="list">列表</button> <button type="button" data-canvas-command="list">列表</button>
<button type="button" data-canvas-command="link">插入链接</button> <button type="button" data-canvas-command="link">插入链接</button>
<button type="button" data-canvas-command="media">插入媒体</button> <button type="button" data-canvas-command="media">插入媒体</button>
</div> </div>
<div class="canvas-format-tools" role="group" aria-label="文字格式">
<label>字号 <input type="number" data-canvas-font-size min="8" max="144" step="1" placeholder="px" disabled></label>
<button type="button" data-canvas-format="weight" aria-label="加粗" title="加粗" aria-pressed="false" disabled><strong>B</strong></button>
<button type="button" data-canvas-format="slant" aria-label="斜体" title="斜体" aria-pressed="false" disabled><em>I</em></button>
<button type="button" data-canvas-format="strike" aria-label="删除线" title="删除线" aria-pressed="false" disabled><s>S</s></button>
</div>
<div role="group" aria-label="画布历史">
<button type="button" data-canvas-history="undo" title="撤销(Ctrl/⌘ Z)" disabled>撤销</button>
<button type="button" data-canvas-history="redo" title="重做(Ctrl/⌘ Shift Z)" disabled>重做</button>
</div>
<button class="button button-primary" form="studio-page-settings" type="submit">保存页面</button> <button class="button button-primary" form="studio-page-settings" type="submit">保存页面</button>
</div> </div>
<div class="studio-frame-window"> <div class="studio-frame-window">
@@ -56,7 +65,7 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
<button type="button" data-align="<?= $value ?>" aria-pressed="false" aria-label="<?= $label ?>" title="<?= $label ?>"><?= View::fragment('studio-icon', ['icon' => $value]) ?></button> <button type="button" data-align="<?= $value ?>" aria-pressed="false" aria-label="<?= $label ?>" title="<?= $label ?>"><?= View::fragment('studio-icon', ['icon' => $value]) ?></button>
<?php endforeach ?> <?php endforeach ?>
</div> </div>
<?php foreach (['module-settings' => ['settings', '模块设置'], 'properties' => ['edit', '属性'], 'copy' => ['copy', '复制'], 'delete' => ['delete', '删除']] as $action => [$icon, $label]): ?> <?php foreach (['module-settings' => ['settings', '模块设置'], 'properties' => ['edit', '属性'], 'parent' => ['parent', '选择父元素'], 'spacing' => ['spacing', '内外边距'], 'copy' => ['copy', '复制'], 'delete' => ['delete', '删除']] as $action => [$icon, $label]): ?>
<button type="button" data-element-<?= $action ?> aria-label="<?= $label ?>" title="<?= $label ?>"><?= View::fragment('studio-icon', compact('icon')) ?></button> <button type="button" data-element-<?= $action ?> aria-label="<?= $label ?>" title="<?= $label ?>"><?= View::fragment('studio-icon', compact('icon')) ?></button>
<?php endforeach ?> <?php endforeach ?>
</div> </div>
@@ -68,6 +77,22 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
</div> </div>
</div> </div>
<p class="field-note studio-canvas-status" data-canvas-status role="status"></p> <p class="field-note studio-canvas-status" data-canvas-status role="status"></p>
<dialog class="media-picker" data-canvas-spacing aria-labelledby="canvas-spacing-title">
<div class="admin-heading compact"><h2 id="canvas-spacing-title">元素间距</h2></div>
<form class="admin-form" method="dialog">
<?php foreach (['p' => ['内边距', 0], 'm' => ['外边距', -128]] as $prefix => [$label, $min]): ?>
<fieldset class="admin-options canvas-spacing-fields"><legend><?= $label ?>(px)</legend>
<?php foreach (['t' => '上', 'r' => '右', 'b' => '下', 'l' => '左'] as $side => $direction): ?>
<label><?= $direction ?><input name="<?= $prefix . $side ?>" type="number" min="<?= $min ?>" max="128" step="1" placeholder="默认"></label>
<?php endforeach ?>
</fieldset>
<?php endforeach ?>
<div class="actions">
<button type="submit" class="button button-primary">应用</button>
<button type="button" class="button button-outline" data-spacing-close>取消</button>
</div>
</form>
</dialog>
<dialog class="media-picker canvas-properties" data-canvas-properties aria-labelledby="canvas-properties-heading"> <dialog class="media-picker canvas-properties" data-canvas-properties aria-labelledby="canvas-properties-heading">
<div class="admin-heading compact"><h2 id="canvas-properties-heading" data-property-heading>编辑属性</h2></div> <div class="admin-heading compact"><h2 id="canvas-properties-heading" data-property-heading>编辑属性</h2></div>
<form class="admin-form" method="dialog"> <form class="admin-form" method="dialog">
@@ -114,6 +139,8 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
<input type="hidden" name="csrf" value="<?= $e($token) ?>"> <input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($page['version']) ?>"> <input type="hidden" name="version" value="<?= $e($page['version']) ?>">
<input type="hidden" name="canvas_sections" value=""> <input type="hidden" name="canvas_sections" value="">
<input type="hidden" name="canvas_order" value="">
<input type="hidden" name="canvas_presentation" value="<?= $e(Database::json($page['presentation'])) ?>">
<input type="hidden" name="alignments" value="<?= $e(Database::json($page['alignments'])) ?>"> <input type="hidden" name="alignments" value="<?= $e(Database::json($page['alignments'])) ?>">
<details class="studio-hero-settings"> <details class="studio-hero-settings">
<summary>首屏与目录</summary> <summary>首屏与目录</summary>
+1
View File
@@ -43,6 +43,7 @@ $showFooter = $page['visibility']['footer'] ?? true;
<?php endif ?> <?php endif ?>
<meta name="twitter:card" content="summary_large_image"> <meta name="twitter:card" content="summary_large_image">
<link rel="stylesheet" href="/assets/site.css"> <link rel="stylesheet" href="/assets/site.css">
<?php if (!empty($canvas) || str_contains($content, 'studio-style-')): ?><link rel="stylesheet" href="/canvas-style.css"><?php endif ?>
<?php if ($theme !== ''): ?><link rel="stylesheet" href="/assets/page-themes.css"><?php endif ?> <?php if ($theme !== ''): ?><link rel="stylesheet" href="/assets/page-themes.css"><?php endif ?>
<?php if ($palette): ?><link rel="stylesheet" data-page-palette href="/palette/<?= $e($palette['id']) ?>.css?v=<?= $e($palette['version']) ?>"><?php endif ?> <?php if ($palette): ?><link rel="stylesheet" data-page-palette href="/palette/<?= $e($palette['id']) ?>.css?v=<?= $e($palette['version']) ?>"><?php endif ?>
<script src="/assets/jquery-4.0.0.min.js" defer></script> <script src="/assets/jquery-4.0.0.min.js" defer></script>
+17 -11
View File
@@ -1,6 +1,6 @@
<?php <?php
use App\Content\Buttons; use App\Content\Buttons;
use App\Content\CanvasStyle;
use App\Content\View; use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
@@ -8,12 +8,16 @@ $home = $page['slug'] === 'home';
$showHero = $page['visibility']['hero'] ?? true; $showHero = $page['visibility']['hero'] ?? true;
$heroLinks = array_filter($page['sections'], static fn (array $section): bool => $section['style'] === 'hero-links'); $heroLinks = array_filter($page['sections'], static fn (array $section): bool => $section['style'] === 'hero-links');
$alignments = $page['alignments']; $alignments = $page['alignments'];
$presentation = $page['presentation'] ?? [];
$style = static fn (string $role): string => CanvasStyle::classes($presentation, $role);
$text = static fn (string $role, string $value): string => CanvasStyle::text($presentation, $role, $value);
$styleField = static fn (string $role): string => $canvas ? ' data-studio-style-field="' . $role . '"' : '';
$alignField = static fn (string $name): string => $canvas ? ' data-studio-align-field="' . $name . '"' : ''; $alignField = static fn (string $name): string => $canvas ? ' data-studio-align-field="' . $name . '"' : '';
$field = static fn (string $name): string => $canvas ? ' data-studio-field="' . $name . '"' : ''; $field = static fn (string $name): string => $canvas ? ' data-studio-field="' . $name . '"' : '';
?> ?>
<?php if (!$showHero && !$canvas): ?><h1 class="sr-only"><?= $e($page['name']) ?></h1><?php endif ?> <?php if (!$showHero && !$canvas): ?><h1 class="sr-only"><?= $e($page['name']) ?></h1><?php endif ?>
<?php if ($showHero || $canvas || $heroLinks): ?> <?php if ($showHero || $canvas || $heroLinks): ?>
<section class="hero hero-<?= $e($page['slug']) ?>" id="home" data-enter> <section class="hero hero-<?= $e($page['slug']) ?><?= $style('hero') ?>" id="home" data-enter<?= $styleField('hero') ?>>
<?php if ($showHero || $canvas): ?> <?php if ($showHero || $canvas): ?>
<div class="wrap hero-inner<?= $page['image'] === '' ? ' hero-text-only' : '' ?>"<?= $canvas ? ' data-studio-hero-content' : '' ?><?= $showHero ? '' : ' hidden' ?>> <div class="wrap hero-inner<?= $page['image'] === '' ? ' hero-text-only' : '' ?>"<?= $canvas ? ' data-studio-hero-content' : '' ?><?= $showHero ? '' : ' hidden' ?>>
<div class="hero-copy"> <div class="hero-copy">
@@ -32,16 +36,17 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' .
<?php else: ?> <?php else: ?>
<p class="overline hero-label"><?= $e($site['name']) ?></p> <p class="overline hero-label"><?= $e($site['name']) ?></p>
<?php endif ?> <?php endif ?>
<h1<?= isset($alignments['heading']) ? ' class="' . trim(View::alignmentClass($alignments['heading'])) . '"' : '' ?><?= $alignField('heading') ?>><span class="hero-heading-primary"<?= $field('heading') ?>><?= $e($page['heading']) ?></span><?php if ($canvas): ?><span class="studio-accent"<?= $field('accent') ?>><?= $e($page['accent']) ?></span><?php elseif ($page['accent'] !== ''): ?><br><span><?= $e($page['accent']) ?></span><?php endif ?></h1> <h1<?= isset($alignments['heading']) ? ' class="' . trim(View::alignmentClass($alignments['heading'])) . '"' : '' ?><?= $alignField('heading') ?>><span class="hero-heading-primary<?= $style('heading') ?>"<?= $field('heading') ?><?= $styleField('heading') ?>><?= $text('heading', $page['heading']) ?></span><?php if ($canvas): ?><span class="studio-accent<?= $style('accent') ?>"<?= $field('accent') ?><?= $styleField('accent') ?>><?= $text('accent', $page['accent']) ?></span><?php elseif ($page['accent'] !== ''): ?><br><span class="<?= trim($style('accent')) ?>"><?= $text('accent', $page['accent']) ?></span><?php endif ?></h1>
<p class="hero-lead<?= View::alignmentClass($alignments['lead'] ?? null) ?>"<?= $field('lead') ?><?= $alignField('lead') ?>><?= $e($page['lead']) ?></p> <p class="hero-lead<?= View::alignmentClass($alignments['lead'] ?? null) ?><?= $style('lead') ?>"<?= $field('lead') ?><?= $alignField('lead') ?><?= $styleField('lead') ?>><?= $text('lead', $page['lead']) ?></p>
<div class="actions hero-actions<?= View::alignmentClass($alignments['actions'] ?? null) ?>"<?= $alignField('actions') ?>> <div class="actions hero-actions<?= View::alignmentClass($alignments['actions'] ?? null) ?><?= $style('actions') ?>"<?= $alignField('actions') ?><?= $styleField('actions') ?>>
<?php foreach (Buttons::validate($page['actions']) as $index => [$url, $label, $style, $blank]): ?> <?php foreach (Buttons::validate($page['actions']) as $index => [$url, $label, $buttonStyle, $blank]): ?>
<a class="<?= $e(Buttons::css($style)) ?>" href="<?= $e($url) ?>"<?= Buttons::target($blank) ?><?= $canvas ? ' data-studio-action="' . $index . '"' : '' ?>><?= $e($label) ?></a> <?php $role = 'action-' . $index; ?>
<a class="<?= $e(Buttons::css($buttonStyle)) ?><?= $style($role) ?>" href="<?= $e($url) ?>"<?= Buttons::target($blank) ?><?= $canvas ? ' data-studio-action="' . $index . '"' : '' ?><?= $styleField($role) ?>><?= $text($role, $label) ?></a>
<?php endforeach ?> <?php endforeach ?>
</div> </div>
</div> </div>
<?php if ($canvas || $page['image'] !== ''): ?> <?php if ($canvas || $page['image'] !== ''): ?>
<div class="hero-visual app-frame<?= $page['image_scale'] ? ' studio-media-' . $e($page['image_scale']) : '' ?><?= View::alignmentClass($alignments['image'] ?? null) ?>" data-visual<?= $alignField('image') ?><?= $page['image'] === '' ? ' hidden' : '' ?>> <div class="hero-visual app-frame<?= $page['image_scale'] ? ' studio-media-' . $e($page['image_scale']) : '' ?><?= View::alignmentClass($alignments['image'] ?? null) ?><?= $style('image') ?>" data-visual<?= $alignField('image') ?><?= $styleField('image') ?><?= $page['image'] === '' ? ' hidden' : '' ?>>
<img<?= $page['image'] === '' ? '' : ' src="' . $e($page['image']) . '"' ?> alt="<?= $e($page['alt']) ?>" width="1448" height="1086" fetchpriority="high"<?= $canvas ? ' data-studio-hero-image' : '' ?>> <img<?= $page['image'] === '' ? '' : ' src="' . $e($page['image']) . '"' ?> alt="<?= $e($page['alt']) ?>" width="1448" height="1086" fetchpriority="high"<?= $canvas ? ' data-studio-hero-image' : '' ?>>
</div> </div>
<?php endif ?> <?php endif ?>
@@ -53,10 +58,11 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' .
</section> </section>
<?php endif ?> <?php endif ?>
<?php if ($canvas || $page['quicklinks']): ?> <?php if ($canvas || $page['quicklinks']): ?>
<nav class="section-nav" aria-label="本页目录"<?= $canvas ? ' data-studio-navigation' : '' ?><?= !$page['quicklinks'] ? ' hidden' : '' ?>> <nav class="section-nav<?= $style('navigation') ?>" aria-label="本页目录"<?= $canvas ? ' data-studio-navigation' : '' ?><?= $styleField('navigation') ?><?= !$page['quicklinks'] ? ' hidden' : '' ?>>
<div class="wrap section-nav-inner"> <div class="wrap section-nav-inner">
<?php foreach ($page['quicklinks'] as [$url, $label]): ?> <?php foreach ($page['quicklinks'] as $index => [$url, $label]): ?>
<a href="<?= $e($url) ?>"><?= $e($label) ?></a> <?php $role = 'nav-' . $index; ?>
<a class="<?= trim($style($role)) ?>" href="<?= $e($url) ?>"<?= $styleField($role) ?>><?= $text($role, $label) ?></a>
<?php endforeach ?> <?php endforeach ?>
</div> </div>
</nav> </nav>
+10 -6
View File
@@ -1,19 +1,23 @@
<?php <?php
use App\Content\CanvasStyle;
use App\Content\View; use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
$canvas ??= false; $canvas ??= false;
$body = $section['body']; $body = $section['body'];
$dynamic = isset($section['feed']); $dynamic = isset($section['feed']);
$presentation = json_decode($section['presentation'] ?? '{}', true, flags: JSON_THROW_ON_ERROR);
$style = static fn (string $role): string => CanvasStyle::classes($presentation, $role);
$text = static fn (string $role): string => CanvasStyle::text($presentation, $role, $section[$role]);
$studio = $canvas ? ' data-studio-section="' . $e($section['version']) . '" data-studio-source="' . $e(base64_encode($section['body'])) . '"' : ''; $studio = $canvas ? ' data-studio-section="' . $e($section['version']) . '" data-studio-source="' . $e(base64_encode($section['body'])) . '"' : '';
if ($canvas && $dynamic) { if ($canvas && $dynamic) {
$studio .= ' data-studio-dynamic data-studio-feed="' . $e($section['feed']) . '" tabindex="0"'; $studio .= ' data-studio-dynamic data-studio-feed="' . $e($section['feed']) . '" tabindex="0"';
} }
if ($section['style'] === 'hero-links'): if ($section['style'] === 'hero-links'):
?> ?>
<div class="wrap hero-directory-slot" id="<?= $e($section['key']) ?>"<?= $studio ?>> <div class="wrap hero-directory-slot<?= $style('section') ?>" id="<?= $e($section['key']) ?>"<?= $studio ?>>
<?php if ($canvas): ?><span data-studio-part="title" hidden><?= $e($section['title']) ?></span><span data-studio-part="lead" hidden><?= $e($section['lead']) ?></span><?php endif ?> <?php if ($canvas): ?><span data-studio-part="title" hidden><?= $e($section['title']) ?></span><span data-studio-part="lead" hidden><?= $e($section['lead']) ?></span><?php endif ?>
<div<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $body ?></div> <div class="<?= trim($style('body')) ?>"<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $body ?></div>
</div> </div>
<?php <?php
return; return;
@@ -26,11 +30,11 @@ if ($dynamic && $body === '<p><a class="back-link" href="/articles">查看全部
$network = $section['networkFeed'] ?? false; $network = $section['networkFeed'] ?? false;
$catalog = $section['catalogFeed'] ?? false; $catalog = $section['catalogFeed'] ?? false;
?> ?>
<section class="section section-<?= $e($section['style']) ?><?= $network ? ' network' : '' ?>" id="<?= $e($section['key']) ?>" aria-labelledby="heading-<?= $e($section['key']) ?>" <?= $moment ? 'data-moment="iris-opens"' : '' ?><?= $studio ?>> <section class="section section-<?= $e($section['style']) ?><?= $network ? ' network' : '' ?><?= $style('section') ?>" id="<?= $e($section['key']) ?>" aria-labelledby="heading-<?= $e($section['key']) ?>" <?= $moment ? 'data-moment="iris-opens"' : '' ?><?= $studio ?>>
<div class="wrap"> <div class="wrap">
<div class="section-heading"> <div class="section-heading">
<h2 id="heading-<?= $e($section['key']) ?>"<?= isset($alignments['title']) ? ' class="' . trim(View::alignmentClass($alignments['title'])) . '"' : '' ?><?= $canvas ? ' data-studio-part="title"' : '' ?>><?= $e($section['title']) ?></h2> <h2 id="heading-<?= $e($section['key']) ?>" class="<?= trim(View::alignmentClass($alignments['title'] ?? null) . $style('title')) ?>"<?= $canvas ? ' data-studio-part="title"' : '' ?>><?= $text('title') ?></h2>
<?php if ($canvas || $section['lead']): ?><p<?= isset($alignments['lead']) ? ' class="' . trim(View::alignmentClass($alignments['lead'])) . '"' : '' ?><?= $canvas ? ' data-studio-part="lead"' : '' ?>><?= $e($section['lead']) ?></p><?php endif ?> <?php if ($canvas || $section['lead']): ?><p class="<?= trim(View::alignmentClass($alignments['lead'] ?? null) . $style('lead')) ?>"<?= $canvas ? ' data-studio-part="lead"' : '' ?>><?= $text('lead') ?></p><?php endif ?>
</div> </div>
<?php if ($network): ?> <?php if ($network): ?>
<?php foreach ($section['articleFeed'] as $group): ?> <?php foreach ($section['articleFeed'] as $group): ?>
@@ -49,6 +53,6 @@ $catalog = $section['catalogFeed'] ?? false;
<?php elseif (!empty($section['articleFeed'])): ?> <?php elseif (!empty($section['articleFeed'])): ?>
<?= View::fragment('article-feed', ['groups' => $section['articleFeed'], 'sectionKey' => $section['key'], 'archivePath' => $section['archivePath']]) ?> <?= View::fragment('article-feed', ['groups' => $section['articleFeed'], 'sectionKey' => $section['key'], 'archivePath' => $section['archivePath']]) ?>
<?php endif ?> <?php endif ?>
<?php if ($canvas || $body !== ''): ?><div class="rich<?= $dynamic ? ' article-feed-note' : '' ?>"<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $body ?></div><?php endif ?> <?php if ($canvas || $body !== ''): ?><div class="rich<?= $dynamic ? ' article-feed-note' : '' ?><?= $style('body') ?>"<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $body ?></div><?php endif ?>
</div> </div>
</section> </section>
+2
View File
@@ -4,6 +4,8 @@ $paths = [
'center' => '<path d="M3 6h18M6 10h12M3 14h18M6 18h12"/>', 'center' => '<path d="M3 6h18M6 10h12M3 14h18M6 18h12"/>',
'right' => '<path d="M3 6h18M9 10h12M3 14h18M9 18h12"/>', 'right' => '<path d="M3 6h18M9 10h12M3 14h18M9 18h12"/>',
'settings' => '<path d="M4 6h12m4 0h0M4 12h3m4 0h9M4 18h10m4 0h2"/><circle cx="17" cy="6" r="2"/><circle cx="9" cy="12" r="2"/><circle cx="16" cy="18" r="2"/>', 'settings' => '<path d="M4 6h12m4 0h0M4 12h3m4 0h9M4 18h10m4 0h2"/><circle cx="17" cy="6" r="2"/><circle cx="9" cy="12" r="2"/><circle cx="16" cy="18" r="2"/>',
'spacing' => '<rect x="8" y="8" width="8" height="8" rx="1"/><path d="M3 4v16m18-16v16M4 3h16M4 21h16"/>',
'parent' => '<path d="M5 20h14V4H5zM12 16V8m-3 3 3-3 3 3"/>',
'edit' => '<path d="m14 5 5 5M5 19l4-.8L20 7.3 16.7 4 5.8 15z"/>', 'edit' => '<path d="m14 5 5 5M5 19l4-.8L20 7.3 16.7 4 5.8 15z"/>',
'copy' => '<rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 4H6a2 2 0 0 0-2 2v10"/>', 'copy' => '<rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 4H6a2 2 0 0 0-2 2v10"/>',
'delete' => '<path d="M4 7h16M9 7V4h6v3m3 0-.8 13H6.8L6 7m4 4v5m4-5v5"/>', 'delete' => '<path d="M4 7h16M9 7V4h6v3m3 0-.8 13H6.8L6 7m4 4v5m4-5v5"/>',
+3 -3
View File
@@ -4,15 +4,15 @@ use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
?> ?>
<details class="studio-layers" id="blocks"> <details class="studio-layers" id="blocks" open>
<summary>区块顺序</summary> <summary>区块顺序</summary>
<ul class="admin-list studio-blocks"> <p class="field-note" data-layers-empty<?= $page['sections'] ? ' hidden' : '' ?>>添加的独立区块会显示在这里。</p>
<ul class="admin-list studio-blocks" data-canvas-layers>
<?php foreach ($page['sections'] as $index => $item): ?> <?php foreach ($page['sections'] as $index => $item): ?>
<?php $fixedSlot = $item['style'] === 'hero-links'; ?> <?php $fixedSlot = $item['style'] === 'hero-links'; ?>
<li> <li>
<div><strong><?= $e($item['title']) ?></strong><small>#<?= $e($item['key']) ?></small></div> <div><strong><?= $e($item['title']) ?></strong><small>#<?= $e($item['key']) ?></small></div>
<div class="actions studio-block-actions"> <div class="actions studio-block-actions">
<button class="button button-outline" type="button" data-canvas-jump="<?= $e($item['key']) ?>" hidden>在画布编辑</button>
<a class="button button-outline" href="/admin/pages/<?= $e($slug) ?>/<?= $e($item['key']) ?>">区块设置</a> <a class="button button-outline" href="/admin/pages/<?= $e($slug) ?>/<?= $e($item['key']) ?>">区块设置</a>
<form method="post" action="/admin/page-blocks/<?= $e($slug) ?>"> <form method="post" action="/admin/page-blocks/<?= $e($slug) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>"> <input type="hidden" name="csrf" value="<?= $e($token) ?>">
+1
View File
@@ -26,6 +26,7 @@ Route::get('/articles/{slug:[a-z0-9-]+}', [SiteController::class, 'article']);
Route::get('/robots.txt', [SiteController::class, 'robots']); Route::get('/robots.txt', [SiteController::class, 'robots']);
Route::get('/sitemap.xml', [SiteController::class, 'sitemap']); Route::get('/sitemap.xml', [SiteController::class, 'sitemap']);
Route::get('/favicon.ico', [SiteController::class, 'favicon']); Route::get('/favicon.ico', [SiteController::class, 'favicon']);
Route::get('/canvas-style.css', [SiteController::class, 'canvasStyle']);
Route::add(['GET', 'POST'], '/admin/login', [AdminController::class, 'login']); Route::add(['GET', 'POST'], '/admin/login', [AdminController::class, 'login']);
Route::post('/admin/logout', [AdminController::class, 'logout']); Route::post('/admin/logout', [AdminController::class, 'logout']);
+5
View File
@@ -62,6 +62,11 @@
.studio-frame-window iframe { display: block; width: 100%; height: 100%; border: 0; background: white; } .studio-frame-window iframe { display: block; width: 100%; height: 100%; border: 0; background: white; }
.studio-frame-window.has-scaled-preview iframe { position: absolute; top: 0; transform-origin: 0 0; } .studio-frame-window.has-scaled-preview iframe { position: absolute; top: 0; transform-origin: 0 0; }
.studio-canvas-toolbar { margin-bottom: .55rem; } .studio-canvas-toolbar { margin-bottom: .55rem; }
.canvas-format-tools label { display: flex; align-items: center; gap: .3rem; font-size: .875rem; }
.canvas-format-tools input { width: 4.3rem; min-height: 2.45rem; padding: .4rem; border: 1px solid var(--line); border-radius: .35rem; }
.canvas-format-tools [aria-pressed=true] { background: var(--accent-light); color: var(--accent-deep); }
.canvas-spacing-fields { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .5rem; }
.canvas-spacing-fields input { padding-inline: .4rem; }
.studio-canvas-toolbar button:disabled { opacity: .5; cursor: default; } .studio-canvas-toolbar button:disabled { opacity: .5; cursor: default; }
.preview-selector { display: flex; gap: .35rem; flex-wrap: wrap; } .preview-selector { display: flex; gap: .35rem; flex-wrap: wrap; }
.preview-selector [aria-pressed="true"] { background: var(--accent-light); color: var(--accent-deep); } .preview-selector [aria-pressed="true"] { background: var(--accent-light); color: var(--accent-deep); }
+3 -1
View File
@@ -115,7 +115,7 @@ address { font-style: normal; }
} }
.hero-label { margin-bottom: 1.4rem; } .hero-label { margin-bottom: 1.4rem; }
.hero h1 { margin-bottom: 1.5rem; text-wrap: initial; } .hero h1 { margin-bottom: 1.5rem; text-wrap: initial; }
.hero h1 span { color: var(--accent); } .hero h1 > span { color: var(--accent); }
.hero-home h1 { font-size: clamp(3.2rem, 7.4vw, 7.3rem); line-height: 1.08; letter-spacing: -.09em; margin: 0 0 1.5rem -.065em; padding-right: .08em; } .hero-home h1 { font-size: clamp(3.2rem, 7.4vw, 7.3rem); line-height: 1.08; letter-spacing: -.09em; margin: 0 0 1.5rem -.065em; padding-right: .08em; }
.hero-lead { margin-bottom: 1.8rem; max-width: 35rem; font-size: clamp(1.03rem, 1.58vw, 1.28rem); line-height: 1.78; } .hero-lead { margin-bottom: 1.8rem; max-width: 35rem; font-size: clamp(1.03rem, 1.58vw, 1.28rem); line-height: 1.78; }
.hero-home .hero-lead { max-width: 28rem; } .hero-home .hero-lead { max-width: 28rem; }
@@ -387,6 +387,8 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
.catalog-content .actions { margin-top: auto; padding-top: 1rem; } .catalog-content .actions { margin-top: auto; padding-top: 1rem; }
.hero h1 .hero-heading-primary { color: inherit; } .hero h1 .hero-heading-primary { color: inherit; }
.rich, .section-heading, .hero-copy { overflow-wrap: anywhere; }
.button:has(> br, > span[class*="studio-style-"]) { display: inline-block; text-align: center; white-space: normal; }
.studio-accent { display: block; } .studio-accent { display: block; }
[data-studio-editing] .hero:has(> [data-studio-hero-content][hidden]):not(:has(> .hero-directory-slot)) { display: none; } [data-studio-editing] .hero:has(> [data-studio-hero-content][hidden]):not(:has(> .hero-directory-slot)) { display: none; }
[data-studio-editing] [contenteditable], [data-studio-editing] [data-studio-action], [data-studio-editing] [contenteditable], [data-studio-editing] [data-studio-action],
+596 -54
View File
@@ -308,7 +308,7 @@ jQuery(function ($) {
const buttonClasses = {solid: 'button-primary', outline: 'button-outline', underline: 'button-underline', plain: 'button-plain'}; const buttonClasses = {solid: 'button-primary', outline: 'button-outline', underline: 'button-underline', plain: 'button-plain'};
const alignmentClasses = alignments.map((value) => 'studio-align-' + value); const alignmentClasses = alignments.map((value) => 'studio-align-' + value);
const canvasFields = '[data-studio-field="heading"], [data-studio-field="accent"], [data-studio-field="lead"], [data-studio-part="title"], [data-studio-part="lead"], [data-studio-action], [data-studio-nav-index]'; const canvasFields = '[data-studio-field="heading"], [data-studio-field="accent"], [data-studio-field="lead"], [data-studio-part="title"], [data-studio-part="lead"], [data-studio-action], [data-studio-nav-index]';
const bodyElements = 'a, article, blockquote, details, div, dl, dt, dd, figure, h1, h2, h3, h4, h5, h6, hr, li, ol, p, pre, progress, table, ul'; const bodyElements = 'a, article, blockquote, button, details, div, dl, dt, dd, figure, figcaption, h1, h2, h3, h4, h5, h6, hr, li, ol, p, pre, progress, section, summary, table, ul';
const mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video'; const mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video';
const $handle = $studio.find('[data-media-handle]'); const $handle = $studio.find('[data-media-handle]');
const $mediaSize = $sizing.find('[data-media-size]'); const $mediaSize = $sizing.find('[data-media-size]');
@@ -352,6 +352,14 @@ jQuery(function ($) {
}); });
const $toolbar = $studio.find('[data-canvas-toolbar]'); const $toolbar = $studio.find('[data-canvas-toolbar]');
const $commands = $toolbar.find('[data-canvas-command]'); const $commands = $toolbar.find('[data-canvas-command]');
const $format = $toolbar.find('[data-canvas-format]');
const $fontSize = $toolbar.find('[data-canvas-font-size]');
const $spacing = $studio.find('[data-canvas-spacing]');
const $spacingForm = $spacing.find('form');
const $layers = $layout.find('[data-canvas-layers]');
const $history = $toolbar.find('[data-canvas-history]');
const stylePattern = /^studio-style-([a-z]+)-(.+)$/;
const formatOptions = {weight: ['bold', 'normal'], slant: ['italic', 'normal'], strike: ['on', 'off']};
const $properties = $studio.find('[data-canvas-properties]'); const $properties = $studio.find('[data-canvas-properties]');
const $propertyForm = $properties.find('form'); const $propertyForm = $properties.find('form');
const $propertyError = $properties.find('[data-property-error]'); const $propertyError = $properties.find('[data-property-error]');
@@ -363,17 +371,134 @@ jQuery(function ($) {
const propertyInput = (name) => $propertyForm.find('[name="' + name + '"]'); const propertyInput = (name) => $propertyForm.find('[name="' + name + '"]');
const pageInput = (name) => $settings.find('[name="' + name + '"]'); const pageInput = (name) => $settings.find('[name="' + name + '"]');
const settingsSnapshot = () => $settings.serializeArray() const settingsSnapshot = () => $settings.serializeArray()
.filter(({name}) => name !== 'csrf' && name !== 'canvas_sections'); .filter(({name}) => !['csrf', 'canvas_sections', 'canvas_order'].includes(name));
const savedSettings = JSON.stringify(settingsSnapshot()); let savedSettings = JSON.stringify(settingsSnapshot());
let dialogAction; let dialogAction;
let doc; let doc;
let activeBody; let activeBody;
let savedRange; let savedRange;
let textRange;
let textHost;
let sections = []; let sections = [];
let initialOrder;
let saveComplete = false; let saveComplete = false;
let syncPageFromInputs;
let spacingTarget;
function classesOf(node, textOnly = false) {
const result = {};
for (const name of node.classList) {
const prefix = name.match(stylePattern)?.[1];
if (prefix && (!textOnly || prefix === 'size' || Object.hasOwn(formatOptions, prefix))) result[prefix] = name;
}
return result;
}
function putStyle(node, property, value) {
const current = classesOf(node)[property];
if (current) node.classList.remove(current);
if (value !== '') node.classList.add('studio-style-' + property + '-' + value);
}
function readRuns(node) {
const runs = [];
function visit(parent, styles) {
for (const child of parent.childNodes) {
if (child.nodeType === 1 && child.localName !== 'br') {
visit(child, {...styles, ...classesOf(child, true)});
continue;
}
const text = child.nodeType === 3 ? child.data : child.localName === 'br' ? '\n' : '';
if (!text) continue;
const tokens = Object.values(styles).join(' ');
const last = runs.at(-1);
if (last?.[1] === tokens) last[0] += text;
else runs.push([text, tokens]);
}
}
visit(node, {});
return runs;
}
function plainText(node) {
return readRuns(node).map(([text]) => text).join('').trim();
}
function paintText(node, value, runs) {
const display = runs?.map(([text]) => text).join('').trim() === value ? runs : [[value, '']];
node.replaceChildren();
for (const [text, tokens] of display) {
const parent = tokens ? doc.createElement('span') : node;
if (tokens) {
parent.className = tokens;
node.append(parent);
}
text.split('\n').forEach((line, index) => {
if (index) parent.append(doc.createElement('br'));
if (line) parent.append(line);
});
}
}
function presentationOf(node, text = false) {
const classes = Object.values(classesOf(node)).join(' ');
const runs = text ? readRuns(node).filter(([part]) => part !== '') : [];
const formatted = runs.some(([part, tokens]) => tokens || part.includes('\n'));
return classes || formatted ? {classes, runs: formatted ? runs : []} : null;
}
function sectionPresentation({node, fields}) {
const presentation = {};
for (const [role, element] of Object.entries({section: node, title: fields.title.node, lead: fields.lead.node, body: fields.body.node})) {
const style = presentationOf(element, role === 'title' || role === 'lead');
if (style) presentation[role] = style;
}
return presentation;
}
function cleanBody(node) {
if (!node.contains(selectedElement) || node === selectedElement) return node.innerHTML;
const copy = node.cloneNode(true);
$(copy).find('[data-studio-selected]').removeAttr('data-studio-selected');
return copy.innerHTML;
}
function pagePresentation() {
return JSON.parse(pageInput('canvas_presentation').val());
}
function syncPagePresentation() {
const result = {};
$(doc).find('[data-studio-style-field]').each(function () {
const role = this.dataset.studioStyleField;
const style = presentationOf(this, this.hasAttribute('data-studio-field') || role.startsWith('action-'));
if (style) result[role] = style;
});
pageInput('canvas_presentation').val(JSON.stringify(result));
}
function remapPageStyles(prefix, indexes) {
syncPagePresentation();
const available = pagePresentation();
const next = Object.fromEntries(Object.entries(available).filter(([key]) => !key.startsWith(prefix + '-')));
indexes.forEach((old, index) => {
if (available[prefix + '-' + old]) next[prefix + '-' + index] = available[prefix + '-' + old];
});
pageInput('canvas_presentation').val(JSON.stringify(next));
}
function setPageStyle(node, style) {
node.classList.remove(...Object.values(classesOf(node)));
if (style?.classes) node.classList.add(...style.classes.split(' '));
}
function canvasOrder() {
return JSON.stringify(sections.filter(({fixed}) => !fixed).map(({key}) => key));
}
function sectionChanges(withEdits = true) { function sectionChanges(withEdits = true) {
const edits = sections.flatMap(({key, version, fields, source, template, copyOf, feed, initialFeed}) => { const edits = sections.flatMap((entry) => {
const {key, version, fields, source, template, copyOf, feed, initialFeed, initialPresentation} = entry;
const changes = {}; const changes = {};
const aligned = {}; const aligned = {};
let alignmentChanged = false; let alignmentChanged = false;
@@ -383,36 +508,40 @@ jQuery(function ($) {
if (value) aligned[field] = value; if (value) aligned[field] = value;
if (value !== initialAlignment) alignmentChanged = true; if (value !== initialAlignment) alignmentChanged = true;
} }
let value = field === 'body' ? node.innerHTML : node.textContent; const value = field === 'body' ? cleanBody(node) : plainText(node);
if (field === 'body' && node.contains(selectedElement)) {
const copy = node.cloneNode(true);
$(copy).find('[data-studio-selected]').removeAttr('data-studio-selected');
value = copy.innerHTML;
}
if (version === null || value !== initial) { if (version === null || value !== initial) {
changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value; changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value;
} }
} }
const feedChanged = feed && (version === null || JSON.stringify(feed) !== initialFeed); const feedChanged = feed && (version === null || JSON.stringify(feed) !== initialFeed);
if (!Object.keys(changes).length && !alignmentChanged && !feedChanged) return []; const presentation = sectionPresentation(entry);
const presentationChanged = JSON.stringify(presentation) !== initialPresentation;
if (!Object.keys(changes).length && !alignmentChanged && !feedChanged && !presentationChanged) return [];
const edit = {key, version, fields: changes}; const edit = {key, version, fields: changes};
if (alignmentChanged || (version === null && Object.keys(aligned).length)) edit.alignments = aligned; if (alignmentChanged || (version === null && Object.keys(aligned).length)) edit.alignments = aligned;
if (template) edit.template = template; if (template) edit.template = template;
if (copyOf) edit.copyOf = copyOf; if (copyOf) edit.copyOf = copyOf;
if (feedChanged) edit.feed = feed; if (feedChanged) edit.feed = feed;
if (presentationChanged || version === null && Object.keys(presentation).length) edit.presentation = presentation;
return [edit]; return [edit];
}); });
return [...edits, ...deletedSections]; return [...edits, ...deletedSections];
} }
$settings.on('studio:sync', () => pageInput('canvas_sections').val(JSON.stringify(sectionChanges()))); $settings.on('studio:sync', () => {
if (!doc || initialOrder === undefined) return;
syncPagePresentation();
pageInput('canvas_sections').val(JSON.stringify(sectionChanges()));
pageInput('canvas_order').val(canvasOrder() === initialOrder ? '' : canvasOrder());
});
$settings.on('studio:saved', () => { saveComplete = true; }); $settings.on('studio:saved', () => { saveComplete = true; });
$settings.on('studio:busy', (_event, busy) => { $settings.on('studio:busy', (_event, busy) => {
$layout.prop('inert', busy); $layout.prop('inert', busy);
$settings.prop('inert', busy); $settings.prop('inert', busy);
}); });
$(window).on('beforeunload', (event) => { $(window).on('beforeunload', (event) => {
if (!saveComplete && (sectionChanges(false).length || JSON.stringify(settingsSnapshot()) !== savedSettings)) { if (!saveComplete && (sectionChanges(false).length || initialOrder !== undefined && canvasOrder() !== initialOrder
|| JSON.stringify(settingsSnapshot()) !== savedSettings)) {
event.preventDefault(); event.preventDefault();
event.originalEvent.returnValue = ''; event.originalEvent.returnValue = '';
} }
@@ -452,8 +581,18 @@ jQuery(function ($) {
function rememberSelection() { function rememberSelection() {
const selection = doc.getSelection(); const selection = doc.getSelection();
if (selection.rangeCount && activeBody?.contains(selection.anchorNode) && activeBody.contains(selection.focusNode)) { if (!selection.rangeCount) return;
savedRange = selection.getRangeAt(0).cloneRange(); const anchor = selection.anchorNode;
const host = (anchor.nodeType === 1 ? anchor : anchor.parentElement)?.closest('[contenteditable="true"]');
if (host?.contains(selection.focusNode)) {
textHost = host;
textRange = selection.getRangeAt(0).cloneRange();
if (host === activeBody) savedRange = textRange.cloneRange();
syncFormatControls();
} else if (textRange) {
textRange = null;
textHost = null;
syncFormatControls();
} }
} }
@@ -480,6 +619,144 @@ jQuery(function ($) {
rememberSelection(); rememberSelection();
} }
function styleTarget(node) {
if (!node || node.closest('[data-studio-dynamic]') && !node.hasAttribute('data-studio-dynamic')) return null;
if (node.hasAttribute('data-studio-hero-image')) return node.parentElement;
return node.matches('[data-studio-section], [data-studio-style-field], [data-studio-part]')
|| node.closest('[data-studio-part="body"]') ? node : null;
}
function parentElement(node) {
const parent = node?.parentElement;
if (!parent || node.hasAttribute('data-studio-dynamic')) return null;
return editableBodyElement(parent)
|| parent.closest('[data-studio-part="body"], [data-studio-section], [data-studio-style-field]');
}
function formatTarget() {
if (textRange?.commonAncestorContainer.isConnected && textHost?.contains(textRange.commonAncestorContainer)) {
if (!textRange.collapsed) return textHost;
if (!selectedElement && doc.activeElement === textHost) {
const anchor = textRange.startContainer;
return styleTarget(editableBodyElement(anchor.parentElement || textHost) || textHost);
}
}
return styleTarget(selectedElement);
}
function formatState(node, property) {
const computed = doc.defaultView.getComputedStyle(node.nodeType === 1 ? node : node.parentElement);
if (property === 'weight') return Number(computed.fontWeight) >= 600 || computed.fontWeight === 'bold';
if (property === 'slant') return computed.fontStyle !== 'normal';
for (let element = node.nodeType === 1 ? node : node.parentElement; element; element = element.parentElement) {
if (classesOf(element).strike === 'studio-style-strike-off') return false;
if (doc.defaultView.getComputedStyle(element).textDecorationLine.includes('line-through')) return true;
}
return false;
}
function selectedText() {
if (!textRange || textRange.collapsed || !textHost?.contains(textRange.commonAncestorContainer) || !textHost?.isConnected) return [];
const nodes = [];
const walker = doc.createTreeWalker(textHost, 4);
while (walker.nextNode()) {
const node = walker.currentNode;
if (!textRange.intersectsNode(node)) continue;
const start = node === textRange.startContainer ? textRange.startOffset : 0;
const end = node === textRange.endContainer ? textRange.endOffset : node.length;
if (end > start) nodes.push({node, start, end});
}
return nodes;
}
function syncFormatControls() {
const target = doc && formatTarget();
$format.add($fontSize).prop('disabled', !target);
const sample = target && (selectedText()[0]?.node || target);
const size = sample ? doc.defaultView.getComputedStyle(sample.nodeType === 1 ? sample : sample.parentElement).fontSize : '';
if (!$fontSize.is(':focus')) $fontSize.val(size ? Math.round(parseFloat(size)) : '');
$format.each(function () {
$(this).attr('aria-pressed', String(Boolean(sample) && formatState(sample, this.dataset.canvasFormat)));
});
}
function applyTextStyle(property, value) {
const target = formatTarget();
if (!target) return;
const nodes = selectedText();
if (property !== 'size') {
const hasFormat = nodes.length ? nodes.every(({node}) => formatState(node, property)) : formatState(target, property);
value = formatOptions[property][Number(hasFormat)];
}
if (!nodes.length) {
putStyle(target, property, value);
} else if (value !== '') {
const spans = [];
for (const {node, start, end} of nodes) {
const parent = node.parentElement;
if (start === 0 && end === node.length && parent.matches('span') && parent.childNodes.length === 1 && parent !== textHost) {
putStyle(parent, property, value);
spans.push(parent);
continue;
}
if (end < node.length) node.splitText(end);
const piece = start > 0 ? node.splitText(start) : node;
const span = doc.createElement('span');
putStyle(span, property, value);
piece.before(span);
span.append(piece);
spans.push(span);
}
const range = doc.createRange();
range.setStart(spans[0].firstChild, 0);
range.setEnd(spans.at(-1).lastChild, spans.at(-1).lastChild.length);
doc.getSelection().removeAllRanges();
doc.getSelection().addRange(range);
textRange = range;
if (textHost === activeBody) savedRange = range.cloneRange();
}
syncFormatControls();
positionSelection();
}
$toolbar.on('mousedown', '[data-canvas-format]', (event) => event.preventDefault());
$format.on('click', function () { applyTextStyle(this.dataset.canvasFormat); });
$fontSize.on('change', function () {
if (this.validity.valid) applyTextStyle('size', this.value);
}).on('keydown', function (event) {
if (event.key === 'Enter') {
event.preventDefault();
this.blur();
}
});
$elementTools.on('click', '[data-element-spacing]', () => {
spacingTarget = styleTarget(selectedElement);
if (!spacingTarget) return;
const styles = classesOf(spacingTarget);
$spacingForm.find('input').each(function () {
this.value = styles[this.name]?.slice(('studio-style-' + this.name + '-').length) || '';
});
$spacing.get(0).showModal();
});
$elementTools.on('click', '[data-element-parent]', () => {
const parent = parentElement(selectedElement);
if (!parent) return;
doc.getSelection().removeAllRanges();
textRange = null;
textHost = null;
selectElement(parent);
});
$spacing.on('click', '[data-spacing-close]', () => $spacing.get(0).close());
$spacingForm.on('submit', (event) => {
event.preventDefault();
if (spacingTarget?.isConnected) {
$spacingForm.find('input').each(function () { putStyle(spacingTarget, this.name, this.value); });
}
$spacing.get(0).close();
positionSelection();
});
$toolbar.on('mousedown', '[data-canvas-command]', (event) => event.preventDefault()); $toolbar.on('mousedown', '[data-canvas-command]', (event) => event.preventDefault());
$toolbar.on('click', '[data-canvas-command]', function () { $toolbar.on('click', '[data-canvas-command]', function () {
const command = this.dataset.canvasCommand; const command = this.dataset.canvasCommand;
@@ -502,13 +779,13 @@ jQuery(function ($) {
}); });
}); });
} else { } else {
const commands = {heading: ['formatBlock', 'h3'], bold: ['bold'], list: ['insertUnorderedList']}; const commands = {heading: ['formatBlock', 'h3'], list: ['insertUnorderedList']};
edit(...commands[command]); edit(...commands[command]);
} }
}); });
function configureText(node, label, placeholder = false) { function configureText(node, label, placeholder = false, rich = true) {
node.contentEditable = 'plaintext-only'; node.contentEditable = rich ? 'true' : 'plaintext-only';
node.setAttribute('aria-label', label); node.setAttribute('aria-label', label);
if (placeholder) node.dataset.studioPlaceholder = label; if (placeholder) node.dataset.studioPlaceholder = label;
} }
@@ -528,9 +805,11 @@ jQuery(function ($) {
const field = this.dataset.studioField; const field = this.dataset.studioField;
const $target = $(this); const $target = $(this);
const $input = pageInput(field); const $input = pageInput(field);
configureText(this, labels[field], ['accent', 'lead'].includes(field)); configureText(this, labels[field], ['accent', 'lead'].includes(field), field !== 'name');
$target.text($input.val()).on('input', () => $input.val($target.text())); $target.on('input', () => $input.val(plainText(this)));
$input.on('input.canvas', () => $target.text($input.val())); $input.on('input.canvas', () => {
if ($input.val() !== plainText(this)) paintText(this, $input.val());
});
}); });
const $image = $doc.find('[data-studio-hero-image]'); const $image = $doc.find('[data-studio-hero-image]');
@@ -562,16 +841,28 @@ jQuery(function ($) {
const $heroActions = $doc.find('.hero-actions'); const $heroActions = $doc.find('.hero-actions');
const $actionsInput = pageInput('hero_actions'); const $actionsInput = pageInput('hero_actions');
let actions = JSON.parse($actionsInput.val()).map(([url, label, style, blank], index) => [ const readActions = () => JSON.parse($actionsInput.val()).map(([url, label, style, blank], index) => [
url, label, style || (index ? 'outline' : 'solid'), Boolean(blank), url, label, style || (index ? 'outline' : 'solid'), Boolean(blank),
]); ]);
let actions = readActions();
function syncActions() { function syncActions() {
$actionsInput.val(JSON.stringify(actions)); $actionsInput.val(JSON.stringify(actions));
const presentation = pagePresentation();
$heroActions.empty(); $heroActions.empty();
for (const [index, [url, label, style, blank]] of actions.entries()) { for (const [index, [url, label, style, blank]] of actions.entries()) {
$('<a>', {href: url, class: 'button ' + buttonClasses[style], 'data-studio-action': index, text: label}) const role = 'action-' + index;
const $action = $('<a>', {href: url, class: 'button ' + buttonClasses[style],
'data-studio-action': index, 'data-studio-style-field': role})
.attr(blank ? {target: '_blank', rel: 'noopener noreferrer'} : {}).appendTo($heroActions); .attr(blank ? {target: '_blank', rel: 'noopener noreferrer'} : {}).appendTo($heroActions);
const node = $action.get(0);
configureText(node, '首屏按钮文案');
setPageStyle(node, presentation[role]);
paintText(node, label, presentation[role]?.runs);
$action.on('input', () => {
actions[index][1] = plainText(node);
$actionsInput.val(JSON.stringify(actions));
});
} }
} }
function editAction(index) { function editAction(index) {
@@ -595,6 +886,9 @@ jQuery(function ($) {
heroControls.set('edit-action', editAction); heroControls.set('edit-action', editAction);
heroControls.set('change-action', (index, copy) => { heroControls.set('change-action', (index, copy) => {
if (copy && actions.length >= 8) return null; if (copy && actions.length >= 8) return null;
const order = actions.map((_, position) => position);
order.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [index] : []));
remapPageStyles('action', order);
actions.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [[...actions[index]]] : [])); actions.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [[...actions[index]]] : []));
syncActions(); syncActions();
return $heroActions.children().get(index + 1); return $heroActions.children().get(index + 1);
@@ -611,6 +905,7 @@ jQuery(function ($) {
const navLines = () => $navInput.val().split(/\r\n|[\n\r\v\f\u0085\u2028\u2029]/); const navLines = () => $navInput.val().split(/\r\n|[\n\r\v\f\u0085\u2028\u2029]/);
function syncNavigation() { function syncNavigation() {
const lines = navLines(); const lines = navLines();
const presentation = pagePresentation();
$navContent.empty(); $navContent.empty();
for (const [index, line] of lines.entries()) { for (const [index, line] of lines.entries()) {
if (!line.trim()) continue; if (!line.trim()) continue;
@@ -621,6 +916,8 @@ jQuery(function ($) {
link.href = safeLink(url) ? url : '#'; link.href = safeLink(url) ? url : '#';
link.textContent = label || url; link.textContent = label || url;
link.dataset.studioNavIndex = index; link.dataset.studioNavIndex = index;
link.dataset.studioStyleField = 'nav-' + $navContent.children().length;
setPageStyle(link, presentation[link.dataset.studioStyleField]);
$(link).on('dblclick studio:properties', (event) => { $(link).on('dblclick studio:properties', (event) => {
event.preventDefault(); event.preventDefault();
openProperties('本页目录链接', {label, url}, (next) => { openProperties('本页目录链接', {label, url}, (next) => {
@@ -641,6 +938,10 @@ jQuery(function ($) {
heroControls.set('change-nav', (index, copy) => { heroControls.set('change-nav', (index, copy) => {
const lines = navLines(); const lines = navLines();
if (copy && $navContent.children().length >= 20) return null; if (copy && $navContent.children().length >= 20) return null;
const ordinal = $navContent.find('[data-studio-nav-index="' + index + '"]').index();
const order = $navContent.children().get().map((_, position) => position);
order.splice(ordinal + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [ordinal] : []));
remapPageStyles('nav', order);
lines.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [lines[index]] : [])); lines.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [lines[index]] : []));
$navInput.val(lines.join('\n')); $navInput.val(lines.join('\n'));
syncNavigation(); syncNavigation();
@@ -649,11 +950,15 @@ jQuery(function ($) {
$navInput.on('input.canvas', syncNavigation); $navInput.on('input.canvas', syncNavigation);
heroControls.set('remove-section-links', (key) => { heroControls.set('remove-section-links', (key) => {
const anchor = '#' + key; const anchor = '#' + key;
const navOrder = $navContent.children().get().flatMap((link, index) => link.getAttribute('href') === anchor ? [] : [index]);
const actionOrder = actions.flatMap(([url], index) => url === anchor ? [] : [index]);
remapPageStyles('nav', navOrder);
$navInput.val(navLines().filter((line) => { $navInput.val(navLines().filter((line) => {
const separator = line.indexOf('|'); const separator = line.indexOf('|');
return separator < 0 || line.slice(separator + 1).trim() !== anchor; return separator < 0 || line.slice(separator + 1).trim() !== anchor;
}).join('\n')); }).join('\n'));
syncNavigation(); syncNavigation();
remapPageStyles('action', actionOrder);
actions = actions.filter(([url]) => url !== anchor); actions = actions.filter(([url]) => url !== anchor);
syncActions(); syncActions();
}); });
@@ -664,6 +969,28 @@ jQuery(function ($) {
}); });
}); });
syncNavigation(); syncNavigation();
syncPageFromInputs = () => {
const presentation = pagePresentation();
$doc.find('[data-studio-field]').each(function () {
const field = this.dataset.studioField;
paintText(this, pageInput(field).val(), presentation[field]?.runs);
});
$doc.find('[data-studio-style-field]').each(function () {
setPageStyle(this, presentation[this.dataset.studioStyleField]);
});
const values = JSON.parse(pageInput('alignments').val());
$doc.find('[data-studio-align-field]').each(function () {
this.classList.remove(...alignmentClasses);
if (values[this.dataset.studioAlignField]) this.classList.add('studio-align-' + values[this.dataset.studioAlignField]);
});
Object.keys(visibilityTargets).forEach((area) => pageInput('show_' + area).triggerHandler('change.canvas'));
pageInput('palette_id').triggerHandler('change.canvas');
actions = readActions();
syncActions();
syncNavigation();
syncImage();
};
syncPageFromInputs();
} }
function editResource(node) { function editResource(node) {
@@ -748,12 +1075,14 @@ jQuery(function ($) {
} else if (!feed && !node.hidden) { } else if (!feed && !node.hidden) {
configureText(node, label, part === 'lead'); configureText(node, label, part === 'lead');
} }
fields[part] = {node, initial: body ? node.innerHTML : node.textContent, initialAlignment: body ? '' : getAlignment(node)}; fields[part] = {node, initial: body ? node.innerHTML : plainText(node), initialAlignment: body ? '' : getAlignment(node)};
} }
const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from( const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from(
atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0) atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0)
)); ));
const entry = {node: section, key: section.id, version, fields, source, feed, initialFeed: JSON.stringify(feed), ...metadata}; const entry = {node: section, key: section.id, version, fields, source, feed, initialFeed: JSON.stringify(feed),
parent: section.parentNode, fixed: section.classList.contains('hero-directory-slot'), ...metadata};
entry.initialPresentation = JSON.stringify(sectionPresentation(entry));
sections.push(entry); sections.push(entry);
return entry; return entry;
} }
@@ -849,7 +1178,7 @@ jQuery(function ($) {
if (!node) return null; if (!node) return null;
const hero = node.closest('[data-studio-align-field]'); const hero = node.closest('[data-studio-align-field]');
if (hero) return hero; if (hero) return hero;
return node.matches('[data-studio-part="title"], [data-studio-part="lead"]') || node.closest('[data-studio-part="body"]') return node.matches('[data-studio-part="title"], [data-studio-part="lead"]') || node.parentElement?.closest('[data-studio-part="body"]')
? node : null; ? node : null;
} }
@@ -862,37 +1191,45 @@ jQuery(function ($) {
function selectElement(node) { function selectElement(node) {
selectionObserver?.disconnect(); selectionObserver?.disconnect();
selectedElement?.removeAttribute('data-studio-selected'); selectedElement?.removeAttribute('data-studio-selected');
if (node && textHost && !node.contains(textHost) && !textHost.contains(node)) {
textHost = null;
textRange = null;
}
selectedElement = node; selectedElement = node;
const dynamic = node?.hasAttribute('data-studio-dynamic'); const dynamic = node?.hasAttribute('data-studio-dynamic');
$elementTools.toggleClass('is-module', Boolean(dynamic)).find('[data-element-module-settings]').prop('hidden', !dynamic); $elementTools.toggleClass('is-module', Boolean(dynamic)).find('[data-element-module-settings]').prop('hidden', !dynamic);
$elementTools.find('[data-element-spacing]').prop('hidden', !styleTarget(node));
$elementTools.find('[data-element-parent]').prop('hidden', !parentElement(node));
selectedMedia = node?.matches(mediaTargets) ? node : null; selectedMedia = node?.matches(mediaTargets) ? node : null;
$sizing.prop('hidden', !selectedMedia); $sizing.prop('hidden', !selectedMedia);
if (node) { if (node) {
node.setAttribute('data-studio-selected', ''); node.setAttribute('data-studio-selected', '');
const target = sizingTarget(); const target = sizingTarget();
const nav = node.hasAttribute('data-studio-nav-index'); const nav = node.hasAttribute('data-studio-nav-index');
const inBody = node.closest('[data-studio-part="body"]') !== null; const inBody = Boolean(node.parentElement?.closest('[data-studio-part="body"]'));
const action = node.hasAttribute('data-studio-action'); const action = node.hasAttribute('data-studio-action');
const canCopy = dynamic || inBody || (nav && $(node).siblings().length < 19) || (action && $(node).siblings().length < 7); const canCopy = dynamic || inBody || (nav && $(node).siblings().length < 19) || (action && $(node).siblings().length < 7);
const hasProperties = !dynamic && (selectedMedia || node.matches('a, progress')); const hasProperties = !dynamic && (selectedMedia || node.matches('a, progress'));
const aligned = dynamic ? null : alignmentTarget(node); const aligned = dynamic ? null : alignmentTarget(node);
syncAlignmentButtons(aligned); syncAlignmentButtons(aligned);
$elementTools.find('[data-element-copy]').prop('hidden', !canCopy); $elementTools.find('[data-element-copy]').prop('hidden', !canCopy);
const sectionRoot = node.hasAttribute('data-studio-section');
const deleteLabel = node.dataset.studioField === 'heading' ? '删除首屏' const deleteLabel = node.dataset.studioField === 'heading' ? '删除首屏'
: node.dataset.studioPart === 'title' ? '删除区块' : '删除'; : node.dataset.studioPart === 'title' || sectionRoot ? '删除区块' : '删除';
$elementTools.find('[data-element-delete]').attr({'aria-label': deleteLabel, title: deleteLabel}) $elementTools.find('[data-element-delete]').attr({'aria-label': deleteLabel, title: deleteLabel})
.prop('hidden', !dynamic && !inBody && !selectedMedia && !node.matches(canvasFields)); .prop('hidden', !sectionRoot && !inBody && !selectedMedia && !node.matches(canvasFields));
$elementTools.find('[data-element-properties]').prop('hidden', !hasProperties); $elementTools.find('[data-element-properties]').prop('hidden', !hasProperties);
if (target) showMediaWidth(currentMediaWidth(target)); if (target) showMediaWidth(currentMediaWidth(target));
selectionObserver?.observe(target || aligned || node); selectionObserver?.observe(target || aligned || node);
} }
syncFormatControls();
positionSelection(); positionSelection();
} }
function changeElement(copy) { function changeElement(copy) {
const node = selectedElement; const node = selectedElement;
if (!node?.isConnected) return; if (!node?.isConnected) return;
if (node.hasAttribute('data-studio-dynamic')) { if (node.hasAttribute('data-studio-section')) {
changeModule(sections.find((section) => section.node === node), copy); changeModule(sections.find((section) => section.node === node), copy);
return; return;
} }
@@ -906,7 +1243,7 @@ jQuery(function ($) {
changeModule(sections.find((section) => section.node === node.closest('[data-studio-section]')), false); changeModule(sections.find((section) => section.node === node.closest('[data-studio-section]')), false);
return; return;
} }
const inBody = node.closest('[data-studio-part="body"]') !== null; const inBody = Boolean(node.parentElement?.closest('[data-studio-part="body"]'));
selectElement(null); selectElement(null);
if (inBody) { if (inBody) {
if (copy) { if (copy) {
@@ -1001,6 +1338,7 @@ jQuery(function ($) {
fields.title.node.textContent = title; fields.title.node.textContent = title;
fields.lead.node.textContent = moduleInput('module_lead').val().trim(); fields.lead.node.textContent = moduleInput('module_lead').val().trim();
noteModule(node, '模块设置将在保存页面后更新。'); noteModule(node, '模块设置将在保存页面后更新。');
refreshLayerTitle(editedModule);
$moduleDialog.get(0).close(); $moduleDialog.get(0).close();
positionSelection(); positionSelection();
}); });
@@ -1009,13 +1347,70 @@ jQuery(function ($) {
return 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join(''); return 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('');
} }
function addPending(section) { function refreshLayerTitle(section) {
const $button = $('<button>', {type: 'button', text: '取消新增:' + section.fields.title.node.textContent}); const title = plainText(section.fields.title.node) || '未命名区块';
section.$pending = $('<li>').append($button).appendTo($pending); $layers.children().filter((_, node) => node.dataset.layerKey === section.key).find('[data-layer-title]').text(title);
$pending.prop('hidden', false);
$button.on('click', () => removeSection(section));
} }
function renderLayers() {
const eligible = sections.filter(({fixed}) => !fixed);
const button = (label, operation, disabled = false) => $('<button>', {
type: 'button', class: 'button button-outline', text: label, 'data-layer-operation': operation, disabled
});
$layers.empty();
$pending.empty();
for (const entry of sections) {
const {key, fixed, version} = entry;
const index = eligible.indexOf(entry);
const $row = $('<li>', {'data-layer-key': key}).appendTo($layers);
const $label = $('<div>').append($('<strong>', {
'data-layer-title': '', text: plainText(entry.fields.title.node) || '未命名区块'
})).appendTo($row);
if (fixed || version === null) $label.append($('<small>').text(fixed ? '首屏目录' : '待保存'));
const $actions = $('<div>', {class: 'actions studio-block-actions'}).appendTo($row);
$actions.append(button('定位', 'jump'), button('上移', 'up', fixed || index === 0),
button('下移', 'down', fixed || index === eligible.length - 1), button('删除', 'delete'));
if (version !== null) {
$('<a>', {class: 'button button-outline', href: $settings.attr('action') + '/' + key, text: '区块设置'}).appendTo($actions);
} else {
const $cancel = $('<button>', {type: 'button', text: '取消新增:' + plainText(entry.fields.title.node)});
$('<li>').append($cancel).appendTo($pending);
$cancel.on('click', () => removeSection(entry));
}
}
$layout.find('[data-layers-empty]').prop('hidden', sections.length > 0);
$pending.prop('hidden', !$pending.children().length);
}
$layers.on('click', '[data-layer-operation]', function () {
const entry = sections.find(({key}) => key === this.closest('[data-layer-key]').dataset.layerKey);
if (!entry) return;
const operation = this.dataset.layerOperation;
if (operation === 'delete') {
changeModule(entry, false);
} else if (operation === 'jump') {
doc.getSelection().removeAllRanges();
textRange = null;
selectBody(entry.feed ? null : entry.fields.body.node);
$studio.get(0).scrollIntoView({block: 'start'});
entry.node.scrollIntoView({block: 'start'});
selectElement(entry.node);
} else {
const eligible = sections.filter(({fixed}) => !fixed);
const other = eligible[eligible.indexOf(entry) + (operation === 'up' ? -1 : 1)];
if (!other || entry.fixed) return;
if (operation === 'up') other.node.before(entry.node);
else other.node.after(entry.node);
const index = sections.indexOf(entry);
const swap = sections.indexOf(other);
[sections[index], sections[swap]] = [sections[swap], sections[index]];
renderLayers();
$layers.children().filter((_, node) => node.dataset.layerKey === entry.key)
.find('[data-layer-operation="' + operation + '"]:enabled, [data-layer-operation="jump"]').last().trigger('focus');
positionSelection();
}
});
function removeSection(section) { function removeSection(section) {
if (section.node.contains(activeBody)) selectBody(null); if (section.node.contains(activeBody)) selectBody(null);
if (section.node.contains(selectedElement)) selectElement(null); if (section.node.contains(selectedElement)) selectElement(null);
@@ -1023,8 +1418,7 @@ jQuery(function ($) {
section.node.remove(); section.node.remove();
sections = sections.filter((entry) => entry !== section); sections = sections.filter((entry) => entry !== section);
heroControls.get('remove-section-links')(section.key); heroControls.get('remove-section-links')(section.key);
section.$pending?.remove(); renderLayers();
$pending.prop('hidden', !$pending.children().length);
} }
function scopeTemplateIds(root, prefix, oldKey = '') { function scopeTemplateIds(root, prefix, oldKey = '') {
@@ -1065,8 +1459,8 @@ jQuery(function ($) {
clone.dataset.studioFeed = JSON.stringify(section.feed); clone.dataset.studioFeed = JSON.stringify(section.feed);
doc.querySelector('[data-studio-section-end]').before(clone); doc.querySelector('[data-studio-section-end]').before(clone);
const copyOf = section.copyOf || (section.version === null ? null : {key: section.key, version: section.version}); const copyOf = section.copyOf || (section.version === null ? null : {key: section.key, version: section.version});
const entry = registerSection(clone, null, {template: copyOf ? null : section.template, copyOf}); registerSection(clone, null, {template: copyOf ? null : section.template, copyOf});
addPending(entry); renderLayers();
noteModule(clone, '模块副本将在保存页面后生效。'); noteModule(clone, '模块副本将在保存页面后生效。');
clone.scrollIntoView({block: 'start'}); clone.scrollIntoView({block: 'start'});
selectElement(clone); selectElement(clone);
@@ -1222,13 +1616,127 @@ jQuery(function ($) {
} }
end.before(section); end.before(section);
const entry = registerSection(section, null, {template}); const entry = registerSection(section, null, {template});
addPending(entry); renderLayers();
section.scrollIntoView({block: 'start'}); section.scrollIntoView({block: 'start'});
if (feed) selectElement(section); if (feed) selectElement(section);
else entry.fields.body.node.focus({preventScroll: true}); else entry.fields.body.node.focus({preventScroll: true});
$templateStatus.text('已添加 ' + title.textContent + ' 区块。'); $templateStatus.text('已添加 ' + title.textContent + ' 区块。');
}); });
const history = [];
let historyIndex = 0;
let historyObserver;
let lastHistoryGroup;
let lastHistoryTime = 0;
function syncHistoryButtons() {
$history.filter('[data-canvas-history="undo"]').prop('disabled', historyIndex === 0);
$history.filter('[data-canvas-history="redo"]').prop('disabled', historyIndex >= history.length - 1);
}
function captureHistory(group = null) {
if (initialOrder === undefined) return;
syncPagePresentation();
const state = {
settings: settingsSnapshot(),
sections: sections.map((entry) => ({
entry, key: entry.key, classes: entry.node.className, feed: entry.feed,
note: entry.node.querySelector('[data-studio-module-note]')?.textContent ?? null,
parts: Object.fromEntries(Object.entries(entry.fields).map(([name, {node}]) =>
[name, [node.className, name === 'body' ? cleanBody(node) : node.innerHTML]])),
})),
deleted: [...deletedSections],
};
const key = JSON.stringify(state, (name, value) => name === 'entry' ? undefined : value);
if (history[historyIndex]?.key === key) return;
const time = performance.now();
history.splice(historyIndex + 1);
if (group && group === lastHistoryGroup && historyIndex > 0 && (group === mediaDrag || time - lastHistoryTime < 750)) {
history[historyIndex] = {state, key};
} else {
history.push({state, key});
}
// Keep a useful undo step even when a single page exceeds the normal history budget.
let size = history.reduce((sum, item) => sum + item.key.length, 0);
while (history.length > 2 && (history.length > 41 || size > 6_000_000)) {
size -= history.shift().key.length;
}
historyIndex = history.length - 1;
lastHistoryGroup = group;
lastHistoryTime = time;
syncHistoryButtons();
}
function stepHistory(direction) {
if (initialOrder === undefined) return false;
if (direction < 0) captureHistory();
const next = history[historyIndex + direction];
if (!next) return false;
historyIndex += direction;
lastHistoryGroup = null;
const {state} = next;
doc.getSelection().removeAllRanges();
textRange = null;
textHost = null;
selectBody(null);
selectElement(null);
const desired = new Set(state.sections.map(({entry}) => entry));
for (const entry of sections) {
if (!desired.has(entry)) entry.node.remove();
}
const end = doc.querySelector('[data-studio-section-end]');
const followingFixed = new Map();
for (const {entry, classes, parts, feed, note} of [...state.sections].reverse()) {
const {node, fields} = entry;
node.className = classes;
entry.feed = feed;
for (const [field, [fieldClasses, markup]] of Object.entries(parts)) {
const element = fields[field].node;
element.className = fieldClasses;
const current = element.innerHTML;
if (current !== markup) element.innerHTML = markup;
}
if (note === null) node.querySelector('[data-studio-module-note]')?.remove();
else noteModule(node, note);
if (entry.fixed) {
const following = followingFixed.get(entry.parent);
if (following) following.before(node);
else entry.parent.append(node);
followingFixed.set(entry.parent, node);
} else {
const following = followingFixed.get(end) || end;
following.before(node);
followingFixed.set(end, node);
}
}
sections = state.sections.map(({entry}) => entry);
deletedSections = [...state.deleted];
for (const {name, value} of state.settings) {
pageInput(name).val(value);
}
syncPageFromInputs();
renderLayers();
historyObserver?.takeRecords();
syncHistoryButtons();
$studio.find('[data-canvas-status]').text(direction < 0 ? '已撤销。' : '已重做。');
return true;
}
function historyShortcut(event) {
if (!(event.ctrlKey || event.metaKey) || event.altKey || event.target.closest?.('dialog, [type="search"]')) return;
const key = event.key.toLowerCase();
if (key !== 'z' && key !== 'y') return;
event.preventDefault();
stepHistory(key === 'y' || event.shiftKey ? 1 : -1);
}
$history.on('click', function () { stepHistory(this.dataset.canvasHistory === 'undo' ? -1 : 1); });
$layout.on('keydown.canvasHistory', historyShortcut);
$settings.on('input change', ':input', function (event) {
const group = event.type === 'input' && this.matches('input:not([type=hidden]), textarea') ? this : null;
captureHistory(group);
});
function attachCanvas() { function attachCanvas() {
doc = $frame.get(0).contentDocument; doc = $frame.get(0).contentDocument;
if (!doc?.querySelector('[data-studio-field]') || doc.documentElement.hasAttribute('data-studio-editing')) return; if (!doc?.querySelector('[data-studio-field]') || doc.documentElement.hasAttribute('data-studio-editing')) return;
@@ -1238,15 +1746,28 @@ jQuery(function ($) {
bindPage($doc); bindPage($doc);
selectBody(null); selectBody(null);
selectElement(null); selectElement(null);
$pending.empty().prop('hidden', true);
sections = []; sections = [];
deletedSections = []; deletedSections = [];
$doc.find('[data-studio-section]').each((_, section) => registerSection(section)); $doc.find('[data-studio-section]').each((_, section) => registerSection(section));
renderLayers();
initialOrder = canvasOrder();
syncPagePresentation();
savedSettings = JSON.stringify(settingsSnapshot());
history.length = 0;
historyIndex = 0;
lastHistoryGroup = null;
captureHistory();
historyObserver?.disconnect();
historyObserver = new MutationObserver(() => captureHistory(mediaDrag || null));
historyObserver.observe(doc.querySelector('#main-content'), {
subtree: true, childList: true, characterData: true, attributes: true,
attributeFilter: ['class', 'href', 'target', 'rel', 'hidden', 'src', 'poster', 'alt', 'value', 'max'],
});
$doc.on('focusin.canvas', '[contenteditable]', function () { $doc.on('focusin.canvas', '[contenteditable]', function () {
selectBody(this.dataset.studioPart === 'body' ? this : null); selectBody(this.dataset.studioPart === 'body' ? this : null);
}); });
$doc.on('selectionchange.canvas', rememberSelection).on('scroll.canvas', positionSelection); $doc.on('selectionchange.canvas mouseup.canvas keyup.canvas', rememberSelection).on('scroll.canvas', positionSelection);
$doc.on('click.canvas auxclick.canvas', 'a', (event) => event.preventDefault()); $doc.on('click.canvas auxclick.canvas', 'a', (event) => event.preventDefault());
$doc.on('click.canvas dblclick.canvas', mediaTargets, function (event) { $doc.on('click.canvas dblclick.canvas', mediaTargets, function (event) {
event.preventDefault(); event.preventDefault();
@@ -1270,7 +1791,8 @@ jQuery(function ($) {
return; return;
} }
const field = node.closest?.(canvasFields); const field = node.closest?.(canvasFields);
selectElement(doc.getSelection()?.isCollapsed ? field || editableBodyElement(node) : null); selectElement(doc.getSelection()?.isCollapsed ? field || editableBodyElement(node)
|| node.closest?.('[data-studio-part="body"], [data-studio-section], [data-studio-style-field]') : null);
}); });
$doc.on('dblclick.canvas', '[data-studio-part="body"] a', function (event) { $doc.on('dblclick.canvas', '[data-studio-part="body"] a', function (event) {
event.preventDefault(); event.preventDefault();
@@ -1278,6 +1800,7 @@ jQuery(function ($) {
}); });
$doc.on('keydown.canvas', (event) => { $doc.on('keydown.canvas', (event) => {
if (event.key === 'Escape') selectElement(null); if (event.key === 'Escape') selectElement(null);
historyShortcut(event);
}); });
$doc.on('keydown.canvas', '[data-studio-dynamic]', function (event) { $doc.on('keydown.canvas', '[data-studio-dynamic]', function (event) {
if ((event.key === 'Enter' || event.key === ' ') && event.target === this) { if ((event.key === 'Enter' || event.key === ' ') && event.target === this) {
@@ -1299,6 +1822,35 @@ jQuery(function ($) {
event.preventDefault(); event.preventDefault();
} }
}); });
$doc.on('keydown.canvas', '[contenteditable="true"]', function (event) {
if (event.key === 'Enter' && !event.originalEvent?.isComposing && !event.ctrlKey && !event.metaKey && !event.altKey) {
event.preventDefault();
doc.execCommand('insertLineBreak');
}
});
$doc.on('beforeinput.canvas', '[contenteditable]', function (event) {
const kind = event.originalEvent?.inputType;
if (kind === 'historyUndo' || kind === 'historyRedo') {
event.preventDefault();
stepHistory(kind === 'historyUndo' ? -1 : 1);
return;
}
const style = {formatBold: 'weight', formatItalic: 'slant', formatStrikeThrough: 'strike'}[kind];
if (style && this.contentEditable === 'true') {
event.preventDefault();
rememberSelection();
applyTextStyle(style);
}
}).on('input.canvas', '[contenteditable]', function (event) {
rememberSelection();
if (this.dataset.studioPart === 'title') {
const entry = sections.find(({node}) => node === this.closest('[data-studio-section]'));
if (entry) refreshLayerTitle(entry);
}
const type = event.originalEvent?.inputType;
const typing = ['insertText', 'insertCompositionText', 'deleteContentBackward', 'deleteContentForward'].includes(type);
captureHistory(typing ? this : null);
});
$doc.on('paste.canvas drop.canvas', '[contenteditable]', (event) => { $doc.on('paste.canvas drop.canvas', '[contenteditable]', (event) => {
event.preventDefault(); event.preventDefault();
if (event.type === 'paste') { if (event.type === 'paste') {
@@ -1306,22 +1858,12 @@ jQuery(function ($) {
} }
}); });
$toolbar.prop('hidden', false); $toolbar.prop('hidden', false);
$layout.find('[data-canvas-jump]').prop('hidden', false);
$layout.find('[data-canvas-template], [data-canvas-element], [data-hero-control]').prop('disabled', false); $layout.find('[data-canvas-template], [data-canvas-element], [data-hero-control]').prop('disabled', false);
$presets.triggerHandler('studio:canvas-ready'); $presets.triggerHandler('studio:canvas-ready');
} }
$frame.on('load', attachCanvas); $frame.on('load', attachCanvas);
if ($frame.contents().find('[data-studio-field]').length) attachCanvas(); if ($frame.contents().find('[data-studio-field]').length) attachCanvas();
$studio.closest('.studio-layout').on('click', '[data-canvas-jump]', function () {
const section = doc?.getElementById(this.dataset.canvasJump);
const body = section?.querySelector('[data-studio-part="body"]');
if (!body) return;
$studio.get(0).scrollIntoView({block: 'start'});
section.scrollIntoView({block: 'start'});
if (section.hasAttribute('data-studio-dynamic')) selectElement(section);
else body.focus({preventScroll: true});
});
}); });
$('[data-rich-canvas]').each(function () { $('[data-rich-canvas]').each(function () {
+2
View File
@@ -27,6 +27,7 @@ CREATE TABLE IF NOT EXISTS pages (
alt TEXT NOT NULL, alt TEXT NOT NULL,
image_scale INTEGER NOT NULL DEFAULT 0, image_scale INTEGER NOT NULL DEFAULT 0,
alignments TEXT NOT NULL DEFAULT '{}', alignments TEXT NOT NULL DEFAULT '{}',
presentation TEXT NOT NULL DEFAULT '{}',
actions TEXT NOT NULL, actions TEXT NOT NULL,
quicklinks TEXT NOT NULL, quicklinks TEXT NOT NULL,
theme TEXT NOT NULL DEFAULT '', theme TEXT NOT NULL DEFAULT '',
@@ -46,6 +47,7 @@ CREATE TABLE IF NOT EXISTS sections (
style TEXT NOT NULL DEFAULT 'plain', style TEXT NOT NULL DEFAULT 'plain',
feed TEXT, feed TEXT,
alignments TEXT NOT NULL DEFAULT '{}', alignments TEXT NOT NULL DEFAULT '{}',
presentation TEXT NOT NULL DEFAULT '{}',
body TEXT NOT NULL, body TEXT NOT NULL,
position INTEGER NOT NULL, position INTEGER NOT NULL,
version INTEGER NOT NULL DEFAULT 0, version INTEGER NOT NULL DEFAULT 0,