forked from laysense/laysite
Add live canvas layers, element styles and undo history
This commit is contained in:
@@ -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.1.0 更新画布功能时,更新脚本会添加页面和区块的样式字段。手动更新源码后,运行 `php bin/install.php` 再启动 Webman。
|
||||
|
||||
## 生产反代
|
||||
|
||||
在 `.env` 配置 `LAYSITE_SITE_URL=https://example.com` 和 `LAYSITE_SECURE_COOKIES=1`。下列示例假定代理和 Webman 在同一主机。代理应以实际访客来源覆盖 `X-Real-IP`,并将项目文件、数据库和媒体存储保持在公开根目录之外。
|
||||
|
||||
@@ -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}';
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use Throwable;
|
||||
|
||||
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.
|
||||
public const NEXT_ARTICLE_ID = 'MAX(COALESCE((SELECT MAX(id) FROM articles), 0),
|
||||
COALESCE((SELECT MAX(article_id) FROM article_deletions), 0)) + 1';
|
||||
@@ -54,6 +54,14 @@ final class Database
|
||||
throw new RuntimeException('当前 SQLite 数据库需要更新版本的 LaySite。');
|
||||
}
|
||||
$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 pages
|
||||
(slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
|
||||
|
||||
@@ -16,11 +16,11 @@ final class Html
|
||||
|
||||
private const TAGS = [
|
||||
'a' => ['href', 'target', 'rel'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [],
|
||||
'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
|
||||
'dl' => [], 'dt' => [], 'em' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [],
|
||||
'button' => [], 'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
|
||||
'dl' => [], 'dt' => [], 'em' => [], 'figure' => [], 'figcaption' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [],
|
||||
'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'],
|
||||
'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' => [],
|
||||
'th' => ['scope', 'colspan', 'rowspan'], 'thead' => [], 'tr' => [], 'ul' => [],
|
||||
'video' => ['src', 'controls', 'muted', 'playsinline', 'poster', 'preload'],
|
||||
@@ -154,6 +154,9 @@ final class Html
|
||||
$element->removeAttribute('rel');
|
||||
}
|
||||
}
|
||||
if ($element->tagName === 'button') {
|
||||
$element->setAttribute('type', 'button');
|
||||
}
|
||||
self::sanitizeChildren($element);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,11 @@ final class PageDraft
|
||||
$key = $kind . '_id';
|
||||
$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 (!is_array($input['visibility'])) {
|
||||
throw new RuntimeException('页面显示选项无效。');
|
||||
@@ -55,8 +59,11 @@ final class PageDraft
|
||||
$page['sections'] = self::sections($input['sections']);
|
||||
if (!array_key_exists('actions', $input)) {
|
||||
$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));
|
||||
}
|
||||
|
||||
|
||||
+43
-18
@@ -62,7 +62,7 @@ final class Repository
|
||||
if (!$page) {
|
||||
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);
|
||||
}
|
||||
$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]);
|
||||
}
|
||||
|
||||
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 = ?,
|
||||
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([
|
||||
$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']),
|
||||
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());
|
||||
if ($replaceDraftSections) {
|
||||
@@ -107,6 +108,9 @@ final class Repository
|
||||
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
|
||||
{
|
||||
$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 = ?');
|
||||
$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());
|
||||
}
|
||||
|
||||
@@ -136,9 +140,9 @@ final class Repository
|
||||
|
||||
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)
|
||||
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 = $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 = ?');
|
||||
$query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $data['alignments'] ?? '{}', $data['presentation'] ?? '{}', $page]);
|
||||
if ($query->rowCount() !== 1) {
|
||||
throw new RuntimeException('此区块锚点已被使用。');
|
||||
}
|
||||
@@ -149,10 +153,20 @@ final class Repository
|
||||
$query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?');
|
||||
$query->execute([$page, $key, $version]);
|
||||
self::checkVersion($query->rowCount());
|
||||
$pdo->prepare("UPDATE pages SET
|
||||
quicklinks = (SELECT json_group_array(json(value)) FROM json_each(quicklinks) WHERE json_extract(value, '$[0]') <> :anchor),
|
||||
actions = (SELECT json_group_array(json(value)) FROM json_each(actions) WHERE json_extract(value, '$[0]') <> :anchor)
|
||||
WHERE slug = :slug")->execute(['anchor' => '#' . $key, 'slug' => $page]);
|
||||
$query = $pdo->prepare('SELECT actions, quicklinks, presentation FROM pages WHERE slug = ?');
|
||||
$query->execute([$page]);
|
||||
$row = $query->fetch();
|
||||
$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
|
||||
@@ -182,14 +196,25 @@ final class Repository
|
||||
return;
|
||||
}
|
||||
[$keys[$index], $keys[$other]] = [$keys[$other], $keys[$index]];
|
||||
$query = $pdo->prepare('UPDATE sections SET position = ? WHERE page_slug = ? AND key = ?');
|
||||
foreach ($keys as $position => $section) {
|
||||
$query->execute([$position, $page, $section]);
|
||||
}
|
||||
self::writeSectionOrder($pdo, $page, $keys);
|
||||
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
|
||||
{
|
||||
$revision = $structureChanged ? ', version = version + 1' : '';
|
||||
|
||||
@@ -185,6 +185,7 @@ final class SiteBackup
|
||||
$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['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']])) {
|
||||
$row['theme'] = '';
|
||||
}
|
||||
@@ -199,6 +200,7 @@ final class SiteBackup
|
||||
throw new RuntimeException('备份包含未知区块样式。');
|
||||
}
|
||||
$row['body'] = Html::sanitize($row['body'] ?? '');
|
||||
$row['presentation'] = Database::json(CanvasStyle::normalize(self::decode($row['presentation'] ?? '{}'), CanvasStyle::SECTION));
|
||||
if (isset($row['feed'])) {
|
||||
$feed = self::decode($row['feed']);
|
||||
if (!in_array($feed['mode'] ?? '', ['merged', 'tabs', 'network', 'catalog'], true)
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace App\Controller;
|
||||
|
||||
use App\Content\BlockTemplates;
|
||||
use App\Content\Buttons;
|
||||
use App\Content\CanvasStyle;
|
||||
use App\Content\DesignLibrary;
|
||||
use App\Content\Database;
|
||||
use App\Content\Html;
|
||||
@@ -285,6 +286,9 @@ class AdminController
|
||||
$data['alignments'] = $request->post('alignments') === null ? $page['alignments']
|
||||
: $this->alignmentMap(json_decode($this->input($request, 'alignments'), true), ['heading', 'lead', 'actions', 'image']);
|
||||
$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'));
|
||||
if ($data['name'] === '' || mb_strlen($data['name']) > 100 || !in_array($data['status'], ['draft', 'published'], true)
|
||||
|| $data['title'] === '' || mb_strlen($data['title']) > 160 ||
|
||||
@@ -296,7 +300,15 @@ class AdminController
|
||||
throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。');
|
||||
}
|
||||
$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');
|
||||
} catch (RuntimeException $exception) {
|
||||
@@ -366,10 +378,12 @@ class AdminController
|
||||
$version = $change['version'] ?? null;
|
||||
$fields = $change['fields'] ?? [];
|
||||
$alignments = $change['alignments'] ?? null;
|
||||
$presentation = $change['presentation'] ?? null;
|
||||
$feed = $change['feed'] ?? null;
|
||||
$delete = ($change['delete'] ?? false) === true;
|
||||
$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))
|
||||
: (!isset($available[$key]) || !is_int($version) || $version !== (int) $available[$key]['version']))) {
|
||||
throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。');
|
||||
@@ -419,6 +433,9 @@ class AdminController
|
||||
if ($alignments !== null) {
|
||||
$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']);
|
||||
if (isset($fields['body'])) {
|
||||
$section['body'] = Html::sanitize($section['body']);
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Content\Assets;
|
||||
use App\Content\CanvasStyle;
|
||||
use App\Content\Html;
|
||||
use App\Content\Repository;
|
||||
use App\Content\View;
|
||||
@@ -223,6 +224,15 @@ final class SiteController
|
||||
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
|
||||
{
|
||||
$path = $request->path();
|
||||
|
||||
+29
-2
@@ -41,11 +41,20 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
|
||||
<div class="editor-toolbar studio-canvas-toolbar" data-canvas-toolbar hidden aria-label="正文工具">
|
||||
<div>
|
||||
<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="link">插入链接</button>
|
||||
<button type="button" data-canvas-command="media">插入媒体</button>
|
||||
</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>
|
||||
</div>
|
||||
<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>
|
||||
<?php endforeach ?>
|
||||
</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>
|
||||
<?php endforeach ?>
|
||||
</div>
|
||||
@@ -68,6 +77,22 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
|
||||
</div>
|
||||
</div>
|
||||
<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">
|
||||
<div class="admin-heading compact"><h2 id="canvas-properties-heading" data-property-heading>编辑属性</h2></div>
|
||||
<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="version" value="<?= $e($page['version']) ?>">
|
||||
<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'])) ?>">
|
||||
<details class="studio-hero-settings">
|
||||
<summary>首屏与目录</summary>
|
||||
|
||||
@@ -43,6 +43,7 @@ $showFooter = $page['visibility']['footer'] ?? true;
|
||||
<?php endif ?>
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<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 ($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>
|
||||
|
||||
+17
-11
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Content\Buttons;
|
||||
use App\Content\CanvasStyle;
|
||||
use App\Content\View;
|
||||
|
||||
$e = View::escape(...);
|
||||
@@ -8,12 +8,16 @@ $home = $page['slug'] === 'home';
|
||||
$showHero = $page['visibility']['hero'] ?? true;
|
||||
$heroLinks = array_filter($page['sections'], static fn (array $section): bool => $section['style'] === 'hero-links');
|
||||
$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 . '"' : '';
|
||||
$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 || $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): ?>
|
||||
<div class="wrap hero-inner<?= $page['image'] === '' ? ' hero-text-only' : '' ?>"<?= $canvas ? ' data-studio-hero-content' : '' ?><?= $showHero ? '' : ' hidden' ?>>
|
||||
<div class="hero-copy">
|
||||
@@ -32,16 +36,17 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' .
|
||||
<?php else: ?>
|
||||
<p class="overline hero-label"><?= $e($site['name']) ?></p>
|
||||
<?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>
|
||||
<p class="hero-lead<?= View::alignmentClass($alignments['lead'] ?? null) ?>"<?= $field('lead') ?><?= $alignField('lead') ?>><?= $e($page['lead']) ?></p>
|
||||
<div class="actions hero-actions<?= View::alignmentClass($alignments['actions'] ?? null) ?>"<?= $alignField('actions') ?>>
|
||||
<?php foreach (Buttons::validate($page['actions']) as $index => [$url, $label, $style, $blank]): ?>
|
||||
<a class="<?= $e(Buttons::css($style)) ?>" href="<?= $e($url) ?>"<?= Buttons::target($blank) ?><?= $canvas ? ' data-studio-action="' . $index . '"' : '' ?>><?= $e($label) ?></a>
|
||||
<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) ?><?= $style('lead') ?>"<?= $field('lead') ?><?= $alignField('lead') ?><?= $styleField('lead') ?>><?= $text('lead', $page['lead']) ?></p>
|
||||
<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, $buttonStyle, $blank]): ?>
|
||||
<?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 ?>
|
||||
</div>
|
||||
</div>
|
||||
<?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' : '' ?>>
|
||||
</div>
|
||||
<?php endif ?>
|
||||
@@ -53,10 +58,11 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' .
|
||||
</section>
|
||||
<?php endif ?>
|
||||
<?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">
|
||||
<?php foreach ($page['quicklinks'] as [$url, $label]): ?>
|
||||
<a href="<?= $e($url) ?>"><?= $e($label) ?></a>
|
||||
<?php foreach ($page['quicklinks'] as $index => [$url, $label]): ?>
|
||||
<?php $role = 'nav-' . $index; ?>
|
||||
<a class="<?= trim($style($role)) ?>" href="<?= $e($url) ?>"<?= $styleField($role) ?>><?= $text($role, $label) ?></a>
|
||||
<?php endforeach ?>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
+10
-6
@@ -1,19 +1,23 @@
|
||||
<?php
|
||||
use App\Content\CanvasStyle;
|
||||
use App\Content\View;
|
||||
|
||||
$e = View::escape(...);
|
||||
$canvas ??= false;
|
||||
$body = $section['body'];
|
||||
$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'])) . '"' : '';
|
||||
if ($canvas && $dynamic) {
|
||||
$studio .= ' data-studio-dynamic data-studio-feed="' . $e($section['feed']) . '" tabindex="0"';
|
||||
}
|
||||
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 ?>
|
||||
<div<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $body ?></div>
|
||||
<div class="<?= trim($style('body')) ?>"<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $body ?></div>
|
||||
</div>
|
||||
<?php
|
||||
return;
|
||||
@@ -26,11 +30,11 @@ if ($dynamic && $body === '<p><a class="back-link" href="/articles">查看全部
|
||||
$network = $section['networkFeed'] ?? 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="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>
|
||||
<?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 ?>
|
||||
<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 class="<?= trim(View::alignmentClass($alignments['lead'] ?? null) . $style('lead')) ?>"<?= $canvas ? ' data-studio-part="lead"' : '' ?>><?= $text('lead') ?></p><?php endif ?>
|
||||
</div>
|
||||
<?php if ($network): ?>
|
||||
<?php foreach ($section['articleFeed'] as $group): ?>
|
||||
@@ -49,6 +53,6 @@ $catalog = $section['catalogFeed'] ?? false;
|
||||
<?php elseif (!empty($section['articleFeed'])): ?>
|
||||
<?= View::fragment('article-feed', ['groups' => $section['articleFeed'], 'sectionKey' => $section['key'], 'archivePath' => $section['archivePath']]) ?>
|
||||
<?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>
|
||||
</section>
|
||||
|
||||
@@ -4,6 +4,8 @@ $paths = [
|
||||
'center' => '<path d="M3 6h18M6 10h12M3 14h18M6 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"/>',
|
||||
'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"/>',
|
||||
'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"/>',
|
||||
|
||||
@@ -4,15 +4,15 @@ use App\Content\View;
|
||||
|
||||
$e = View::escape(...);
|
||||
?>
|
||||
<details class="studio-layers" id="blocks">
|
||||
<details class="studio-layers" id="blocks" open>
|
||||
<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 $fixedSlot = $item['style'] === 'hero-links'; ?>
|
||||
<li>
|
||||
<div><strong><?= $e($item['title']) ?></strong><small>#<?= $e($item['key']) ?></small></div>
|
||||
<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>
|
||||
<form method="post" action="/admin/page-blocks/<?= $e($slug) ?>">
|
||||
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
|
||||
|
||||
@@ -26,6 +26,7 @@ Route::get('/articles/{slug:[a-z0-9-]+}', [SiteController::class, 'article']);
|
||||
Route::get('/robots.txt', [SiteController::class, 'robots']);
|
||||
Route::get('/sitemap.xml', [SiteController::class, 'sitemap']);
|
||||
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::post('/admin/logout', [AdminController::class, 'logout']);
|
||||
|
||||
@@ -62,6 +62,11 @@
|
||||
.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-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; }
|
||||
.preview-selector { display: flex; gap: .35rem; flex-wrap: wrap; }
|
||||
.preview-selector [aria-pressed="true"] { background: var(--accent-light); color: var(--accent-deep); }
|
||||
|
||||
@@ -115,7 +115,7 @@ address { font-style: normal; }
|
||||
}
|
||||
.hero-label { margin-bottom: 1.4rem; }
|
||||
.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-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; }
|
||||
@@ -387,6 +387,8 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
|
||||
.catalog-content .actions { margin-top: auto; padding-top: 1rem; }
|
||||
|
||||
.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; }
|
||||
[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],
|
||||
|
||||
+596
-54
@@ -308,7 +308,7 @@ jQuery(function ($) {
|
||||
const buttonClasses = {solid: 'button-primary', outline: 'button-outline', underline: 'button-underline', plain: 'button-plain'};
|
||||
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 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 $handle = $studio.find('[data-media-handle]');
|
||||
const $mediaSize = $sizing.find('[data-media-size]');
|
||||
@@ -352,6 +352,14 @@ jQuery(function ($) {
|
||||
});
|
||||
const $toolbar = $studio.find('[data-canvas-toolbar]');
|
||||
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 $propertyForm = $properties.find('form');
|
||||
const $propertyError = $properties.find('[data-property-error]');
|
||||
@@ -363,17 +371,134 @@ jQuery(function ($) {
|
||||
const propertyInput = (name) => $propertyForm.find('[name="' + name + '"]');
|
||||
const pageInput = (name) => $settings.find('[name="' + name + '"]');
|
||||
const settingsSnapshot = () => $settings.serializeArray()
|
||||
.filter(({name}) => name !== 'csrf' && name !== 'canvas_sections');
|
||||
const savedSettings = JSON.stringify(settingsSnapshot());
|
||||
.filter(({name}) => !['csrf', 'canvas_sections', 'canvas_order'].includes(name));
|
||||
let savedSettings = JSON.stringify(settingsSnapshot());
|
||||
let dialogAction;
|
||||
let doc;
|
||||
let activeBody;
|
||||
let savedRange;
|
||||
let textRange;
|
||||
let textHost;
|
||||
let sections = [];
|
||||
let initialOrder;
|
||||
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) {
|
||||
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 aligned = {};
|
||||
let alignmentChanged = false;
|
||||
@@ -383,36 +508,40 @@ jQuery(function ($) {
|
||||
if (value) aligned[field] = value;
|
||||
if (value !== initialAlignment) alignmentChanged = true;
|
||||
}
|
||||
let value = field === 'body' ? node.innerHTML : node.textContent;
|
||||
if (field === 'body' && node.contains(selectedElement)) {
|
||||
const copy = node.cloneNode(true);
|
||||
$(copy).find('[data-studio-selected]').removeAttr('data-studio-selected');
|
||||
value = copy.innerHTML;
|
||||
}
|
||||
const value = field === 'body' ? cleanBody(node) : plainText(node);
|
||||
if (version === null || value !== initial) {
|
||||
changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value;
|
||||
}
|
||||
}
|
||||
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};
|
||||
if (alignmentChanged || (version === null && Object.keys(aligned).length)) edit.alignments = aligned;
|
||||
if (template) edit.template = template;
|
||||
if (copyOf) edit.copyOf = copyOf;
|
||||
if (feedChanged) edit.feed = feed;
|
||||
if (presentationChanged || version === null && Object.keys(presentation).length) edit.presentation = presentation;
|
||||
return [edit];
|
||||
});
|
||||
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:busy', (_event, busy) => {
|
||||
$layout.prop('inert', busy);
|
||||
$settings.prop('inert', busy);
|
||||
});
|
||||
$(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.originalEvent.returnValue = '';
|
||||
}
|
||||
@@ -452,8 +581,18 @@ jQuery(function ($) {
|
||||
|
||||
function rememberSelection() {
|
||||
const selection = doc.getSelection();
|
||||
if (selection.rangeCount && activeBody?.contains(selection.anchorNode) && activeBody.contains(selection.focusNode)) {
|
||||
savedRange = selection.getRangeAt(0).cloneRange();
|
||||
if (!selection.rangeCount) return;
|
||||
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();
|
||||
}
|
||||
|
||||
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('click', '[data-canvas-command]', function () {
|
||||
const command = this.dataset.canvasCommand;
|
||||
@@ -502,13 +779,13 @@ jQuery(function ($) {
|
||||
});
|
||||
});
|
||||
} else {
|
||||
const commands = {heading: ['formatBlock', 'h3'], bold: ['bold'], list: ['insertUnorderedList']};
|
||||
const commands = {heading: ['formatBlock', 'h3'], list: ['insertUnorderedList']};
|
||||
edit(...commands[command]);
|
||||
}
|
||||
});
|
||||
|
||||
function configureText(node, label, placeholder = false) {
|
||||
node.contentEditable = 'plaintext-only';
|
||||
function configureText(node, label, placeholder = false, rich = true) {
|
||||
node.contentEditable = rich ? 'true' : 'plaintext-only';
|
||||
node.setAttribute('aria-label', label);
|
||||
if (placeholder) node.dataset.studioPlaceholder = label;
|
||||
}
|
||||
@@ -528,9 +805,11 @@ jQuery(function ($) {
|
||||
const field = this.dataset.studioField;
|
||||
const $target = $(this);
|
||||
const $input = pageInput(field);
|
||||
configureText(this, labels[field], ['accent', 'lead'].includes(field));
|
||||
$target.text($input.val()).on('input', () => $input.val($target.text()));
|
||||
$input.on('input.canvas', () => $target.text($input.val()));
|
||||
configureText(this, labels[field], ['accent', 'lead'].includes(field), field !== 'name');
|
||||
$target.on('input', () => $input.val(plainText(this)));
|
||||
$input.on('input.canvas', () => {
|
||||
if ($input.val() !== plainText(this)) paintText(this, $input.val());
|
||||
});
|
||||
});
|
||||
|
||||
const $image = $doc.find('[data-studio-hero-image]');
|
||||
@@ -562,16 +841,28 @@ jQuery(function ($) {
|
||||
|
||||
const $heroActions = $doc.find('.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),
|
||||
]);
|
||||
let actions = readActions();
|
||||
|
||||
function syncActions() {
|
||||
$actionsInput.val(JSON.stringify(actions));
|
||||
const presentation = pagePresentation();
|
||||
$heroActions.empty();
|
||||
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);
|
||||
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) {
|
||||
@@ -595,6 +886,9 @@ jQuery(function ($) {
|
||||
heroControls.set('edit-action', editAction);
|
||||
heroControls.set('change-action', (index, copy) => {
|
||||
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]]] : []));
|
||||
syncActions();
|
||||
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]/);
|
||||
function syncNavigation() {
|
||||
const lines = navLines();
|
||||
const presentation = pagePresentation();
|
||||
$navContent.empty();
|
||||
for (const [index, line] of lines.entries()) {
|
||||
if (!line.trim()) continue;
|
||||
@@ -621,6 +916,8 @@ jQuery(function ($) {
|
||||
link.href = safeLink(url) ? url : '#';
|
||||
link.textContent = label || url;
|
||||
link.dataset.studioNavIndex = index;
|
||||
link.dataset.studioStyleField = 'nav-' + $navContent.children().length;
|
||||
setPageStyle(link, presentation[link.dataset.studioStyleField]);
|
||||
$(link).on('dblclick studio:properties', (event) => {
|
||||
event.preventDefault();
|
||||
openProperties('本页目录链接', {label, url}, (next) => {
|
||||
@@ -641,6 +938,10 @@ jQuery(function ($) {
|
||||
heroControls.set('change-nav', (index, copy) => {
|
||||
const lines = navLines();
|
||||
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]] : []));
|
||||
$navInput.val(lines.join('\n'));
|
||||
syncNavigation();
|
||||
@@ -649,11 +950,15 @@ jQuery(function ($) {
|
||||
$navInput.on('input.canvas', syncNavigation);
|
||||
heroControls.set('remove-section-links', (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) => {
|
||||
const separator = line.indexOf('|');
|
||||
return separator < 0 || line.slice(separator + 1).trim() !== anchor;
|
||||
}).join('\n'));
|
||||
syncNavigation();
|
||||
remapPageStyles('action', actionOrder);
|
||||
actions = actions.filter(([url]) => url !== anchor);
|
||||
syncActions();
|
||||
});
|
||||
@@ -664,6 +969,28 @@ jQuery(function ($) {
|
||||
});
|
||||
});
|
||||
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) {
|
||||
@@ -748,12 +1075,14 @@ jQuery(function ($) {
|
||||
} else if (!feed && !node.hidden) {
|
||||
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(
|
||||
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);
|
||||
return entry;
|
||||
}
|
||||
@@ -849,7 +1178,7 @@ jQuery(function ($) {
|
||||
if (!node) return null;
|
||||
const hero = node.closest('[data-studio-align-field]');
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -862,37 +1191,45 @@ jQuery(function ($) {
|
||||
function selectElement(node) {
|
||||
selectionObserver?.disconnect();
|
||||
selectedElement?.removeAttribute('data-studio-selected');
|
||||
if (node && textHost && !node.contains(textHost) && !textHost.contains(node)) {
|
||||
textHost = null;
|
||||
textRange = null;
|
||||
}
|
||||
selectedElement = node;
|
||||
const dynamic = node?.hasAttribute('data-studio-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;
|
||||
$sizing.prop('hidden', !selectedMedia);
|
||||
if (node) {
|
||||
node.setAttribute('data-studio-selected', '');
|
||||
const target = sizingTarget();
|
||||
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 canCopy = dynamic || inBody || (nav && $(node).siblings().length < 19) || (action && $(node).siblings().length < 7);
|
||||
const hasProperties = !dynamic && (selectedMedia || node.matches('a, progress'));
|
||||
const aligned = dynamic ? null : alignmentTarget(node);
|
||||
syncAlignmentButtons(aligned);
|
||||
$elementTools.find('[data-element-copy]').prop('hidden', !canCopy);
|
||||
const sectionRoot = node.hasAttribute('data-studio-section');
|
||||
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})
|
||||
.prop('hidden', !dynamic && !inBody && !selectedMedia && !node.matches(canvasFields));
|
||||
.prop('hidden', !sectionRoot && !inBody && !selectedMedia && !node.matches(canvasFields));
|
||||
$elementTools.find('[data-element-properties]').prop('hidden', !hasProperties);
|
||||
if (target) showMediaWidth(currentMediaWidth(target));
|
||||
selectionObserver?.observe(target || aligned || node);
|
||||
}
|
||||
syncFormatControls();
|
||||
positionSelection();
|
||||
}
|
||||
|
||||
function changeElement(copy) {
|
||||
const node = selectedElement;
|
||||
if (!node?.isConnected) return;
|
||||
if (node.hasAttribute('data-studio-dynamic')) {
|
||||
if (node.hasAttribute('data-studio-section')) {
|
||||
changeModule(sections.find((section) => section.node === node), copy);
|
||||
return;
|
||||
}
|
||||
@@ -906,7 +1243,7 @@ jQuery(function ($) {
|
||||
changeModule(sections.find((section) => section.node === node.closest('[data-studio-section]')), false);
|
||||
return;
|
||||
}
|
||||
const inBody = node.closest('[data-studio-part="body"]') !== null;
|
||||
const inBody = Boolean(node.parentElement?.closest('[data-studio-part="body"]'));
|
||||
selectElement(null);
|
||||
if (inBody) {
|
||||
if (copy) {
|
||||
@@ -1001,6 +1338,7 @@ jQuery(function ($) {
|
||||
fields.title.node.textContent = title;
|
||||
fields.lead.node.textContent = moduleInput('module_lead').val().trim();
|
||||
noteModule(node, '模块设置将在保存页面后更新。');
|
||||
refreshLayerTitle(editedModule);
|
||||
$moduleDialog.get(0).close();
|
||||
positionSelection();
|
||||
});
|
||||
@@ -1009,13 +1347,70 @@ jQuery(function ($) {
|
||||
return 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
function addPending(section) {
|
||||
const $button = $('<button>', {type: 'button', text: '取消新增:' + section.fields.title.node.textContent});
|
||||
section.$pending = $('<li>').append($button).appendTo($pending);
|
||||
$pending.prop('hidden', false);
|
||||
$button.on('click', () => removeSection(section));
|
||||
function refreshLayerTitle(section) {
|
||||
const title = plainText(section.fields.title.node) || '未命名区块';
|
||||
$layers.children().filter((_, node) => node.dataset.layerKey === section.key).find('[data-layer-title]').text(title);
|
||||
}
|
||||
|
||||
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) {
|
||||
if (section.node.contains(activeBody)) selectBody(null);
|
||||
if (section.node.contains(selectedElement)) selectElement(null);
|
||||
@@ -1023,8 +1418,7 @@ jQuery(function ($) {
|
||||
section.node.remove();
|
||||
sections = sections.filter((entry) => entry !== section);
|
||||
heroControls.get('remove-section-links')(section.key);
|
||||
section.$pending?.remove();
|
||||
$pending.prop('hidden', !$pending.children().length);
|
||||
renderLayers();
|
||||
}
|
||||
|
||||
function scopeTemplateIds(root, prefix, oldKey = '') {
|
||||
@@ -1065,8 +1459,8 @@ jQuery(function ($) {
|
||||
clone.dataset.studioFeed = JSON.stringify(section.feed);
|
||||
doc.querySelector('[data-studio-section-end]').before(clone);
|
||||
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});
|
||||
addPending(entry);
|
||||
registerSection(clone, null, {template: copyOf ? null : section.template, copyOf});
|
||||
renderLayers();
|
||||
noteModule(clone, '模块副本将在保存页面后生效。');
|
||||
clone.scrollIntoView({block: 'start'});
|
||||
selectElement(clone);
|
||||
@@ -1222,13 +1616,127 @@ jQuery(function ($) {
|
||||
}
|
||||
end.before(section);
|
||||
const entry = registerSection(section, null, {template});
|
||||
addPending(entry);
|
||||
renderLayers();
|
||||
section.scrollIntoView({block: 'start'});
|
||||
if (feed) selectElement(section);
|
||||
else entry.fields.body.node.focus({preventScroll: true});
|
||||
$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() {
|
||||
doc = $frame.get(0).contentDocument;
|
||||
if (!doc?.querySelector('[data-studio-field]') || doc.documentElement.hasAttribute('data-studio-editing')) return;
|
||||
@@ -1238,15 +1746,28 @@ jQuery(function ($) {
|
||||
bindPage($doc);
|
||||
selectBody(null);
|
||||
selectElement(null);
|
||||
$pending.empty().prop('hidden', true);
|
||||
sections = [];
|
||||
deletedSections = [];
|
||||
$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 () {
|
||||
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 dblclick.canvas', mediaTargets, function (event) {
|
||||
event.preventDefault();
|
||||
@@ -1270,7 +1791,8 @@ jQuery(function ($) {
|
||||
return;
|
||||
}
|
||||
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) {
|
||||
event.preventDefault();
|
||||
@@ -1278,6 +1800,7 @@ jQuery(function ($) {
|
||||
});
|
||||
$doc.on('keydown.canvas', (event) => {
|
||||
if (event.key === 'Escape') selectElement(null);
|
||||
historyShortcut(event);
|
||||
});
|
||||
$doc.on('keydown.canvas', '[data-studio-dynamic]', function (event) {
|
||||
if ((event.key === 'Enter' || event.key === ' ') && event.target === this) {
|
||||
@@ -1299,6 +1822,35 @@ jQuery(function ($) {
|
||||
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) => {
|
||||
event.preventDefault();
|
||||
if (event.type === 'paste') {
|
||||
@@ -1306,22 +1858,12 @@ jQuery(function ($) {
|
||||
}
|
||||
});
|
||||
$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);
|
||||
$presets.triggerHandler('studio:canvas-ready');
|
||||
}
|
||||
|
||||
$frame.on('load', 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 () {
|
||||
|
||||
@@ -27,6 +27,7 @@ CREATE TABLE IF NOT EXISTS pages (
|
||||
alt TEXT NOT NULL,
|
||||
image_scale INTEGER NOT NULL DEFAULT 0,
|
||||
alignments TEXT NOT NULL DEFAULT '{}',
|
||||
presentation TEXT NOT NULL DEFAULT '{}',
|
||||
actions TEXT NOT NULL,
|
||||
quicklinks TEXT NOT NULL,
|
||||
theme TEXT NOT NULL DEFAULT '',
|
||||
@@ -46,6 +47,7 @@ CREATE TABLE IF NOT EXISTS sections (
|
||||
style TEXT NOT NULL DEFAULT 'plain',
|
||||
feed TEXT,
|
||||
alignments TEXT NOT NULL DEFAULT '{}',
|
||||
presentation TEXT NOT NULL DEFAULT '{}',
|
||||
body TEXT NOT NULL,
|
||||
position INTEGER NOT NULL,
|
||||
version INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
Reference in New Issue
Block a user