Manage dynamic blocks and expand the editor library

This commit is contained in:
2026-11-22 00:59:59 +08:00
parent 828dfc09f9
commit 92354d7e4a
63 changed files with 671 additions and 188 deletions
+3 -3
View File
@@ -28,10 +28,10 @@ php bin/admin.php reset admin@example.com
## 后台编辑 ## 后台编辑
- **网站后台**可按名称、地址或发布状态查找页面,从列表打开画布、公开页或草稿预览。 - **网站后台**可按名称、地址或发布状态查找页面,从列表打开画布、公开页或草稿预览。
- **页面设计**支持新建草稿、发布和撤回。首屏标题与简介可在桌面或手机画布中直接编辑。区块支持新增、排序、删除、可视化编辑、媒体插入和 HTML 源码。单击画布元素可用浮动工具条复制或删除。选中媒体后,可拖动边缘手柄调整宽度。浮动工具条可将正文元素、区块标题和首屏元素对齐到左侧、中央或右侧。编辑器左侧分为「组件」「元素」「图层」。先进入分类,再查找并插入模板或基础元素。悬停或键盘聚焦缩略图可放大,点击可打开预览。 - **页面设计**支持新建草稿、发布和撤回。首屏标题与简介可在桌面或手机画布中直接编辑。区块支持新增、排序、删除、可视化编辑、媒体插入和 HTML 源码。单击画布元素可用浮动工具条复制或删除。选中媒体后,可拖动边缘手柄调整宽度。浮动工具条可将正文元素、区块标题和首屏元素对齐到左侧、中央或右侧。编辑器左侧分为「组件」「元素」「图层」。先进入分类,再查找并插入模板或基础元素。已有五个内置页面的首屏图文和正文区块都可复用,徽标、按钮组、面包屑、进度、通知和折叠等元素参考 [Preline UI 免费组件文档](https://preline.co/docs/index.html),用本站样式实现。悬停或键盘聚焦缩略图可放大,点击可打开预览。
- **媒体库**集中列出项目静态文件及上传文件,支持查找、选取、复制路径、改名和归档。归档资源的已有 URL 保持可访问。上传文件放在 `LAYSENSE_MEDIA_DIR`,由 `/assets/uploads/` 提供。 - **媒体库**集中列出项目静态文件及上传文件,支持查找、选取、复制路径、改名和归档。归档资源的已有 URL 保持可访问。上传文件放在 `LAYSENSE_MEDIA_DIR`,由 `/assets/uploads/` 提供。
- **文章**使用自托管的 TOAST UI Editor 3.2.2(MIT)。Markdown 左侧源码、右侧实时预览,富文本使用所见即所得模式。文章可以加入多个分类,可在「管理分类」创建新分类。 - **文章**使用自托管的 TOAST UI Editor 3.2.2(MIT)。Markdown 左侧源码、右侧实时预览,富文本使用所见即所得模式。文章可以加入多个分类,可在「管理分类」创建新分类。
- **分类文章**支持在任意页面添加,保存区块后在「图层」中编辑分类、展示数量和合并或标签页模式。「查看全部动态」和翻页只列出该区块所选的分类。 - **分类文章**支持在任意页面添加,选中动态模块后可用浮动工具条打开设置、复制或删除,随页面一起保存。文章列表和项目与伙伴卡片共用分类设置。「查看全部动态」和翻页只列出该区块所选的分类。
- **产品与服务**(`/services`)和**支持项目与合作伙伴**(`/network`)由文章分类生成。通过文章的目录卡片设置图片、链接和排序,使用草稿状态可从目录撤下。 - **产品与服务**(`/services`)和**支持项目与合作伙伴**(`/network`)由文章分类生成。通过文章的目录卡片设置图片、链接和排序,使用草稿状态可从目录撤下。
- **网站设置**分别编辑页头标志、导航及按钮,和页脚的公司信息、产品、公司及资源链接和备注。页脚设置可恢复原站内容。CDN 设置接受 HTTPS 源站地址。浏览器看到的公开 `/assets/…` 路径使用该源站。 - **网站设置**分别编辑页头标志、导航及按钮,和页脚的公司信息、产品、公司及资源链接和备注。页脚设置可恢复原站内容。CDN 设置接受 HTTPS 源站地址。浏览器看到的公开 `/assets/…` 路径使用该源站。
- 文章支持摘要和标签。状态选「草稿」可撤回公开文章。已发布文章改网址标识后,旧标识会自动跳转。 - 文章支持摘要和标签。状态选「草稿」可撤回公开文章。已发布文章改网址标识后,旧标识会自动跳转。
@@ -71,7 +71,7 @@ location = /admin/media {
| `LAYSENSE_SECURE_COOKIES` | 默认关闭 · 本地 HTTP 使用默认值。生产 HTTPS 设置为 `1`。 | | `LAYSENSE_SECURE_COOKIES` | 默认关闭 · 本地 HTTP 使用默认值。生产 HTTPS 设置为 `1`。 |
| `LAYSENSE_TRUSTED_PROXIES` | 默认 `127.0.0.1,::1` · 逗号分隔的受信反代 IP,设为空字符串可关闭信任 | | `LAYSENSE_TRUSTED_PROXIES` | 默认 `127.0.0.1,::1` · 逗号分隔的受信反代 IP,设为空字符串可关闭信任 |
SQLite 已启用 WAL。使用上一版多分类文章结构的站点,可用当前 `LAYSENSE_DB` 运行 `php bin/install.php` 增加对齐字段,之后重启 Webman。全新安装时,将 `LAYSENSE_DB` 指向新文件并按上面的步骤初始化和创建管理员。安装会预载网站自带页面、文章、产品和伙伴目录。服务用户需要对 SQLite 目录、媒体目录和 `runtime/` 有写权限。备份可用 `sqlite3 storage/laysense.sqlite ".backup 'laysense-backup.sqlite'"`,媒体目录单独保存。 SQLite 已启用 WAL。使用上一版多分类文章结构的站点,可用当前 `LAYSENSE_DB` 运行 `php bin/install.php` 增量安装,之后重启 Webman。首页五联导航和伙伴动态模块会作为可管理区块导入一次。全新安装时,将 `LAYSENSE_DB` 指向新文件并按上面的步骤初始化和创建管理员。安装会预载网站自带页面、文章、产品和伙伴目录。服务用户需要对 SQLite 目录、媒体目录和 `runtime/` 有写权限。备份可用 `sqlite3 storage/laysense.sqlite ".backup 'laysense-backup.sqlite'"`,媒体目录单独保存。
### CDN ### CDN
+54 -2
View File
@@ -8,6 +8,10 @@ final class BlockTemplates
{ {
public const ARTICLE_FEED = '{"categories":["announcement","news","product"],"mode":"merged","limit":6}'; public const ARTICLE_FEED = '{"categories":["announcement","news","product"],"mode":"merged","limit":6}';
public const NETWORK_FEED = '{"categories":["supported-projects","partners"],"mode":"network","limit":30}';
public const PRODUCT_LINKS = '<div class="hero-directory"><a class="overline directory-label" href="/services">产品与服务</a><a href="/pagepan"><span>PAGEPAN</span><small>可视化建站</small></a><a href="/highspeaker"><span>HighSpeaker DNS</span><small>开源智能解析</small></a><a href="/sc"><span>软著代理</span><small>登记申请与材料服务</small></a><a href="/shnu-sc"><span>SHNU 学生</span><small>软著申请方案</small></a></div>';
public const ELEMENT_GROUPS = [ public const ELEMENT_GROUPS = [
'text-elements' => ['文字与列表', [ 'text-elements' => ['文字与列表', [
'paragraph' => ['段落', '<p>填写正文。</p>'], 'paragraph' => ['段落', '<p>填写正文。</p>'],
@@ -16,24 +20,39 @@ final class BlockTemplates
'blockquote' => ['引用', '<blockquote><p>填写需要引用的内容。</p></blockquote>'], 'blockquote' => ['引用', '<blockquote><p>填写需要引用的内容。</p></blockquote>'],
'bullet-list' => ['项目列表', '<ul><li>填写列表项</li><li>填写列表项</li></ul>'], 'bullet-list' => ['项目列表', '<ul><li>填写列表项</li><li>填写列表项</li></ul>'],
'ordered-list' => ['编号列表', '<ol><li>填写第一项</li><li>填写第二项</li></ol>'], 'ordered-list' => ['编号列表', '<ol><li>填写第一项</li><li>填写第二项</li></ol>'],
'heading-kicker' => ['标题眉标', '<p class="overline">填写分类名称</p>'],
'tag' => ['徽标', '<p><span class="studio-badge">填写标签</span></p>'],
'large-number' => ['重点数字', '<p class="price-value">填写数字</p>'],
'definition-list' => ['术语说明', '<dl class="studio-definitions"><dt>填写术语</dt><dd>填写术语说明。</dd></dl>'], 'definition-list' => ['术语说明', '<dl class="studio-definitions"><dt>填写术语</dt><dd>填写术语说明。</dd></dl>'],
]], ]],
'link-elements' => ['链接与按钮', [ 'link-elements' => ['链接与按钮', [
'button' => ['主按钮', '<p><a class="button button-primary" href="#contact">联系来笙</a></p>'], 'button' => ['主按钮', '<p><a class="button button-primary" href="#contact">联系来笙</a></p>'],
'outline-button' => ['描边按钮', '<p><a class="button button-outline" href="/services">查看服务</a></p>'], 'outline-button' => ['描边按钮', '<p><a class="button button-outline" href="/services">查看服务</a></p>'],
'text-link' => ['文字链接', '<p><a href="/articles">阅读文章</a></p>'], 'text-link' => ['文字链接', '<p><a href="/articles">阅读文章</a></p>'],
'button-group' => ['按钮组', '<div class="actions studio-button-group"><a class="button button-primary" href="/services">查看服务</a><a class="button button-outline" href="#contact">联系团队</a></div>'],
'breadcrumbs' => ['面包屑', '<p class="breadcrumbs"><a href="/">首页</a><span> / </span><span>当前页面</span></p>'],
'download-link' => ['下载入口', '<p><a class="button button-outline" href="/pagepan#download">查看下载</a></p>'],
'email-link' => ['邮件链接', '<p><a href="mailto:hello@example.com">发送邮件</a></p>'], 'email-link' => ['邮件链接', '<p><a href="mailto:hello@example.com">发送邮件</a></p>'],
]], ]],
'media-elements' => ['图片与影音', [ 'media-elements' => ['图片与影音', [
'image' => ['图片', '', 'image/'], 'image' => ['图片', '', 'image/'],
'video' => ['视频', '', 'video/'], 'video' => ['视频', '', 'video/'],
'audio' => ['音频', '', 'audio/'], 'audio' => ['音频', '', 'audio/'],
'qr-image' => ['二维码', '', 'image/'],
'image-link' => ['图片链接', '<p><a href="/pagepan"><img src="/assets/original/pagepan-example.webp" alt="PAGEPAN 产品预览" loading="lazy"></a></p>'],
]], ]],
'structure-elements' => ['版式与数据', [ 'structure-elements' => ['版式与数据', [
'separator' => ['分割线', '<hr class="studio-divider">'], 'separator' => ['分割线', '<hr class="studio-divider">'],
'spacer' => ['留白', '<div class="studio-spacer"></div>'], 'spacer' => ['留白', '<div class="studio-spacer"></div>'],
'code' => ['代码块', '<pre class="studio-code"><code>填写代码</code></pre>'], 'code' => ['代码块', '<pre class="studio-code"><code>填写代码</code></pre>'],
'basic-table' => ['数据表格', '<table><thead><tr><th scope="col">名称</th><th scope="col">数据</th></tr></thead><tbody><tr><td>填写名称</td><td>填写数据</td></tr></tbody></table>'], 'basic-table' => ['数据表格', '<table><thead><tr><th scope="col">名称</th><th scope="col">数据</th></tr></thead><tbody><tr><td>填写名称</td><td>填写数据</td></tr></tbody></table>'],
'progress' => ['进度条', '<div class="studio-progress"><p>完成进度</p><progress max="100" value="65">65%</progress></div>'],
'alert' => ['提示卡', '<div class="studio-notice"><p><strong>请注意</strong></p><p>填写一条提示信息。</p></div>'],
'simple-card' => ['内容卡片', '<article class="content-card"><h3>填写卡片标题</h3><p>填写卡片内容。</p></article>'],
'link-card' => ['链接卡片', '<article class="content-card"><h3>查看资料</h3><p>填写链接指向的资料说明。</p><a href="/articles">打开资料</a></article>'],
'list-group' => ['列表组', '<ul class="studio-resources"><li><a href="/services">产品与服务</a><span>目录</span></li><li><a href="/articles">来笙动态</a><span>文章</span></li></ul>'],
'empty-card' => ['空状态', '<div class="studio-empty"><h3>暂无内容</h3><p>填写访客可以执行的下一步。</p><a href="/articles">查看站点动态</a></div>'],
'status-note' => ['状态提示', '<div class="studio-notice studio-success-note"><p><strong>已完成</strong></p><p>填写操作结果或服务状态。</p></div>'],
'disclosure' => ['折叠内容', '<div class="faq"><details><summary>填写折叠标题</summary><div><p>填写展开后的内容。</p></div></details></div>'], 'disclosure' => ['折叠内容', '<div class="faq"><details><summary>填写折叠标题</summary><div><p>填写展开后的内容。</p></div></details></div>'],
]], ]],
]; ];
@@ -42,7 +61,8 @@ final class BlockTemplates
'content' => ['标题与正文', [ 'content' => ['标题与正文', [
'headline' => ['标题与简介', '<div class="studio-intro"><h3>填写区块标题</h3><p>用一句话补充背景或说明。</p></div>'], 'headline' => ['标题与简介', '<div class="studio-intro"><h3>填写区块标题</h3><p>用一句话补充背景或说明。</p></div>'],
'text' => ['正文', '<p>在这里输入区块内容。</p>'], 'text' => ['正文', '<p>在这里输入区块内容。</p>'],
'articles' => ['分类文章', ''], 'articles' => ['分类文章', '', '', self::ARTICLE_FEED],
'network' => ['支持项目与合作伙伴', '', '', self::NETWORK_FEED],
'list' => ['步骤列表', '<ol><li>填写第一步</li><li>填写第二步</li><li>填写第三步</li></ol>'], 'list' => ['步骤列表', '<ol><li>填写第一步</li><li>填写第二步</li><li>填写第三步</li></ol>'],
'notice' => ['重点提示', '<div class="studio-notice"><h3>填写重要提示</h3><p>说明访客需要知悉的事项、条件或时间。</p></div>'], 'notice' => ['重点提示', '<div class="studio-notice"><h3>填写重要提示</h3><p>说明访客需要知悉的事项、条件或时间。</p></div>'],
]], ]],
@@ -74,6 +94,7 @@ final class BlockTemplates
'pricing' => ['双方案报价', '<div class="card-grid price-grid studio-pricing"><article class="content-card price-card"><h3>基础方案</h3><p class="price-value">填写价格</p><p>填写方案包含的服务。</p><a class="button button-outline" href="/#contact">咨询基础方案</a></article><article class="content-card price-card"><h3>进阶方案</h3><p class="price-value">填写价格</p><p>填写扩展服务或权益。</p><a class="button button-primary" href="/#contact">咨询进阶方案</a></article></div>'], 'pricing' => ['双方案报价', '<div class="card-grid price-grid studio-pricing"><article class="content-card price-card"><h3>基础方案</h3><p class="price-value">填写价格</p><p>填写方案包含的服务。</p><a class="button button-outline" href="/#contact">咨询基础方案</a></article><article class="content-card price-card"><h3>进阶方案</h3><p class="price-value">填写价格</p><p>填写扩展服务或权益。</p><a class="button button-primary" href="/#contact">咨询进阶方案</a></article></div>'],
]], ]],
'actions' => ['导航与引导', [ 'actions' => ['导航与引导', [
'product-links' => ['产品与服务五联导航', self::PRODUCT_LINKS],
'navigation' => ['快速导航', '<ul class="studio-quick-nav"><li><a href="/services">产品与服务</a></li><li><a href="/articles">动态与文章</a></li><li><a href="/#contact">联系来笙</a></li></ul>'], 'navigation' => ['快速导航', '<ul class="studio-quick-nav"><li><a href="/services">产品与服务</a></li><li><a href="/articles">动态与文章</a></li><li><a href="/#contact">联系来笙</a></li></ul>'],
'cta' => ['行动按钮', '<p>说明下一步。</p><p><a class="button button-primary" href="#contact">联系来笙</a></p>'], 'cta' => ['行动按钮', '<p>说明下一步。</p><p><a class="button button-primary" href="#contact">联系来笙</a></p>'],
'resources' => ['资料与链接', '<ul class="studio-resources"><li><a href="/pagepan#download">获取 PAGEPAN</a><span>应用下载</span></li><li><a href="/articles">浏览动态与文档</a><span>网站资源</span></li></ul>'], 'resources' => ['资料与链接', '<ul class="studio-resources"><li><a href="/pagepan#download">获取 PAGEPAN</a><span>应用下载</span></li><li><a href="/articles">浏览动态与文档</a><span>网站资源</span></li></ul>'],
@@ -81,9 +102,40 @@ final class BlockTemplates
]], ]],
]; ];
public static function groups(): array
{
static $groups;
if ($groups !== null) {
return $groups;
}
$groups = self::GROUPS;
$seed = json_decode(file_get_contents(dirname(__DIR__, 2) . '/resources/seed.json'), true, flags: JSON_THROW_ON_ERROR);
foreach ($seed['pages'] as $page) {
$links = '';
foreach ($page['actions'] as [$url, $label]) {
$links .= '<a class="button button-outline" href="' . View::escape($url) . '">' . View::escape($label) . '</a>';
}
$hero = '<div class="studio-cover"><img src="' . View::escape($page['image']) . '" alt="' . View::escape($page['alt']) . '" loading="lazy">'
. '<div><h3>' . View::escape(trim($page['heading'] . ' ' . $page['accent'])) . '</h3><p>' . View::escape($page['lead'])
. '</p><div class="actions">' . $links . '</div></div></div>';
$items = ['existing-' . $page['slug'] . '-hero' => ['首屏图文', $hero]];
foreach ($page['sections'] as $section) {
$items['existing-' . $page['slug'] . '-' . $section['key']] = [
$section['title'], Html::sanitize($section['body']), $section['lead'],
isset($section['feed']) ? Database::json($section['feed']) : null,
$section['style'],
];
}
$groups['existing-' . $page['slug']] = ['现有页面 · ' . $page['name'], $items];
}
return $groups;
}
public static function find(string $key): ?array public static function find(string $key): ?array
{ {
foreach (self::GROUPS as [, $templates]) { foreach (self::groups() as [, $templates]) {
if (isset($templates[$key])) { if (isset($templates[$key])) {
return $templates[$key]; return $templates[$key];
} }
+14
View File
@@ -75,6 +75,20 @@ final class Database
} }
} }
if ((int) $pdo->query('PRAGMA user_version')->fetchColumn() === 0) {
$heroDirectory = $pdo->prepare("INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, position)
VALUES ('home', 'hero-directory', '产品与服务导航', '', 'hero-links', ?, -1)");
$heroDirectory->execute([BlockTemplates::PRODUCT_LINKS]);
$network = $pdo->prepare("INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, position)
SELECT 'home', 'network', '支持项目与合作伙伴', '', 'plain', '', ?, COALESCE(MAX(position), -1) + 1
FROM sections WHERE page_slug = 'home'");
$network->execute([BlockTemplates::NETWORK_FEED]);
if ($heroDirectory->rowCount() + $network->rowCount() > 0) {
$pdo->exec("UPDATE pages SET version = version + 1 WHERE slug = 'home'");
}
$pdo->exec('PRAGMA user_version = 1');
}
$category = $pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)'); $category = $pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
foreach (Repository::CATEGORIES as $slug => $name) { foreach (Repository::CATEGORIES as $slug => $name) {
$category->execute([$slug, $name]); $category->execute([$slug, $name]);
+17 -1
View File
@@ -88,7 +88,7 @@ final class Html
return $result; return $result;
} }
public static function sanitize(string $html): string public static function sanitize(string $html, ?string $anchorPrefix = null): string
{ {
$document = new DOMDocument('1.0', 'UTF-8'); $document = new DOMDocument('1.0', 'UTF-8');
$document->loadHTML('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' . $html . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET); $document->loadHTML('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' . $html . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
@@ -97,6 +97,22 @@ final class Html
return ''; return '';
} }
self::sanitizeChildren($body); self::sanitizeChildren($body);
if ($anchorPrefix !== null) {
$ids = [];
foreach ($body->getElementsByTagName('*') as $element) {
$id = $element->getAttribute('id');
if ($id !== '') {
$ids[$id] = $anchorPrefix . '-' . $id;
$element->setAttribute('id', $ids[$id]);
}
}
foreach ($body->getElementsByTagName('a') as $link) {
$href = $link->getAttribute('href');
if (str_starts_with($href, '#') && isset($ids[substr($href, 1)])) {
$link->setAttribute('href', '#' . $ids[substr($href, 1)]);
}
}
}
$output = ''; $output = '';
foreach ($body->childNodes as $child) { foreach ($body->childNodes as $child) {
$output .= $document->saveHTML($child); $output .= $document->saveHTML($child);
+15 -8
View File
@@ -86,7 +86,9 @@ final class Repository
]); ]);
self::checkVersion($query->rowCount()); self::checkVersion($query->rowCount());
foreach ($sections as $section) { foreach ($sections as $section) {
if ($section['version'] === null) { if (!empty($section['delete'])) {
self::deleteSection($pdo, $slug, $section['key'], $section['version']);
} elseif ($section['version'] === null) {
self::insertSection($pdo, $slug, $section['key'], $section); self::insertSection($pdo, $slug, $section['key'], $section);
} else { } else {
self::updateSection($pdo, $slug, $section['key'], $section, $section['version']); self::updateSection($pdo, $slug, $section['key'], $section, $section['version']);
@@ -111,10 +113,10 @@ final class Repository
self::checkVersion($query->rowCount()); self::checkVersion($query->rowCount());
} }
public function createSection(string $page, string $key, string $title, string $style, string $body, ?string $feed = null): void public function createSection(string $page, string $key, string $title, string $style, string $body, ?string $feed = null, string $lead = ''): void
{ {
Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body, $feed): void { Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body, $feed, $lead): void {
self::insertSection($pdo, $page, $key, compact('title', 'style', 'body', 'feed') + ['lead' => '']); self::insertSection($pdo, $page, $key, compact('title', 'style', 'body', 'feed', 'lead'));
self::touchPage($pdo, $page, structureChanged: true); self::touchPage($pdo, $page, structureChanged: true);
}); });
} }
@@ -129,6 +131,13 @@ final class Repository
} }
} }
private static function deleteSection(PDO $pdo, string $page, string $key, int $version): void
{
$query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?');
$query->execute([$page, $key, $version]);
self::checkVersion($query->rowCount());
}
public function arrangeSection(string $page, string $key, string $operation, int $version, int $pageVersion): void public function arrangeSection(string $page, string $key, string $operation, int $version, int $pageVersion): void
{ {
Database::write(function (PDO $pdo) use ($page, $key, $operation, $version, $pageVersion): void { Database::write(function (PDO $pdo) use ($page, $key, $operation, $version, $pageVersion): void {
@@ -137,14 +146,12 @@ final class Repository
$revision = $current->fetchColumn(); $revision = $current->fetchColumn();
self::checkVersion($revision !== false && (int) $revision === $pageVersion ? 1 : 0); self::checkVersion($revision !== false && (int) $revision === $pageVersion ? 1 : 0);
if ($operation === 'delete') { if ($operation === 'delete') {
$query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?'); self::deleteSection($pdo, $page, $key, $version);
$query->execute([$page, $key, $version]);
self::checkVersion($query->rowCount());
self::touchPage($pdo, $page, structureChanged: true); self::touchPage($pdo, $page, structureChanged: true);
return; return;
} }
$query = $pdo->prepare('SELECT key, version FROM sections WHERE page_slug = ? ORDER BY position, key'); $query = $pdo->prepare("SELECT key, version FROM sections WHERE page_slug = ? AND style <> 'hero-links' ORDER BY position, key");
$query->execute([$page]); $query->execute([$page]);
$revisions = $query->fetchAll(PDO::FETCH_KEY_PAIR); $revisions = $query->fetchAll(PDO::FETCH_KEY_PAIR);
if (!array_key_exists($key, $revisions)) { if (!array_key_exists($key, $revisions)) {
+46 -13
View File
@@ -268,7 +268,7 @@ class AdminController
strlen($data['image']) > 1000 || ($data['image'] !== '' && !Html::url($data['image'], true)) || !$validButtons) { strlen($data['image']) > 1000 || ($data['image'] !== '' && !Html::url($data['image'], true)) || !$validButtons) {
throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。'); throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。');
} }
$sections = $this->canvasSections($request->post('canvas_sections', ''), $page['sections']); $sections = $this->canvasSections($request->post('canvas_sections', ''), $page['sections'], $repo->categories());
$repo->savePage($slug, $data, $this->version($request), $sections); $repo->savePage($slug, $data, $this->version($request), $sections);
return $this->success($request, '/admin/pages/' . $slug . '?saved=1'); return $this->success($request, '/admin/pages/' . $slug . '?saved=1');
@@ -278,7 +278,7 @@ class AdminController
} }
return $this->render($request, 'admin-page', [ return $this->render($request, 'admin-page', [
'title' => '编辑 ' . $page['name'], 'page' => $page, 'wideAdmin' => true, 'error' => $error, 'saved' => $request->get('saved') === '1', 'title' => '编辑 ' . $page['name'], 'page' => $page, 'categories' => $repo->categories(), 'wideAdmin' => true, 'error' => $error, 'saved' => $request->get('saved') === '1',
], $error !== '' ? 422 : 200); ], $error !== '' ? 422 : 200);
} }
@@ -299,12 +299,12 @@ class AdminController
$data = [ $data = [
'title' => $this->input($request, 'title'), 'lead' => $this->input($request, 'lead'), 'title' => $this->input($request, 'title'), 'lead' => $this->input($request, 'lead'),
'body' => $this->input($request, 'body'), 'body' => $this->input($request, 'body'),
'style' => $request->post('style') === null ? $section['style'] : $this->input($request, 'style'), 'style' => $savedStyle === 'hero-links' || $request->post('style') === null ? $savedStyle : $this->input($request, 'style'),
'feed' => $section['feed'], 'feed' => $section['feed'],
]; ];
$section = array_replace($section, $data, ['version' => $this->version($request)]); $section = array_replace($section, $data, ['version' => $this->version($request)]);
try { try {
if ($request->post('feed_mode') !== null) { if ($savedStyle !== 'hero-links' && $request->post('feed_mode') !== null) {
$data['feed'] = $section['feed'] = $this->feedInput($request, $categories); $data['feed'] = $section['feed'] = $this->feedInput($request, $categories);
} }
$this->checkSection($data, $savedStyle); $this->checkSection($data, $savedStyle);
@@ -322,7 +322,7 @@ class AdminController
], $error !== '' ? 422 : 200); ], $error !== '' ? 422 : 200);
} }
private function canvasSections(mixed $payload, array $sections): array private function canvasSections(mixed $payload, array $sections, array $categories): array
{ {
if ($payload === '') { if ($payload === '') {
return []; return [];
@@ -336,15 +336,46 @@ class AdminController
foreach ($changes as $change) { foreach ($changes as $change) {
$key = $change['key'] ?? null; $key = $change['key'] ?? null;
$version = $change['version'] ?? null; $version = $change['version'] ?? null;
$fields = $change['fields'] ?? null; $fields = $change['fields'] ?? [];
$alignments = $change['alignments'] ?? null; $alignments = $change['alignments'] ?? null;
$feed = $change['feed'] ?? null;
$delete = ($change['delete'] ?? false) === true;
$isNew = is_array($change) && array_key_exists('version', $change) && $version === null; $isNew = is_array($change) && array_key_exists('version', $change) && $version === null;
if (!is_string($key) || isset($updates[$key]) || !is_array($fields) || ($fields === [] && $alignments === null) if (!is_string($key) || isset($updates[$key]) || !is_array($fields) || (!$delete && $fields === [] && $alignments === null && $feed === null)
|| ($isNew ? (isset($available[$key]) || !preg_match('/^block-[a-f0-9]{32}$/D', $key)) || ($isNew ? (isset($available[$key]) || !preg_match('/^block-[a-f0-9]{32}$/D', $key))
: (!isset($available[$key]) || !is_int($version) || $version !== (int) $available[$key]['version']))) { : (!isset($available[$key]) || !is_int($version) || $version !== (int) $available[$key]['version']))) {
throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。'); throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。');
} }
if ($delete) {
if ($isNew || empty($available[$key]['feed'])) {
throw new RuntimeException('此区块不能通过模块工具删除。');
}
$updates[$key] = compact('key', 'version', 'delete');
continue;
}
$section = $available[$key] ?? ['key' => $key, 'title' => '', 'lead' => '', 'body' => '', 'style' => 'plain']; $section = $available[$key] ?? ['key' => $key, 'title' => '', 'lead' => '', 'body' => '', 'style' => 'plain'];
if ($isNew && isset($change['template'])) {
$preset = is_string($change['template']) ? BlockTemplates::find($change['template']) : null;
if ($preset === null) {
throw new RuntimeException('区块模板已失效。');
}
$section['feed'] = $preset[3] ?? null;
$section['style'] = $preset[4] ?? 'plain';
}
if ($isNew && isset($change['copyOf'])) {
$source = $change['copyOf']['key'] ?? null;
$sourceVersion = $change['copyOf']['version'] ?? null;
if (!is_string($source) || empty($available[$source]['feed']) || $sourceVersion !== (int) $available[$source]['version']) {
throw new RuntimeException('原模块已变更,请刷新画布后再复制。');
}
$section = array_replace($available[$source], ['key' => $key]);
}
if ($feed !== null) {
if (!is_array($feed) || empty($section['feed'])) {
throw new RuntimeException('模块设置不正确。');
}
$section['feed'] = $this->encodeFeed($feed['mode'] ?? null, $feed['categories'] ?? null, $feed['limit'] ?? null, $categories);
}
foreach ($fields as $field => $value) { foreach ($fields as $field => $value) {
if (!in_array($field, ['title', 'lead', 'body'], true)) { if (!in_array($field, ['title', 'lead', 'body'], true)) {
throw new RuntimeException('画布内容无效。'); throw new RuntimeException('画布内容无效。');
@@ -364,9 +395,6 @@ class AdminController
if (isset($fields['body'])) { if (isset($fields['body'])) {
$section['body'] = Html::sanitize($section['body']); $section['body'] = Html::sanitize($section['body']);
} }
if ($isNew && ($change['template'] ?? null) === 'articles') {
$section['feed'] = BlockTemplates::ARTICLE_FEED;
}
$section['version'] = $version; $section['version'] = $version;
$updates[$key] = $section; $updates[$key] = $section;
} }
@@ -546,9 +574,14 @@ class AdminController
if ($mode === 'off') { if ($mode === 'off') {
return null; return null;
} }
$categories = $this->selectedCategories($request->post('feed_categories')); return $this->encodeFeed($mode, $request->post('feed_categories'), $this->input($request, 'feed_limit'), $available);
$limit = filter_var($this->input($request, 'feed_limit'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 30]]); }
if (!in_array($mode, ['merged', 'tabs'], true) || !$categories || array_diff($categories, array_keys($available)) || $limit === false) {
private function encodeFeed(mixed $mode, mixed $selected, mixed $value, array $available): string
{
$categories = $this->selectedCategories($selected);
$limit = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 30]]);
if (!in_array($mode, ['merged', 'tabs', 'network'], true) || !$categories || array_diff($categories, array_keys($available)) || $limit === false) {
throw new RuntimeException('请选择文章分类,并将展示数量设为 1 至 30。'); throw new RuntimeException('请选择文章分类,并将展示数量设为 1 至 30。');
} }
+10 -5
View File
@@ -37,14 +37,20 @@ final class SiteController
continue; continue;
} }
$feed = json_decode($section['feed'], true, flags: JSON_THROW_ON_ERROR); $feed = json_decode($section['feed'], true, flags: JSON_THROW_ON_ERROR);
$tabs = $feed['mode'] === 'tabs' && count($feed['categories']) > 1; $network = $feed['mode'] === 'network';
$grouped = $network || ($feed['mode'] === 'tabs' && count($feed['categories']) > 1);
$archivePath = '/articles/feed/' . $slug . '/' . $section['key'];
if ($network && count($feed['categories']) === 2 && !array_diff($feed['categories'], ['supported-projects', 'partners'])) {
$archivePath = '/network';
}
$section['archivePath'] = $page['status'] === 'published' ? $archivePath : null;
$section['articleFeed'] = []; $section['articleFeed'] = [];
$section['archivePath'] = $page['status'] === 'published' ? '/articles/feed/' . $slug . '/' . $section['key'] : null; $section['networkFeed'] = $network;
foreach ($tabs ? $feed['categories'] : [''] as $category) { foreach ($grouped ? $feed['categories'] : [''] as $category) {
$selected = $category === '' ? $feed['categories'] : [$category]; $selected = $category === '' ? $feed['categories'] : [$category];
$section['articleFeed'][] = [ $section['articleFeed'][] = [
'categories' => $selected, 'label' => $categories[$category] ?? '', 'categories' => $selected, 'label' => $categories[$category] ?? '',
'articles' => $repo->articles($selected, limit: $feed['limit']), 'articles' => $repo->articles($selected, limit: $feed['limit'], directoryOrder: $network),
]; ];
} }
} }
@@ -58,7 +64,6 @@ final class SiteController
'description' => $page['description'], 'description' => $page['description'],
'socialImage' => $page['image'], 'socialImage' => $page['image'],
'socialAlt' => $page['alt'], 'socialAlt' => $page['alt'],
'network' => $isHome ? $this->networkGroups($repo) : [],
'previewMode' => $preview, 'canvas' => $preview && $canvas, 'noindex' => $preview, 'previewMode' => $preview, 'canvas' => $preview && $canvas, 'noindex' => $preview,
]); ]);
} }
+1 -1
View File
@@ -74,7 +74,7 @@ final class StudioController extends AdminController
if ($preset === null) { if ($preset === null) {
throw new RuntimeException('请选择区块类型。'); throw new RuntimeException('请选择区块类型。');
} }
$repo->createSection($slug, $key, $preset[0], 'plain', $preset[1], $type === 'articles' ? BlockTemplates::ARTICLE_FEED : null); $repo->createSection($slug, $key, $preset[0], $preset[4] ?? 'plain', Html::sanitize($preset[1], $key), $preset[3] ?? null, $preset[2] ?? '');
return $this->success($request, "/admin/pages/$slug/$key"); return $this->success($request, "/admin/pages/$slug/$key");
} }
+39 -9
View File
@@ -10,8 +10,10 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
?> ?>
<a class="back-link" href="/admin">返回页面</a> <a class="back-link" href="/admin">返回页面</a>
<header class="admin-heading"> <header class="admin-heading">
<div><h1><?= $e($title) ?></h1><p><?= $e($path) ?> · <?= $page['status'] === 'draft' ? '草稿' : '已发布' ?></p></div> <div><h1><?= $e($title) ?></h1><p class="studio-page-meta"><code><?= $e($path) ?></code>
<span class="dashboard-page-state" data-published="<?= $page['status'] === 'published' ? 'true' : 'false' ?>"><?= $page['status'] === 'draft' ? '草稿' : '已发布' ?></span></p></div>
<div class="actions"> <div class="actions">
<a class="button button-outline" href="#studio-page-settings">页面设置</a>
<?php if ($page['status'] === 'published'): ?><a class="button button-outline" href="<?= $e($path) ?>">公开页面</a><?php endif ?> <?php if ($page['status'] === 'published'): ?><a class="button button-outline" href="<?= $e($path) ?>">公开页面</a><?php endif ?>
<a class="button button-outline" href="<?= $e($previewUrl) ?>" target="_blank" rel="noopener">打开预览</a> <a class="button button-outline" href="<?= $e($previewUrl) ?>" target="_blank" rel="noopener">打开预览</a>
</div> </div>
@@ -20,7 +22,10 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
<div class="studio-layout"> <div class="studio-layout">
<aside class="admin-panel studio-library" aria-labelledby="studio-library-title"> <aside class="admin-panel studio-library" aria-labelledby="studio-library-title">
<h2 id="studio-library-title">页面编辑</h2> <h2 id="studio-library-title">页面编辑</h2>
<?= View::fragment('studio-templates', ['layers' => View::fragment('studio-layers', compact('page', 'slug', 'token'))]) ?> <?= View::fragment('studio-templates', [
'layers' => View::fragment('studio-layers', compact('page', 'slug', 'token')),
'anchorForm' => View::fragment('studio-anchor-form', compact('slug', 'token')),
]) ?>
</aside> </aside>
<div class="studio-workspace"> <div class="studio-workspace">
<section class="admin-panel studio-preview" data-preview-studio aria-labelledby="studio-preview-title"> <section class="admin-panel studio-preview" data-preview-studio aria-labelledby="studio-preview-title">
@@ -45,13 +50,13 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
<iframe title="可编辑页面画布" src="<?= $e($previewUrl) ?>?canvas=1" sandbox="allow-same-origin"></iframe> <iframe title="可编辑页面画布" src="<?= $e($previewUrl) ?>?canvas=1" sandbox="allow-same-origin"></iframe>
<div class="studio-element-tools" data-element-tools role="group" aria-label="所选元素" hidden> <div class="studio-element-tools" data-element-tools role="group" aria-label="所选元素" hidden>
<div class="studio-element-align" data-element-align role="group" aria-label="对齐"> <div class="studio-element-align" data-element-align role="group" aria-label="对齐">
<button type="button" data-align="left" aria-pressed="false">居左</button> <?php foreach (['left' => '居左', 'center' => '居中', 'right' => '居右'] as $value => $label): ?>
<button type="button" data-align="center" aria-pressed="false">居中</button> <button type="button" data-align="<?= $value ?>" aria-pressed="false" aria-label="<?= $label ?>" title="<?= $label ?>"><?= View::fragment('studio-icon', ['icon' => $value]) ?></button>
<button type="button" data-align="right" aria-pressed="false">居右</button> <?php endforeach ?>
</div> </div>
<button type="button" data-element-properties>属性</button> <?php foreach (['module-settings' => ['settings', '模块设置'], 'properties' => ['edit', '属性'], 'copy' => ['copy', '复制'], 'delete' => ['delete', '删除']] as $action => [$icon, $label]): ?>
<button type="button" data-element-copy>复制</button> <button type="button" data-element-<?= $action ?> aria-label="<?= $label ?>" title="<?= $label ?>"><?= View::fragment('studio-icon', compact('icon')) ?></button>
<button type="button" data-element-delete>删除</button> <?php endforeach ?>
</div> </div>
<button class="studio-media-handle" type="button" role="slider" aria-label="媒体宽度" aria-valuemin="10" aria-valuemax="100" aria-valuenow="100" data-media-handle hidden></button> <button class="studio-media-handle" type="button" role="slider" aria-label="媒体宽度" aria-valuemin="10" aria-valuemax="100" aria-valuenow="100" data-media-handle hidden></button>
<div class="studio-media-sizing" data-media-sizing hidden> <div class="studio-media-sizing" data-media-sizing hidden>
@@ -60,14 +65,17 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
<button class="button button-outline" type="button" data-replace-media>替换媒体</button> <button class="button button-outline" type="button" data-replace-media>替换媒体</button>
</div> </div>
</div> </div>
<p class="field-note">单击画布元素可设置对齐、复制或删除。选中媒体后可拖动边缘手柄调整宽度。</p> <p class="field-note studio-canvas-status" data-canvas-status role="status"></p>
<dialog class="media-picker canvas-properties" data-canvas-properties aria-labelledby="canvas-properties-heading"> <dialog class="media-picker canvas-properties" data-canvas-properties aria-labelledby="canvas-properties-heading">
<div class="admin-heading compact"><h2 id="canvas-properties-heading" data-property-heading>编辑属性</h2></div> <div class="admin-heading compact"><h2 id="canvas-properties-heading" data-property-heading>编辑属性</h2></div>
<form class="admin-form" method="dialog"> <form class="admin-form" method="dialog">
<label data-property-row="label">文案<input name="label"></label> <label data-property-row="label">文案<input name="label"></label>
<label data-property-row="note">副标题<input name="note" maxlength="200"></label>
<label data-property-row="url">地址<input name="url" maxlength="1000"></label> <label data-property-row="url">地址<input name="url" maxlength="1000"></label>
<label data-property-row="alt">图片替代文本<input name="alt" maxlength="200"></label> <label data-property-row="alt">图片替代文本<input name="alt" maxlength="200"></label>
<label data-property-row="quicklinks">目录链接<textarea name="quicklinks" rows="5" placeholder="概览 | #overview"></textarea><small>每行填写「文案 | 链接」。</small></label> <label data-property-row="quicklinks">目录链接<textarea name="quicklinks" rows="5" placeholder="概览 | #overview"></textarea><small>每行填写「文案 | 链接」。</small></label>
<label data-property-row="value">当前值<input name="value" inputmode="numeric"></label>
<label data-property-row="max">最大值<input name="max" inputmode="numeric"></label>
<label data-property-row="poster">视频封面<input name="poster" maxlength="1000"></label> <label data-property-row="poster">视频封面<input name="poster" maxlength="1000"></label>
<p class="feedback error" role="alert" data-property-error hidden></p> <p class="feedback error" role="alert" data-property-error hidden></p>
<div class="actions"> <div class="actions">
@@ -80,6 +88,19 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
</div> </div>
</form> </form>
</dialog> </dialog>
<dialog class="media-picker canvas-module-settings" data-module-dialog aria-labelledby="module-settings-title">
<div class="admin-heading compact"><h2 id="module-settings-title">模块设置</h2></div>
<form class="admin-form" method="dialog">
<label>模块标题<input name="module_title" maxlength="100" required></label>
<label>模块简介<textarea name="module_lead" rows="2" maxlength="500"></textarea></label>
<?= View::fragment('studio-feed-fields', ['categories' => $categories, 'feed' => [], 'allowOff' => false]) ?>
<p class="feedback error" role="alert" data-module-error hidden></p>
<div class="actions">
<button class="button button-primary" type="submit">应用</button>
<button class="button button-outline" data-module-close type="button">取消</button>
</div>
</form>
</dialog>
</section> </section>
</div> </div>
<form id="studio-page-settings" class="admin-form admin-panel studio-inspector" method="post" action="/admin/pages/<?= $e($slug) ?>"> <form id="studio-page-settings" class="admin-form admin-panel studio-inspector" method="post" action="/admin/pages/<?= $e($slug) ?>">
@@ -88,6 +109,15 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
<input type="hidden" name="version" value="<?= $e($page['version']) ?>"> <input type="hidden" name="version" value="<?= $e($page['version']) ?>">
<input type="hidden" name="canvas_sections" value=""> <input type="hidden" name="canvas_sections" value="">
<input type="hidden" name="alignments" value="<?= $e(Database::json($page['alignments'])) ?>"> <input type="hidden" name="alignments" value="<?= $e(Database::json($page['alignments'])) ?>">
<details class="studio-hero-settings">
<summary>首屏与目录</summary>
<div class="studio-hero-controls">
<button class="button button-outline" type="button" disabled data-hero-control="image">首屏图片</button>
<button class="button button-outline" type="button" disabled data-hero-control="1">首屏按钮 1</button>
<button class="button button-outline" type="button" disabled data-hero-control="2">首屏按钮 2</button>
<button class="button button-outline" type="button" disabled data-hero-control="navigation">本页目录</button>
</div>
</details>
<label>页面名称<input name="name" value="<?= $e($page['name']) ?>" required maxlength="100"></label> <label>页面名称<input name="name" value="<?= $e($page['name']) ?>" required maxlength="100"></label>
<label>SEO 标题<input name="title" value="<?= $e($page['title']) ?>" required maxlength="160"></label> <label>SEO 标题<input name="title" value="<?= $e($page['title']) ?>" required maxlength="160"></label>
<label>SEO 描述<textarea name="description" rows="2" maxlength="300"><?= $e($page['description']) ?></textarea></label> <label>SEO 描述<textarea name="description" rows="2" maxlength="300"><?= $e($page['description']) ?></textarea></label>
+11 -17
View File
@@ -17,23 +17,17 @@ $feed = json_decode($section['feed'] ?? '{}', true, flags: JSON_THROW_ON_ERROR);
<input type="hidden" name="version" value="<?= $e($section['version']) ?>"> <input type="hidden" name="version" value="<?= $e($section['version']) ?>">
<label>区块标题<input name="title" value="<?= $e($section['title']) ?>" required maxlength="100"></label> <label>区块标题<input name="title" value="<?= $e($section['title']) ?>" required maxlength="100"></label>
<label>区块简介<textarea name="lead" rows="2" maxlength="500"><?= $e($section['lead']) ?></textarea></label> <label>区块简介<textarea name="lead" rows="2" maxlength="500"><?= $e($section['lead']) ?></textarea></label>
<label>区块背景<select name="style"> <?php if ($savedStyle !== 'hero-links'): ?>
<?php foreach (array_unique([$savedStyle, 'plain', 'tinted']) as $style): ?> <label>区块背景<select name="style">
<option value="<?= $e($style) ?>" <?= $style === $section['style'] ? 'selected' : '' ?>><?= $e(['plain' => '默认', 'tinted' => '浅色背景'][$style] ?? '保留原布局') ?></option> <?php foreach (array_unique([$savedStyle, 'plain', 'tinted']) as $style): ?>
<?php endforeach ?> <option value="<?= $e($style) ?>" <?= $style === $section['style'] ? 'selected' : '' ?>><?= $e(['plain' => '默认', 'tinted' => '浅色背景'][$style] ?? '保留原布局') ?></option>
</select></label> <?php endforeach ?>
<details class="admin-options" <?= $feed ? 'open' : '' ?>> </select></label>
<summary>文章组件</summary> <details class="admin-options" <?= $feed ? 'open' : '' ?>>
<div class="form-grid"> <summary>动态模块</summary>
<label>展示方式<select name="feed_mode"> <?= View::fragment('studio-feed-fields', ['categories' => $categories, 'feed' => $feed, 'allowOff' => true]) ?>
<?php foreach (['off' => '不展示', 'merged' => '合并为一个列表', 'tabs' => '按分类分标签页'] as $mode => $label): ?> </details>
<option value="<?= $mode ?>" <?= ($feed['mode'] ?? 'off') === $mode ? 'selected' : '' ?>><?= $e($label) ?></option> <?php endif ?>
<?php endforeach ?>
</select></label>
<label>展示数量<input name="feed_limit" type="number" min="1" max="30" value="<?= $e($feed['limit'] ?? 6) ?>"><small>分标签页时,每个分类独立计数。</small></label>
</div>
<?= View::fragment('admin-category-checkboxes', ['name' => 'feed_categories', 'selected' => $feed['categories'] ?? [], 'categories' => $categories, 'legend' => '展示哪些分类(可多选)']) ?>
</details>
<?= View::fragment('admin-editor', ['format' => 'html', 'body' => $section['body']]) ?> <?= View::fragment('admin-editor', ['format' => 'html', 'body' => $section['body']]) ?>
<div class="form-submit"><button class="button button-primary" type="submit">保存区块</button></div> <div class="form-submit"><button class="button button-primary" type="submit">保存区块</button></div>
</form> </form>
+1 -21
View File
@@ -1,6 +1,4 @@
<?php <?php
use App\Content\DirectoryCard;
use App\Content\Html;
use App\Content\View; use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
@@ -17,25 +15,7 @@ $e = View::escape(...);
<div class="network-group" id="<?= $e($slug) ?>"> <div class="network-group" id="<?= $e($slug) ?>">
<?php if ($standalone): ?><h2><?= $e($group['name']) ?></h2><?php else: ?><h3><?= $e($group['name']) ?></h3><?php endif ?> <?php if ($standalone): ?><h2><?= $e($group['name']) ?></h2><?php else: ?><h3><?= $e($group['name']) ?></h3><?php endif ?>
<?php if (!$group['articles']): ?><p class="empty-state">暂无已发布条目。</p><?php endif ?> <?php if (!$group['articles']): ?><p class="empty-state">暂无已发布条目。</p><?php endif ?>
<ul class="network-list"> <?= View::fragment('network-items', ['articles' => $group['articles'], 'standalone' => $standalone]) ?>
<?php foreach ($group['articles'] as $item): ?>
<?php
$card = $item['card'];
['primary' => $target, 'detail' => $detail] = DirectoryCard::links($item, Html::articleBody($item));
?>
<li>
<?php if ($target !== ''): ?><a href="<?= $e($target) ?>"><?php else: ?><span class="network-static"><?php endif ?>
<?php if (!empty($card['image'])): ?>
<img src="<?= $e($card['image']) ?>" alt="" loading="lazy" width="76" height="28">
<?php endif ?>
<span><?= $e($item['title']) ?></span>
<?php if ($target !== ''): ?></a><?php else: ?></span><?php endif ?>
<?php if ($standalone && $detail !== ''): ?>
<a class="network-detail" href="<?= $e($detail) ?>">查看详情</a>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
</div> </div>
<?php endforeach ?> <?php endforeach ?>
</div> </div>
+27
View File
@@ -0,0 +1,27 @@
<?php
use App\Content\DirectoryCard;
use App\Content\Html;
use App\Content\View;
$e = View::escape(...);
?>
<ul class="network-list">
<?php foreach ($articles as $item): ?>
<?php
$card = $item['card'];
['primary' => $target, 'detail' => $detail] = DirectoryCard::links($item, Html::articleBody($item));
?>
<li>
<?php if ($target !== ''): ?><a href="<?= $e($target) ?>"><?php else: ?><span class="network-static"><?php endif ?>
<?php if (!empty($card['image'])): ?>
<img src="<?= $e($card['image']) ?>" alt="" loading="lazy" width="76" height="28">
<?php endif ?>
<span><?= $e($item['title']) ?></span>
<?php if ($target !== ''): ?></a><?php else: ?></span><?php endif ?>
<?php if ($standalone && $detail !== ''): ?>
<a class="network-detail" href="<?= $e($detail) ?>">查看详情</a>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
+8 -13
View File
@@ -55,15 +55,11 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' .
</div> </div>
<?php endif ?> <?php endif ?>
</div> </div>
<?php if ($home): ?> <?php foreach ($page['sections'] as $section): ?>
<div class="wrap hero-directory"> <?php if ($section['style'] === 'hero-links'): ?>
<a class="overline directory-label" href="/services">产品与服务</a> <?= View::fragment('section', ['section' => $section, 'moment' => false, 'canvas' => $canvas, 'pageSlug' => $page['slug']]) ?>
<a href="/pagepan"><span>PAGEPAN</span><small>可视化建站</small></a> <?php endif ?>
<a href="/highspeaker"><span>HighSpeaker DNS</span><small>开源智能解析</small></a> <?php endforeach ?>
<a href="/sc"><span>软著代理</span><small>登记申请与材料服务</small></a>
<a href="/shnu-sc"><span>SHNU 学生</span><small>软著申请方案</small></a>
</div>
<?php endif ?>
</section> </section>
<?php if ($canvas || $page['quicklinks']): ?> <?php if ($canvas || $page['quicklinks']): ?>
<nav class="section-nav" aria-label="本页目录"<?= $canvas ? ' data-studio-navigation' : '' ?><?= !$page['quicklinks'] ? ' hidden' : '' ?>> <nav class="section-nav" aria-label="本页目录"<?= $canvas ? ' data-studio-navigation' : '' ?><?= !$page['quicklinks'] ? ' hidden' : '' ?>>
@@ -75,7 +71,9 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' .
</nav> </nav>
<?php endif ?> <?php endif ?>
<?php foreach ($page['sections'] as $section): ?> <?php foreach ($page['sections'] as $section): ?>
<?= View::fragment('section', ['section' => $section, 'moment' => $home && $section['key'] === 'about', 'canvas' => $canvas]) ?> <?php if ($section['style'] !== 'hero-links'): ?>
<?= View::fragment('section', ['section' => $section, 'moment' => $home && $section['key'] === 'about', 'canvas' => $canvas, 'pageSlug' => $page['slug']]) ?>
<?php endif ?>
<?php endforeach ?> <?php endforeach ?>
<?php if ($canvas): ?> <?php if ($canvas): ?>
<template data-studio-section-end><?= View::fragment('section', [ <template data-studio-section-end><?= View::fragment('section', [
@@ -83,6 +81,3 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' .
'moment' => false, 'canvas' => true, 'moment' => false, 'canvas' => true,
]) ?></template> ]) ?></template>
<?php endif ?> <?php endif ?>
<?php if ($home): ?>
<?= View::fragment('network-groups', ['network' => $network, 'standalone' => false]) ?>
<?php endif ?>
+29 -4
View File
@@ -4,20 +4,45 @@ use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
$canvas ??= false; $canvas ??= false;
$body = $section['body']; $body = $section['body'];
$dynamic = isset($section['feed']);
$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 ?>>
<?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>
<?php
return;
endif;
$alignments = json_decode($section['alignments'] ?? '{}', true, flags: JSON_THROW_ON_ERROR); $alignments = json_decode($section['alignments'] ?? '{}', true, flags: JSON_THROW_ON_ERROR);
if (isset($section['articleFeed']) && $body === '<p><a class="back-link" href="/articles">查看全部动态</a></p>') { if ($dynamic && $body === '<p><a class="back-link" href="/articles">查看全部动态</a></p>') {
$body = ''; $body = '';
} }
$network = $section['networkFeed'] ?? false;
?> ?>
<section class="section section-<?= $e($section['style']) ?>" id="<?= $e($section['key']) ?>" aria-labelledby="heading-<?= $e($section['key']) ?>" <?= $moment ? 'data-moment="iris-opens"' : '' ?><?= $canvas ? ' data-studio-section="' . $e($section['version']) . '" data-studio-source="' . $e(base64_encode($section['body'])) . '"' : '' ?>> <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 ?>>
<div class="wrap"> <div class="wrap">
<div class="section-heading"> <div class="section-heading">
<h2 id="heading-<?= $e($section['key']) ?>"<?= isset($alignments['title']) ? ' class="' . trim(View::alignmentClass($alignments['title'])) . '"' : '' ?><?= $canvas ? ' data-studio-part="title"' : '' ?>><?= $e($section['title']) ?></h2> <h2 id="heading-<?= $e($section['key']) ?>"<?= 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 ?> <?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 ?>
</div> </div>
<?php if (!empty($section['articleFeed'])): ?> <?php if ($network): ?>
<?php foreach ($section['articleFeed'] as $group): ?>
<?php $slug = $group['categories'][0]; $anchor = ($pageSlug ?? '') === 'home' && $section['key'] === 'network' ? $slug : $section['key'] . '-group-' . $slug; ?>
<div class="network-group" id="<?= $e($anchor) ?>">
<h3><?= $e($group['label']) ?></h3>
<?= View::fragment('network-items', ['articles' => $group['articles'], 'standalone' => false]) ?>
</div>
<?php endforeach ?>
<?php if ($section['archivePath'] !== null): ?><p class="article-feed-archive"><a class="back-link" href="<?= $e($section['archivePath']) ?>">查看全部</a></p><?php endif ?>
<?php elseif (!empty($section['articleFeed'])): ?>
<?= View::fragment('article-feed', ['groups' => $section['articleFeed'], 'sectionKey' => $section['key'], 'archivePath' => $section['archivePath']]) ?> <?= View::fragment('article-feed', ['groups' => $section['articleFeed'], 'sectionKey' => $section['key'], 'archivePath' => $section['archivePath']]) ?>
<?php endif ?> <?php endif ?>
<?php if ($canvas || $body !== ''): ?><div class="rich<?= !empty($section['articleFeed']) ? ' article-feed-note' : '' ?>"<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $body ?></div><?php endif ?> <?php if ($canvas || $body !== ''): ?><div class="rich<?= $dynamic ? ' article-feed-note' : '' ?>"<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $body ?></div><?php endif ?>
</div> </div>
</section> </section>
+24
View File
@@ -0,0 +1,24 @@
<?php
use App\Content\BlockTemplates;
use App\Content\View;
$e = View::escape(...);
?>
<details class="studio-anchor-create">
<summary>按锚点新建区块</summary>
<form class="admin-form" method="post" action="/admin/page-blocks/<?= $e($slug) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="operation" value="create">
<label>锚点<input name="key" pattern="[a-z0-9]+(-[a-z0-9]+)*" maxlength="70" placeholder="overview" required></label>
<label>模板<select name="preset">
<?php foreach (BlockTemplates::groups() as [$category, $templates]): ?>
<optgroup label="<?= $e($category) ?>">
<?php foreach ($templates as $preset => [$label]): ?>
<option value="<?= $e($preset) ?>"><?= $e($label) ?></option>
<?php endforeach ?>
</optgroup>
<?php endforeach ?>
</select></label>
<button type="submit" class="button button-outline">新建</button>
</form>
</details>
+15
View File
@@ -0,0 +1,15 @@
<?php
use App\Content\View;
$e = View::escape(...);
$modes = ($allowOff ? ['off' => '不展示'] : []) + ['merged' => '合并列表', 'tabs' => '分类标签页', 'network' => '项目与伙伴卡片'];
?>
<div class="form-grid">
<label>展示方式<select name="feed_mode">
<?php foreach ($modes as $mode => $label): ?>
<option value="<?= $mode ?>" <?= ($feed['mode'] ?? 'off') === $mode ? 'selected' : '' ?>><?= $e($label) ?></option>
<?php endforeach ?>
</select></label>
<label>展示数量<input name="feed_limit" type="number" required min="1" max="30" value="<?= $e($feed['limit'] ?? 6) ?>"><small>分组时每个分类独立计数。</small></label>
</div>
<?= View::fragment('admin-category-checkboxes', ['name' => 'feed_categories', 'selected' => $feed['categories'] ?? [], 'categories' => $categories, 'legend' => '展示分类']) ?>
+12
View File
@@ -0,0 +1,12 @@
<?php
$paths = [
'left' => '<path d="M3 6h18M3 10h12M3 14h18M3 18h12"/>',
'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"/>',
'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"/>',
];
?>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><?= $paths[$icon] ?></svg>
+3 -28
View File
@@ -1,39 +1,14 @@
<?php <?php
use App\Content\BlockTemplates;
use App\Content\View; use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
?> ?>
<details class="studio-layers">
<summary>首屏与目录</summary>
<button type="button" disabled data-hero-control="image">首屏图片</button>
<button type="button" disabled data-hero-control="1">首屏按钮 1</button>
<button type="button" disabled data-hero-control="2">首屏按钮 2</button>
<button type="button" disabled data-hero-control="navigation">本页目录</button>
</details>
<details class="studio-layers">
<summary>按锚点新建区块</summary>
<form class="admin-form" method="post" action="/admin/page-blocks/<?= $e($slug) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="operation" value="create">
<label>锚点<input name="key" pattern="[a-z0-9]+(-[a-z0-9]+)*" maxlength="70" placeholder="overview" required></label>
<label>模板<select name="preset">
<?php foreach (BlockTemplates::GROUPS as [$category, $templates]): ?>
<optgroup label="<?= $e($category) ?>">
<?php foreach ($templates as $preset => [$label]): ?>
<option value="<?= $e($preset) ?>"><?= $e($label) ?></option>
<?php endforeach ?>
</optgroup>
<?php endforeach ?>
</select></label>
<button type="submit" class="button button-outline">新建</button>
</form>
</details>
<details class="studio-layers" id="blocks"> <details class="studio-layers" id="blocks">
<summary>区块顺序</summary> <summary>区块顺序</summary>
<ul class="admin-list studio-blocks"> <ul class="admin-list studio-blocks">
<?php foreach ($page['sections'] as $index => $item): ?> <?php foreach ($page['sections'] as $index => $item): ?>
<?php $fixedSlot = $item['style'] === 'hero-links'; ?>
<li> <li>
<div><strong><?= $e($item['title']) ?></strong><small>#<?= $e($item['key']) ?></small></div> <div><strong><?= $e($item['title']) ?></strong><small>#<?= $e($item['key']) ?></small></div>
<div class="actions studio-block-actions"> <div class="actions studio-block-actions">
@@ -44,8 +19,8 @@ $e = View::escape(...);
<input type="hidden" name="key" value="<?= $e($item['key']) ?>"> <input type="hidden" name="key" value="<?= $e($item['key']) ?>">
<input type="hidden" name="page_version" value="<?= $e($page['version']) ?>"> <input type="hidden" name="page_version" value="<?= $e($page['version']) ?>">
<input type="hidden" name="version" value="<?= $e($item['version']) ?>"> <input type="hidden" name="version" value="<?= $e($item['version']) ?>">
<button class="button button-outline" name="operation" value="up" type="submit" <?= $index === 0 ? 'disabled' : '' ?>>上移</button> <button class="button button-outline" name="operation" value="up" type="submit" <?= $fixedSlot || $index === 0 || $page['sections'][$index - 1]['style'] === 'hero-links' ? 'disabled' : '' ?>>上移</button>
<button class="button button-outline" name="operation" value="down" type="submit" <?= $index === count($page['sections']) - 1 ? 'disabled' : '' ?>>下移</button> <button class="button button-outline" name="operation" value="down" type="submit" <?= $fixedSlot || $index === count($page['sections']) - 1 ? 'disabled' : '' ?>>下移</button>
<button class="button button-outline" name="operation" value="delete" type="submit" data-confirm="删除这个区块?">删除</button> <button class="button button-outline" name="operation" value="delete" type="submit" data-confirm="删除这个区块?">删除</button>
</form> </form>
</div> </div>
+5 -3
View File
@@ -13,6 +13,7 @@ $modules = $kind === 'modules';
</button></li> </button></li>
<?php endforeach ?> <?php endforeach ?>
</ul> </ul>
<?php if ($modules): ?><?= $anchorForm ?><?php endif ?>
<div class="studio-library-content" data-library-content hidden> <div class="studio-library-content" data-library-content hidden>
<div class="studio-library-category-title"> <div class="studio-library-category-title">
<button type="button" data-library-back>返回分类</button> <button type="button" data-library-back>返回分类</button>
@@ -26,7 +27,7 @@ $modules = $kind === 'modules';
<?php foreach ($groups as $group => [$category, $items]): ?> <?php foreach ($groups as $group => [$category, $items]): ?>
<div class="<?= $modules ? 'studio-template-cards' : 'studio-element-items' ?>" data-template-group="<?= $e($group) ?>" hidden> <div class="<?= $modules ? 'studio-template-cards' : 'studio-element-items' ?>" data-template-group="<?= $e($group) ?>" hidden>
<?php foreach ($items as $key => $item): ?> <?php foreach ($items as $key => $item): ?>
<?php [$label, $markup, $mime] = array_pad($item, 3, ''); ?> <?php [$label, $markup, $option, $feed] = array_pad($item, 4, null); ?>
<?php if ($modules): ?> <?php if ($modules): ?>
<article class="studio-template-card" data-template-card data-library-item data-template-search-text="<?= $e($label . ' ' . $key) ?>"> <article class="studio-template-card" data-template-card data-library-item data-template-search-text="<?= $e($label . ' ' . $key) ?>">
<button type="button" class="studio-template-image" data-template-preview="<?= $e($key) ?>" data-template-title="<?= $e($label) ?>" <button type="button" class="studio-template-image" data-template-preview="<?= $e($key) ?>" data-template-title="<?= $e($label) ?>"
@@ -36,14 +37,15 @@ $modules = $kind === 'modules';
<div class="studio-template-meta"> <div class="studio-template-meta">
<span><?= $e($label) ?></span> <span><?= $e($label) ?></span>
<button type="button" class="button button-outline" disabled data-canvas-template="<?= $e($key) ?>" <button type="button" class="button button-outline" disabled data-canvas-template="<?= $e($key) ?>"
data-template-title="<?= $e($label) ?>" aria-label="添加<?= $e($label) ?>组件">添加</button> data-template-title="<?= $e($label) ?>" data-template-lead="<?= $e($option) ?>" data-template-style="<?= $e($item[4] ?? 'plain') ?>"
<?= $feed !== null ? 'data-template-feed="' . $e($feed) . '"' : '' ?> aria-label="添加<?= $e($label) ?>组件">添加</button>
</div> </div>
<template data-preset="<?= $e($key) ?>"><?= $markup ?></template> <template data-preset="<?= $e($key) ?>"><?= $markup ?></template>
</article> </article>
<?php else: ?> <?php else: ?>
<div data-library-item data-template-search-text="<?= $e($label . ' ' . $key) ?>"> <div data-library-item data-template-search-text="<?= $e($label . ' ' . $key) ?>">
<button type="button" disabled data-canvas-element="<?= $e($key) ?>" <button type="button" disabled data-canvas-element="<?= $e($key) ?>"
<?php if ($mime): ?>data-element-mime="<?= $e($mime) ?>"<?php endif ?> <?php if ($option): ?>data-element-mime="<?= $e($option) ?>"<?php endif ?>
aria-label="插入<?= $e($label) ?>"><?= $e($label) ?></button> aria-label="插入<?= $e($label) ?>"><?= $e($label) ?></button>
<template data-element="<?= $e($key) ?>"><?= $markup ?></template> <template data-element="<?= $e($key) ?>"><?= $markup ?></template>
</div> </div>
+2 -2
View File
@@ -13,8 +13,8 @@ $labels = ['modules' => '组件', 'elements' => '元素', 'layers' => '图层'];
aria-selected="false" tabindex="-1" data-library-tab="<?= $kind ?>"><?= $e($label) ?></button> aria-selected="false" tabindex="-1" data-library-tab="<?= $kind ?>"><?= $e($label) ?></button>
<?php endforeach ?> <?php endforeach ?>
</div> </div>
<?php foreach (['modules' => BlockTemplates::GROUPS, 'elements' => BlockTemplates::ELEMENT_GROUPS] as $kind => $groups): ?> <?php foreach (['modules' => BlockTemplates::groups(), 'elements' => BlockTemplates::ELEMENT_GROUPS] as $kind => $groups): ?>
<?= View::fragment('studio-library-panel', compact('kind', 'groups')) ?> <?= View::fragment('studio-library-panel', compact('kind', 'groups', 'anchorForm')) ?>
<?php endforeach ?> <?php endforeach ?>
<section role="tabpanel" id="studio-panel-layers" aria-labelledby="studio-tab-layers" data-library-panel="layers"> <section role="tabpanel" id="studio-panel-layers" aria-labelledby="studio-tab-layers" data-library-panel="layers">
<?= $layers ?> <?= $layers ?>
+28 -10
View File
@@ -132,16 +132,19 @@
.studio-layers .studio-block-actions .button { min-height: 2.25rem; padding: .25rem .5rem; font-size: .8rem; } .studio-layers .studio-block-actions .button { min-height: 2.25rem; padding: .25rem .5rem; font-size: .8rem; }
.studio-media-sizing { position: absolute; z-index: 1; inset: auto .6rem .6rem auto; display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; padding: .45rem .6rem; max-width: calc(100% - 1.2rem); background: var(--accent-light); border: 1px solid var(--line); border-radius: .45rem; } .studio-media-sizing { position: absolute; z-index: 1; inset: auto .6rem .6rem auto; display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; padding: .45rem .6rem; max-width: calc(100% - 1.2rem); background: var(--accent-light); border: 1px solid var(--line); border-radius: .45rem; }
.studio-element-tools { .studio-element-tools {
position: absolute; z-index: 3; display: flex; align-items: center; gap: .15rem; padding: .2rem; position: absolute; z-index: 3; display: flex; align-items: center; gap: .12rem; padding: .18rem;
border: 1px solid #3f62e0; border-radius: .65rem; background: #244bc8; border: 1px solid #c7d6f3; border-radius: .52rem; background: var(--white);
box-shadow: 0 .22rem .7rem #13297538; box-shadow: 0 .22rem .85rem #16305230;
} }
.studio-element-tools button { .studio-element-tools button {
min-height: 2rem; padding: .22rem .6rem; border: 0; border-radius: .42rem; display: grid; place-items: center; width: 2rem; height: 2rem; padding: 0;
background: transparent; color: white; font-size: .84rem; white-space: nowrap; cursor: pointer; border: 0; border-radius: .32rem; background: transparent; color: #35496d; cursor: pointer;
} }
.studio-element-tools button:hover, .studio-element-tools button:focus-visible { background: #ffffff32; } .studio-element-tools button svg { width: 1rem; height: 1rem; pointer-events: none; }
.studio-element-tools button:focus-visible { outline: 1px solid white; outline-offset: -2px; } .studio-element-tools button:hover, .studio-element-tools button:focus-visible { background: var(--accent-light); color: var(--accent-deep); }
.studio-element-tools button:focus-visible { outline: 1px solid var(--accent); outline-offset: -2px; }
.studio-element-tools button[data-element-delete]:hover { color: #a12727; background: #fceeee; }
.studio-element-tools.is-module [data-element-module-settings] { background: var(--accent-light); color: var(--accent-deep); }
.studio-media-handle { .studio-media-handle {
position: absolute; z-index: 2; width: 1.4rem; height: 2.8rem; translate: -50% -50%; position: absolute; z-index: 2; width: 1.4rem; height: 2.8rem; translate: -50% -50%;
display: grid; place-content: center; border: 2px solid white; border-radius: .42rem; display: grid; place-content: center; border: 2px solid white; border-radius: .42rem;
@@ -245,9 +248,8 @@
.article-editor-heading > .button { min-height: 2.1rem; padding: .25rem .6rem; } .article-editor-heading > .button { min-height: 2.1rem; padding: .25rem .6rem; }
.article-editor-help:empty { display: none; } .article-editor-help:empty { display: none; }
.studio-element-align { display: flex; gap: .05rem; padding-inline-end: .2rem; border-inline-end: 1px solid #ffffff55; } .studio-element-align { display: flex; gap: .05rem; padding-inline-end: .15rem; border-inline-end: 1px solid var(--line); }
.studio-element-align button { padding-inline: .38rem; } .studio-element-align button[aria-pressed="true"] { background: var(--accent-light); color: var(--accent-deep); }
.studio-element-align button[aria-pressed="true"] { background: white; color: #244bc8; }
.admin-primary a { padding: .28rem .65rem; border-radius: .48rem; color: var(--muted); } .admin-primary a { padding: .28rem .65rem; border-radius: .48rem; color: var(--muted); }
.admin-primary a[aria-current="page"] { background: var(--accent-light); color: var(--accent-deep); } .admin-primary a[aria-current="page"] { background: var(--accent-light); color: var(--accent-deep); }
@@ -293,3 +295,19 @@
.dashboard-page-list li { grid-template-columns: minmax(0, 1fr) auto; } .dashboard-page-list li { grid-template-columns: minmax(0, 1fr) auto; }
.dashboard-page-actions { grid-column: 1 / -1; } .dashboard-page-actions { grid-column: 1 / -1; }
} }
.studio-page-meta { display: flex; flex-wrap: wrap; align-items: center; gap: .65rem; }
.studio-page-meta code { color: var(--muted); font-size: .86rem; }
.studio-anchor-create, .studio-hero-settings { padding: .55rem .65rem; border: 1px solid var(--line); border-radius: .45rem; }
.studio-anchor-create { margin-top: .55rem; font-size: .84rem; }
.studio-anchor-create summary, .studio-hero-settings summary { cursor: pointer; font-weight: 630; }
.studio-anchor-create[open] form, .studio-hero-controls { margin-top: .6rem; }
.studio-hero-controls { display: flex; flex-wrap: wrap; gap: .42rem; }
.studio-hero-controls .button { min-height: 2.35rem; padding: .3rem .62rem; font-size: .85rem; }
.studio-canvas-status:empty { display: none; }
.canvas-module-settings { max-width: min(92vw, 40rem); }
@media (pointer: coarse) {
.studio-element-tools button { width: 2.5rem; height: 2.5rem; }
}
.canvas-module-settings .category-checks { max-height: min(15rem, 27dvh); overflow-y: auto; }
.canvas-module-settings .actions { position: sticky; bottom: 0; padding-block: .35rem; margin: 0; background: var(--white); }
+11
View File
@@ -725,3 +725,14 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
.studio-releases article:last-child { border-block-end: 1px solid var(--line); } .studio-releases article:last-child { border-block-end: 1px solid var(--line); }
.studio-pricing { grid-template-columns: repeat(2, minmax(0, 1fr)); } .studio-pricing { grid-template-columns: repeat(2, minmax(0, 1fr)); }
@media (max-width: 36rem) { .studio-pricing { grid-template-columns: 1fr; } } @media (max-width: 36rem) { .studio-pricing { grid-template-columns: 1fr; } }
.hero-directory-slot > [data-studio-part="body"] { min-height: 2.2rem; }
[data-studio-editing] [data-studio-dynamic] { cursor: pointer; }
[data-studio-editing] [data-studio-dynamic]:focus-visible { outline: 1px solid var(--accent); }
.studio-module-note { margin: 1rem 0 0; color: var(--accent-deep); padding: .6rem .8rem; background: var(--accent-light); border-radius: .4rem; }
.studio-badge { display: inline-flex; padding: .13rem .63rem; border-radius: 999px; background: var(--accent-light); color: var(--accent-deep); font-size: .85rem; }
.studio-progress progress { width: min(100%, 28rem); accent-color: var(--accent); display: block; }
.studio-progress p { margin-bottom: .3rem; }
.studio-empty { text-align: center; border: 1px dashed var(--line); border-radius: .6rem; padding: clamp(1.25rem, 4vw, 2.7rem); }
.studio-success-note { border-inline-start-color: #257b50; background: #e7f6ed; }
.rich .hero-directory { border-bottom: 1px solid var(--line); border-radius: .85rem; }
+216 -44
View File
@@ -240,7 +240,7 @@ jQuery(function ($) {
$gallery.on('click', '[data-library-category]', function () { $gallery.on('click', '[data-library-category]', function () {
const $panel = $(this).closest('[data-library-panel]'); const $panel = $(this).closest('[data-library-panel]');
$panel.data('categoryTrigger', this); $panel.data('categoryTrigger', this);
$panel.find('[data-library-index]').prop('hidden', true); $panel.find('[data-library-index], .studio-anchor-create').prop('hidden', true);
$panel.find('[data-library-content]').prop('hidden', false); $panel.find('[data-library-content]').prop('hidden', false);
$panel.find('[data-library-title]').text(this.dataset.libraryLabel); $panel.find('[data-library-title]').text(this.dataset.libraryLabel);
$panel.find('[data-template-search]').val(''); $panel.find('[data-template-search]').val('');
@@ -253,7 +253,7 @@ jQuery(function ($) {
}).on('click', '[data-library-back]', function () { }).on('click', '[data-library-back]', function () {
const $panel = $(this).closest('[data-library-panel]'); const $panel = $(this).closest('[data-library-panel]');
$panel.find('[data-library-content]').prop('hidden', true); $panel.find('[data-library-content]').prop('hidden', true);
$panel.find('[data-library-index]').prop('hidden', false); $panel.find('[data-library-index], .studio-anchor-create').prop('hidden', false);
hidePeek(); hidePeek();
$($panel.data('categoryTrigger')).trigger('focus'); $($panel.data('categoryTrigger')).trigger('focus');
}).on('input', '[data-template-search]', function () { }).on('input', '[data-template-search]', function () {
@@ -308,7 +308,7 @@ jQuery(function ($) {
const alignmentClasses = alignments.map((value) => 'studio-align-' + value); const alignmentClasses = alignments.map((value) => 'studio-align-' + value);
const heroOrOptional = '[data-studio-field="accent"], [data-studio-field="lead"], [data-studio-part="lead"], [data-studio-action], [data-studio-nav-index]'; const heroOrOptional = '[data-studio-field="accent"], [data-studio-field="lead"], [data-studio-part="lead"], [data-studio-action], [data-studio-nav-index]';
const canvasFields = heroOrOptional + ', [data-studio-field="heading"], [data-studio-part="title"]'; const canvasFields = heroOrOptional + ', [data-studio-field="heading"], [data-studio-part="title"]';
const bodyElements = 'a, article, blockquote, details, div, dl, dt, dd, figure, h1, h2, h3, h4, h5, h6, hr, li, ol, p, pre, table, ul'; 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 mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video'; const mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video';
const $handle = $studio.find('[data-media-handle]'); const $handle = $studio.find('[data-media-handle]');
const $mediaSize = $sizing.find('[data-media-size]'); const $mediaSize = $sizing.find('[data-media-size]');
@@ -355,6 +355,11 @@ jQuery(function ($) {
const $properties = $studio.find('[data-canvas-properties]'); const $properties = $studio.find('[data-canvas-properties]');
const $propertyForm = $properties.find('form'); const $propertyForm = $properties.find('form');
const $propertyError = $properties.find('[data-property-error]'); const $propertyError = $properties.find('[data-property-error]');
const $moduleDialog = $studio.find('[data-module-dialog]');
const $moduleForm = $moduleDialog.find('form');
const moduleInput = (name) => $moduleForm.find('[name="' + name + '"]');
let editedModule;
let deletedModules = [];
const propertyInput = (name) => $propertyForm.find('[name="' + name + '"]'); const propertyInput = (name) => $propertyForm.find('[name="' + name + '"]');
const pageInput = (name) => $settings.find('[name="' + name + '"]'); const pageInput = (name) => $settings.find('[name="' + name + '"]');
const settingsSnapshot = () => $settings.serializeArray() const settingsSnapshot = () => $settings.serializeArray()
@@ -368,7 +373,7 @@ jQuery(function ($) {
let saveComplete = false; let saveComplete = false;
function sectionChanges(withEdits = true) { function sectionChanges(withEdits = true) {
return sections.flatMap(({key, version, fields, source, template}) => { const edits = sections.flatMap(({key, version, fields, source, template, copyOf, feed, initialFeed}) => {
const changes = {}; const changes = {};
const aligned = {}; const aligned = {};
let alignmentChanged = false; let alignmentChanged = false;
@@ -388,9 +393,16 @@ jQuery(function ($) {
changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value; changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value;
} }
} }
if (!Object.keys(changes).length && !alignmentChanged) return []; const feedChanged = feed && (version === null || JSON.stringify(feed) !== initialFeed);
return [{key, version, fields: changes, ...(alignmentChanged ? {alignments: aligned} : {}), ...(template ? {template} : {})}]; if (!Object.keys(changes).length && !alignmentChanged && !feedChanged) 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;
return [edit];
}); });
return [...edits, ...deletedModules];
} }
$settings.on('studio:sync', () => pageInput('canvas_sections').val(JSON.stringify(sectionChanges()))); $settings.on('studio:sync', () => pageInput('canvas_sections').val(JSON.stringify(sectionChanges())));
@@ -409,7 +421,7 @@ jQuery(function ($) {
function openProperties(heading, values, apply, mime = null, allowEmptyUrl = false) { function openProperties(heading, values, apply, mime = null, allowEmptyUrl = false) {
$properties.find('[data-property-heading]').text(heading); $properties.find('[data-property-heading]').text(heading);
$propertyError.prop('hidden', true); $propertyError.prop('hidden', true);
for (const key of ['label', 'url', 'alt', 'poster', 'quicklinks']) { for (const key of ['label', 'note', 'url', 'alt', 'poster', 'quicklinks', 'value', 'max']) {
const visible = Object.hasOwn(values, key); const visible = Object.hasOwn(values, key);
$propertyForm.find('[data-property-row="' + key + '"]').prop('hidden', !visible); $propertyForm.find('[data-property-row="' + key + '"]').prop('hidden', !visible);
propertyInput(key).val(visible ? values[key] : ''); propertyInput(key).val(visible ? values[key] : '');
@@ -621,16 +633,40 @@ jQuery(function ($) {
function editResource(node) { function editResource(node) {
const tag = node.localName; const tag = node.localName;
if (tag === 'progress') {
openProperties('进度条', {value: node.getAttribute('value') || '0', max: node.getAttribute('max') || '100'}, ({value, max}) => {
if (!/^\d+$/.test(value) || !/^\d+$/.test(max) || Number(max) < 1 || Number(value) > Number(max)) {
$propertyError.prop('hidden', false).text('请输入不超过最大值的非负整数。');
return false;
}
node.max = Number(max);
node.value = Number(value);
node.textContent = Math.round(100 * node.value / node.max) + '%';
});
return;
}
if (tag === 'a') { if (tag === 'a') {
const product = node.parentElement.matches('.hero-directory');
const title = product ? node.querySelector(':scope > span') : null;
const note = product ? node.querySelector(':scope > small') : null;
const onlyChild = node.firstElementChild; const onlyChild = node.firstElementChild;
const text = node.childElementCount === 0 ? node : ( const text = title || (node.childElementCount === 0 ? node : (
node.childElementCount === 1 && onlyChild.matches('span, strong, b, em, i, small') node.childElementCount === 1 && onlyChild.matches('span, strong, b, em, i, small')
&& !onlyChild.childElementCount && node.textContent.trim() === onlyChild.textContent.trim() ? onlyChild : null && !onlyChild.childElementCount && node.textContent.trim() === onlyChild.textContent.trim() ? onlyChild : null
); ));
const values = text ? {label: text.textContent, url: node.getAttribute('href') || ''} : {url: node.getAttribute('href') || ''}; const values = text ? {label: text.textContent, url: node.getAttribute('href') || ''} : {url: node.getAttribute('href') || ''};
openProperties('正文链接', values, ({label, url}) => { if (title) values.note = note?.textContent || '';
openProperties(product ? '导航卡片' : '正文链接', values, ({label, note: description, url}) => {
if (text && !label) {
$propertyError.prop('hidden', false).text('请填写链接文案。');
return false;
}
node.setAttribute('href', url); node.setAttribute('href', url);
if (text && label !== values.label) text.textContent = label; if (text && label !== values.label) text.textContent = label;
if (description !== undefined) {
if (note) $(note).text(description);
else if (description) $('<small>').text(description).appendTo(node);
}
}); });
return; return;
} }
@@ -653,17 +689,18 @@ jQuery(function ($) {
}, (tag === 'img' ? 'image' : tag) + '/'); }, (tag === 'img' ? 'image' : tag) + '/');
} }
function registerSection(section, version = Number(section.dataset.studioSection)) { function registerSection(section, version = Number(section.dataset.studioSection), metadata = {}) {
const fields = {}; const fields = {};
const feed = section.dataset.studioFeed ? JSON.parse(section.dataset.studioFeed) : null;
for (const node of section.querySelectorAll('[data-studio-part]')) { for (const node of section.querySelectorAll('[data-studio-part]')) {
const part = node.dataset.studioPart; const part = node.dataset.studioPart;
const body = part === 'body'; const body = part === 'body';
const label = {title: '区块标题', lead: '添加区块简介', body: '区块正文'}[part]; const label = {title: '区块标题', lead: '添加区块简介', body: '区块正文'}[part];
if (body) { if (!feed && body) {
node.contentEditable = 'true'; node.contentEditable = 'true';
node.setAttribute('aria-label', label); node.setAttribute('aria-label', label);
node.dataset.studioPlaceholder = label; node.dataset.studioPlaceholder = label;
} else { } else if (!feed && !node.hidden) {
configureText(node, label, part === 'lead'); configureText(node, label, part === 'lead');
} }
fields[part] = {node, initial: body ? node.innerHTML : node.textContent, initialAlignment: body ? '' : getAlignment(node)}; fields[part] = {node, initial: body ? node.innerHTML : node.textContent, initialAlignment: body ? '' : getAlignment(node)};
@@ -671,7 +708,9 @@ jQuery(function ($) {
const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from( const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from(
atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0) atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0)
)); ));
sections.push({key: section.id, version, fields, source, template: section.dataset.studioTemplate}); const entry = {node: section, key: section.id, version, fields, source, feed, initialFeed: JSON.stringify(feed), ...metadata};
sections.push(entry);
return entry;
} }
function setMediaWidth(node, width) { function setMediaWidth(node, width) {
@@ -779,6 +818,8 @@ jQuery(function ($) {
selectionObserver?.disconnect(); selectionObserver?.disconnect();
selectedElement?.removeAttribute('data-studio-selected'); selectedElement?.removeAttribute('data-studio-selected');
selectedElement = node; selectedElement = node;
const dynamic = node?.hasAttribute('data-studio-dynamic');
$elementTools.toggleClass('is-module', Boolean(dynamic)).find('[data-element-module-settings]').prop('hidden', !dynamic);
selectedMedia = node?.matches(mediaTargets) ? node : null; selectedMedia = node?.matches(mediaTargets) ? node : null;
$sizing.prop('hidden', !selectedMedia); $sizing.prop('hidden', !selectedMedia);
if (node) { if (node) {
@@ -786,12 +827,12 @@ jQuery(function ($) {
const target = sizingTarget(); const target = sizingTarget();
const nav = node.hasAttribute('data-studio-nav-index'); const nav = node.hasAttribute('data-studio-nav-index');
const inBody = node.closest('[data-studio-part="body"]') !== null; const inBody = node.closest('[data-studio-part="body"]') !== null;
const canCopy = inBody || (nav && $(node).siblings().length < 19); const canCopy = dynamic || inBody || (nav && $(node).siblings().length < 19);
const hasProperties = selectedMedia || node.matches('a'); const hasProperties = !dynamic && (selectedMedia || node.matches('a, progress'));
const aligned = alignmentTarget(node); const aligned = dynamic ? null : alignmentTarget(node);
syncAlignmentButtons(aligned); syncAlignmentButtons(aligned);
$elementTools.find('[data-element-copy]').prop('hidden', !canCopy); $elementTools.find('[data-element-copy]').prop('hidden', !canCopy);
$elementTools.find('[data-element-delete]').prop('hidden', !inBody && !selectedMedia && !node.matches(heroOrOptional)); $elementTools.find('[data-element-delete]').prop('hidden', !dynamic && !inBody && !selectedMedia && !node.matches(heroOrOptional));
$elementTools.find('[data-element-properties]').prop('hidden', !hasProperties); $elementTools.find('[data-element-properties]').prop('hidden', !hasProperties);
if (target) showMediaWidth(currentMediaWidth(target)); if (target) showMediaWidth(currentMediaWidth(target));
selectionObserver?.observe(target || aligned || node); selectionObserver?.observe(target || aligned || node);
@@ -802,6 +843,10 @@ jQuery(function ($) {
function changeElement(copy) { function changeElement(copy) {
const node = selectedElement; const node = selectedElement;
if (!node?.isConnected) return; if (!node?.isConnected) return;
if (node.hasAttribute('data-studio-dynamic')) {
changeModule(sections.find((section) => section.node === node), copy);
return;
}
const {studioField, studioAction, studioNavIndex} = node.dataset; const {studioField, studioAction, studioNavIndex} = node.dataset;
const inBody = node.closest('[data-studio-part="body"]') !== null; const inBody = node.closest('[data-studio-part="body"]') !== null;
selectElement(null); selectElement(null);
@@ -853,13 +898,119 @@ jQuery(function ($) {
if (selectedMedia) replaceMedia(); if (selectedMedia) replaceMedia();
else if (selectedElement?.matches('[data-studio-action], [data-studio-nav-index]')) { else if (selectedElement?.matches('[data-studio-action], [data-studio-nav-index]')) {
$(selectedElement).triggerHandler('studio:properties'); $(selectedElement).triggerHandler('studio:properties');
} else if (selectedElement?.matches('a')) { } else if (selectedElement?.matches('a, progress')) {
editResource(selectedElement); editResource(selectedElement);
} }
}).on('keydown', (event) => { }).on('keydown', (event) => {
if (event.key === 'Escape') selectElement(null); if (event.key === 'Escape') selectElement(null);
}); });
function noteModule(section, text) {
const $body = $(section).find('[data-studio-part="body"]');
let $note = $(section).find('[data-studio-module-note]');
if (!$note.length) $note = $('<p>', {class: 'studio-module-note', 'data-studio-module-note': ''}).insertBefore($body);
$note.text(text);
}
$elementTools.on('click', '[data-element-module-settings]', () => {
editedModule = sections.find(({node}) => node === selectedElement);
if (!editedModule?.feed) return;
const {fields, feed} = editedModule;
moduleInput('module_title').val(fields.title.node.textContent);
moduleInput('module_lead').val(fields.lead.node.textContent);
moduleInput('feed_mode').val(feed.mode);
moduleInput('feed_limit').val(feed.limit);
moduleInput('feed_categories[]').each(function () {
this.checked = feed.categories.includes(this.value);
});
$moduleDialog.find('[data-module-error]').prop('hidden', true);
$moduleDialog.get(0).showModal();
});
$moduleDialog.on('click', '[data-module-close]', () => $moduleDialog.get(0).close());
$moduleForm.on('submit', (event) => {
event.preventDefault();
const categories = moduleInput('feed_categories[]').filter(':checked').map((_, node) => node.value).get();
const title = moduleInput('module_title').val().trim();
if (!title || !categories.length) {
$moduleDialog.find('[data-module-error]').text('请填写标题并至少选择一个分类。').prop('hidden', false);
return;
}
const {node, fields} = editedModule;
editedModule.feed = {mode: moduleInput('feed_mode').val(), categories, limit: Number(moduleInput('feed_limit').val())};
fields.title.node.textContent = title;
fields.lead.node.textContent = moduleInput('module_lead').val().trim();
noteModule(node, '模块设置将在保存页面后更新。');
$moduleDialog.get(0).close();
positionSelection();
});
function newSectionId() {
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 removeSection(section) {
if (section.node.contains(activeBody)) selectBody(null);
if (section.node.contains(selectedElement)) selectElement(null);
if (section.version !== null) deletedModules.push({key: section.key, version: section.version, delete: true});
section.node.remove();
sections = sections.filter((entry) => entry !== section);
section.$pending?.remove();
$pending.prop('hidden', !$pending.children().length);
}
function scopeTemplateIds(root, prefix, oldKey = '') {
const ids = new Map();
$(root).find('[id]').addBack('[id]').each(function () {
const next = oldKey && this.id.includes(oldKey) ? this.id.replace(oldKey, prefix) : prefix + '-' + this.id;
ids.set(this.id, next);
this.id = next;
});
$(root).find('[aria-labelledby], [aria-controls], [href^="#"]').addBack('[aria-labelledby]').each(function () {
for (const attribute of ['aria-labelledby', 'aria-controls', 'href']) {
const value = this.getAttribute(attribute);
if (!value) continue;
if (attribute === 'href') {
const target = ids.get(value.slice(1));
if (value.startsWith('#') && target) this.setAttribute('href', '#' + target);
} else {
this.setAttribute(attribute, value.split(' ').map((part) => ids.get(part) || part).join(' '));
}
}
});
}
function changeModule(section, copy) {
if (!section) return;
if (!copy) {
if (window.confirm('删除此模块?保存页面后生效。')) {
removeSection(section);
$studio.find('[data-canvas-status]').text('模块已移除,保存页面后生效。');
}
return;
}
if (sections.filter(({version}) => version === null).length >= 50) return;
selectElement(null);
const clone = section.node.cloneNode(true);
const id = newSectionId();
scopeTemplateIds(clone, id, section.key);
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);
noteModule(clone, '模块副本将在保存页面后生效。');
clone.scrollIntoView({block: 'start'});
selectElement(clone);
$studio.find('[data-canvas-status]').text('已复制模块,保存页面后生效。');
}
function replaceMedia() { function replaceMedia() {
if (!selectedMedia?.isConnected) return; if (!selectedMedia?.isConnected) return;
if (selectedMedia.hasAttribute('data-studio-hero-image')) heroControls.get('image')(); if (selectedMedia.hasAttribute('data-studio-hero-image')) heroControls.get('image')();
@@ -939,7 +1090,10 @@ jQuery(function ($) {
while (node.parentNode !== body) node = node.parentNode; while (node.parentNode !== body) node = node.parentNode;
insertion.setStartAfter(node); insertion.setStartAfter(node);
} }
editBody(body, insertion, 'insertHTML', markup); const template = doc.createElement('template');
template.innerHTML = markup;
if (template.content.querySelector('[id]')) scopeTemplateIds(template.content, newSectionId());
editBody(body, insertion, 'insertHTML', template.innerHTML);
} }
$presets.on('mousedown', '[data-canvas-template], [data-canvas-element]', (event) => event.preventDefault()); $presets.on('mousedown', '[data-canvas-template], [data-canvas-element]', (event) => event.preventDefault());
@@ -966,9 +1120,10 @@ jQuery(function ($) {
$presets.on('click', '[data-canvas-template]', function () { $presets.on('click', '[data-canvas-template]', function () {
const markup = $presets.find('template[data-preset="' + this.dataset.canvasTemplate + '"]').get(0).innerHTML; const markup = $presets.find('template[data-preset="' + this.dataset.canvasTemplate + '"]').get(0).innerHTML;
const template = this.dataset.canvasTemplate; const template = this.dataset.canvasTemplate;
const feed = this.dataset.templateFeed;
if ($presets.find('[data-template-inline]').prop('checked')) { if ($presets.find('[data-template-inline]').prop('checked')) {
if (template === 'articles') { if (feed) {
$templateStatus.text('分类文章需要作为独立区块添加。'); $templateStatus.text('动态模块需要作为独立区块添加。');
return; return;
} }
if (!activeBody) { if (!activeBody) {
@@ -986,34 +1141,29 @@ jQuery(function ($) {
} }
const end = doc.querySelector('[data-studio-section-end]'); const end = doc.querySelector('[data-studio-section-end]');
const section = end.content.firstElementChild.cloneNode(true); const section = end.content.firstElementChild.cloneNode(true);
const id = 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join(''); const id = newSectionId();
section.id = id; section.id = id;
section.classList.replace('section-plain', 'section-' + this.dataset.templateStyle);
const title = section.querySelector('[data-studio-part="title"]'); const title = section.querySelector('[data-studio-part="title"]');
title.id = 'heading-' + id; title.id = 'heading-' + id;
title.textContent = this.dataset.templateTitle; title.textContent = this.dataset.templateTitle;
section.setAttribute('aria-labelledby', title.id); section.setAttribute('aria-labelledby', title.id);
section.querySelector('[data-studio-part="body"]').innerHTML = markup; section.querySelector('[data-studio-part="lead"]').textContent = this.dataset.templateLead || '';
if (template === 'articles') { const body = section.querySelector('[data-studio-part="body"]');
section.dataset.studioTemplate = template; body.innerHTML = markup;
$('<p>', {class: 'empty-state', text: '保存页面后可在图层的区块设置中选择分类和展示方式。'}) scopeTemplateIds(body, id);
.insertBefore($(section).find('[data-studio-part="body"]')); if (feed) {
section.dataset.studioDynamic = '';
section.dataset.studioFeed = feed;
section.tabIndex = 0;
noteModule(section, '保存页面后将加载动态内容。');
} }
end.before(section); end.before(section);
registerSection(section, null); const entry = registerSection(section, null, {template});
addPending(entry);
section.scrollIntoView({block: 'start'}); section.scrollIntoView({block: 'start'});
section.querySelector('[data-studio-part="body"]').focus({preventScroll: true}); if (feed) selectElement(section);
const $cancel = $('<button>', {type: 'button', text: '取消新增:' + title.textContent}); else entry.fields.body.node.focus({preventScroll: true});
const $item = $('<li>').append($cancel).appendTo($pending);
$pending.prop('hidden', false);
$cancel.on('click', () => {
if (section.contains(activeBody)) selectBody(null);
if (section.contains(selectedElement)) selectElement(null);
section.remove();
sections = sections.filter(({key}) => key !== id);
$item.remove();
$pending.prop('hidden', !$pending.children().length);
$templateStatus.text('已取消新增区块。');
});
$templateStatus.text('已添加 ' + title.textContent + ' 区块。'); $templateStatus.text('已添加 ' + title.textContent + ' 区块。');
}); });
@@ -1028,6 +1178,7 @@ jQuery(function ($) {
selectElement(null); selectElement(null);
$pending.empty().prop('hidden', true); $pending.empty().prop('hidden', true);
sections = []; sections = [];
deletedModules = [];
$doc.find('[data-studio-section]').each((_, section) => registerSection(section)); $doc.find('[data-studio-section]').each((_, section) => registerSection(section));
$doc.on('focusin.canvas', '[contenteditable]', function () { $doc.on('focusin.canvas', '[contenteditable]', function () {
@@ -1038,22 +1189,42 @@ jQuery(function ($) {
$doc.on('click.canvas dblclick.canvas', mediaTargets, function (event) { $doc.on('click.canvas dblclick.canvas', mediaTargets, function (event) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
const dynamic = this.closest('[data-studio-dynamic]');
if (dynamic) {
selectBody(null);
selectElement(dynamic);
return;
}
selectBody(this.closest('[data-studio-part="body"]')); selectBody(this.closest('[data-studio-part="body"]'));
selectElement(this); selectElement(this);
if (event.type === 'dblclick') replaceMedia(); if (event.type === 'dblclick') replaceMedia();
}); });
$doc.on('click.canvas', (event) => { $doc.on('click.canvas', (event) => {
const node = event.target; const node = event.target;
const dynamic = node.closest?.('[data-studio-dynamic]');
if (dynamic) {
selectBody(null);
selectElement(dynamic);
return;
}
const field = node.closest?.(canvasFields); const field = node.closest?.(canvasFields);
selectElement(doc.getSelection()?.isCollapsed ? field || editableBodyElement(node) : null); selectElement(doc.getSelection()?.isCollapsed ? field || editableBodyElement(node) : null);
}); });
$doc.on('dblclick.canvas', '[data-studio-part="body"] a', function (event) { $doc.on('dblclick.canvas', '[data-studio-part="body"] a', function (event) {
event.preventDefault(); event.preventDefault();
if (!event.target.closest(mediaTargets)) editResource(this); if (!this.closest('[data-studio-dynamic]') && !event.target.closest(mediaTargets)) editResource(this);
}); });
$doc.on('keydown.canvas', (event) => { $doc.on('keydown.canvas', (event) => {
if (event.key === 'Escape') selectElement(null); if (event.key === 'Escape') selectElement(null);
}); });
$doc.on('keydown.canvas', '[data-studio-dynamic]', function (event) {
if ((event.key === 'Enter' || event.key === ' ') && event.target === this) {
event.preventDefault();
selectBody(null);
selectElement(this);
$elementTools.find('[data-element-module-settings]').trigger('focus');
}
});
$doc.on('keydown.canvas', '[data-studio-hero-image]', function (event) { $doc.on('keydown.canvas', '[data-studio-hero-image]', function (event) {
if (event.key === 'Enter' || event.key === ' ') { if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault(); event.preventDefault();
@@ -1086,7 +1257,8 @@ jQuery(function ($) {
if (!body) return; if (!body) return;
$studio.get(0).scrollIntoView({block: 'start'}); $studio.get(0).scrollIntoView({block: 'start'});
section.scrollIntoView({block: 'start'}); section.scrollIntoView({block: 'start'});
body.focus({preventScroll: true}); if (section.hasAttribute('data-studio-dynamic')) selectElement(section);
else body.focus({preventScroll: true});
}); });
}); });
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

+80 -4
View File
@@ -46,6 +46,7 @@ async function run(browser) {
assert.equal(await dashboard.locator('[data-page-item]:visible').count(), 1); assert.equal(await dashboard.locator('[data-page-item]:visible').count(), 1);
assert.equal(await page.getByRole('navigation', {name: '后台导航'}).getByRole('link', {name: '页面'}).getAttribute('aria-current'), 'page'); assert.equal(await page.getByRole('navigation', {name: '后台导航'}).getByRole('link', {name: '页面'}).getAttribute('aria-current'), 'page');
await post('/admin/page-blocks/' + slug, {operation: 'create', key: 'fixtures', preset: 'text'}); await post('/admin/page-blocks/' + slug, {operation: 'create', key: 'fixtures', preset: 'text'});
await post('/admin/page-blocks/' + slug, {operation: 'create', key: 'fee-sample', preset: 'existing-sc-pricing'});
await post('/admin/pages/' + slug + '/fixtures', { await post('/admin/pages/' + slug + '/fixtures', {
version: '0', title: '媒体和链接', lead: '', style: 'plain', version: '0', title: '媒体和链接', lead: '', style: 'plain',
body: '<p><img src="/assets/favicon.png" alt="示例图片" width="96"></p>' body: '<p><img src="/assets/favicon.png" alt="示例图片" width="96"></p>'
@@ -165,9 +166,12 @@ async function run(browser) {
const elementTab = gallery.getByRole('tab', {name: '元素'}); const elementTab = gallery.getByRole('tab', {name: '元素'});
const backToModules = () => modules.getByRole('button', {name: '返回分类'}).click(); const backToModules = () => modules.getByRole('button', {name: '返回分类'}).click();
const openModule = (key) => modules.locator('[data-library-category="' + key + '"]').click(); const openModule = (key) => modules.locator('[data-library-category="' + key + '"]').click();
assert.equal(await modules.locator('[data-library-category]:visible').count(), 7); assert.equal(await modules.locator('[data-library-category]:visible').count(), 12);
assert.equal(await modules.locator('[data-template-card]:visible').count(), 0); assert.equal(await modules.locator('[data-template-card]:visible').count(), 0);
assert.equal(await modules.locator('[data-template-card]').count(), 26); assert.equal(await modules.locator('[data-template-card]').count(), 65);
assert.equal(await modules.getByText('按锚点新建区块').count(), 1);
assert.equal(await gallery.locator('[data-library-panel=layers]').getByText(/首屏与目录|按锚点新建区块/).count(), 0);
assert.equal(await page.locator('#studio-page-settings').getByText('首屏与目录').count(), 1);
await copyText.first().click(); await copyText.first().click();
await moduleTab.press('ArrowRight'); await moduleTab.press('ArrowRight');
@@ -177,7 +181,7 @@ async function run(browser) {
const structural = elements.locator('[data-library-category=structure-elements]'); const structural = elements.locator('[data-library-category=structure-elements]');
await structural.click(); await structural.click();
assert.equal(await elements.locator('[data-library-category]:visible').count(), 0); assert.equal(await elements.locator('[data-library-category]:visible').count(), 0);
assert.equal(await elements.locator('[data-canvas-element]:visible').count(), 5); assert.equal(await elements.locator('[data-canvas-element]:visible').count(), 12);
await elements.getByRole('button', {name: '插入分割线'}).click(); await elements.getByRole('button', {name: '插入分割线'}).click();
await frame.locator('#fixtures .studio-divider').waitFor(); await frame.locator('#fixtures .studio-divider').waitFor();
await elements.getByRole('button', {name: '插入留白'}).click(); await elements.getByRole('button', {name: '插入留白'}).click();
@@ -221,6 +225,15 @@ async function run(browser) {
await modules.locator('[data-canvas-template=pricing]').click(); await modules.locator('[data-canvas-template=pricing]').click();
await frame.locator('.studio-pricing').waitFor(); await frame.locator('.studio-pricing').waitFor();
await backToModules(); await backToModules();
await openModule('existing-sc');
await modules.locator('[data-canvas-template=existing-sc-materials]').click();
await frame.locator('section[id^=block-]').filter({hasText: '申请软著需要哪些材料'}).waitFor();
await modules.locator('[data-canvas-template=existing-sc-pricing]').click();
const reused = frame.locator('section[id^=block-]').filter({hasText: '服务方案与价格'});
const reusedId = await reused.getAttribute('id');
assert.equal(await reused.locator('#' + reusedId + '-price1').count(), 1);
assert.equal(await frame.locator('#fee-sample-price1').count(), 1);
await backToModules();
await openModule('content'); await openModule('content');
await search.fill('重点提示'); await search.fill('重点提示');
await modules.locator('[data-canvas-template=notice]').click(); await modules.locator('[data-canvas-template=notice]').click();
@@ -271,6 +284,7 @@ async function run(browser) {
assert(await phoneGallery.locator('#blocks').evaluate((details) => details.open)); assert(await phoneGallery.locator('#blocks').evaluate((details) => details.open));
await phone.close(); await phone.close();
await verifyArticleLibrary(browser, context, page, post, slug, feedId); await verifyArticleLibrary(browser, context, page, post, slug, feedId);
await verifyHomeModules(context, page);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
await context.close(); await context.close();
} }
@@ -414,11 +428,73 @@ async function verifyScopedArchive(context, admin, page, post, slug, feedId, cat
assert.equal(await page.getByRole('link', {name: '返回原页面'}).getAttribute('href'), '/' + slug + '#' + feedId); assert.equal(await page.getByRole('link', {name: '返回原页面'}).getAttribute('href'), '/' + slug + '#' + feedId);
} }
async function verifyHomeModules(context, page) {
await page.goto('/admin/pages/home');
const frame = page.frameLocator('iframe[title="可编辑页面画布"]');
const tools = page.getByRole('group', {name: '所选元素'});
const card = frame.locator('#hero-directory .hero-directory a').nth(1);
assert.equal(await frame.locator('#hero-directory .hero-directory a').count(), 5);
await card.click();
const edit = tools.getByRole('button', {name: '属性'});
assert.equal((await edit.textContent()).trim(), '');
await edit.click();
const props = page.locator('[data-canvas-properties]');
await props.locator('[name=label]').fill('PAGEPAN 导航验证');
await props.locator('[name=note]').fill('编辑过的导航说明');
await props.locator('[name=url]').fill('/pagepan#download');
await props.getByRole('button', {name: '应用'}).click();
assert.equal(await card.locator('small').textContent(), '编辑过的导航说明');
await frame.locator('#network h2').click();
const moduleSettings = tools.getByRole('button', {name: '模块设置'});
await moduleSettings.waitFor();
assert.equal(await tools.getByRole('button').allTextContents().then((items) => items.map((text) => text.trim()).join('')), '');
assert.equal(await tools.getByRole('button').count(), 3);
assert.equal(await frame.locator('#network h2').getAttribute('contenteditable'), null);
const copyButton = tools.getByRole('button', {name: '复制'});
await copyButton.click();
const pending = frame.locator('[data-studio-dynamic][id^=block-]').filter({hasText: '模块副本将在保存页面后生效。'});
const id = await pending.getAttribute('id');
await moduleSettings.click();
const dialog = page.locator('[data-module-dialog]');
await dialog.locator('[name=module_title]').fill('复制的伙伴模块');
await dialog.locator('[name=feed_limit]').fill('1');
await dialog.locator('[name="feed_categories[]"][value=supported-projects]').uncheck();
assert(await dialog.locator('[name="feed_categories[]"][value=partners]').isChecked());
await dialog.getByRole('button', {name: '应用'}).click();
await page.getByRole('button', {name: '保存页面', exact: true}).first().click();
await page.locator('[data-save-confirmation]').waitFor();
await frame.locator('#' + id + ' h2').getByText('复制的伙伴模块').waitFor();
const publicPage = await context.newPage();
await publicPage.goto('/');
const module = publicPage.locator('#' + id);
assert.equal(await module.locator('.network-group').count(), 1);
assert.equal(await module.locator('.network-list li').count(), 1);
assert.equal(await module.getByRole('link', {name: '查看全部'}).getAttribute('href'), '/articles/feed/home/' + id);
assert.equal(await publicPage.locator('#hero-directory a').nth(1).getAttribute('href'), '/pagepan#download');
assert.equal(await publicPage.locator('#hero-directory a').nth(1).locator('small').textContent(), '编辑过的导航说明');
assert.equal(await publicPage.locator('#network #supported-projects').count(), 1);
await page.bringToFront();
await frame.locator('#' + id + ' h2').click();
page.once('dialog', (prompt) => prompt.accept());
await tools.getByRole('button', {name: '删除'}).click();
await frame.locator('#' + id).waitFor({state: 'detached'});
await page.getByRole('button', {name: '保存页面', exact: true}).first().click();
await page.locator('[data-save-confirmation]').waitFor();
await publicPage.reload();
assert.equal(await publicPage.locator('#' + id).count(), 0);
assert.equal(await publicPage.locator('#network').count(), 1);
assert.equal((await context.request.get('/articles/feed/home/' + id)).status(), 404);
await publicPage.close();
}
(async () => { (async () => {
const browser = await chromium.launch({executablePath: process.env.CHROMIUM_EXECUTABLE || undefined}); const browser = await chromium.launch({executablePath: process.env.CHROMIUM_EXECUTABLE || undefined});
try { try {
await run(browser); await run(browser);
console.log('Passed Chromium dashboard, categorized library, canvas persistence, and scoped article archives.'); console.log('Passed Chromium dashboard, template library, dynamic module tools, homepage links, and scoped archives.');
} finally { } finally {
await browser.close(); await browser.close();
} }