diff --git a/README.md b/README.md index f4e0392..a1b7c34 100644 --- a/README.md +++ b/README.md @@ -27,10 +27,10 @@ php bin/admin.php reset admin@example.com ## 后台编辑 -- **页面设计**支持新建草稿、发布和撤回。首屏标题与简介可在桌面或手机画布中直接编辑。区块支持新增、排序、删除、可视化编辑、媒体插入和 HTML 源码。单击画布元素可用浮动工具条复制或删除。选中媒体后,可拖动边缘手柄调整宽度。编辑器左侧可按分类和名称查找模板。悬停或键盘聚焦缩略图可放大,点击可打开预览。 +- **页面设计**支持新建草稿、发布和撤回。首屏标题与简介可在桌面或手机画布中直接编辑。区块支持新增、排序、删除、可视化编辑、媒体插入和 HTML 源码。单击画布元素可用浮动工具条复制或删除。选中媒体后,可拖动边缘手柄调整宽度。浮动工具条可将正文元素、区块标题和首屏元素对齐到左侧、中央或右侧。编辑器左侧可插入基础元素,或按分类和名称查找区块模板。悬停或键盘聚焦缩略图可放大,点击可打开预览。 - **媒体库**集中列出项目静态文件及上传文件,支持查找、选取、复制路径、改名和归档。归档资源的已有 URL 保持可访问。上传文件放在 `LAYSENSE_MEDIA_DIR`,由 `/assets/uploads/` 提供。 - **文章**使用自托管的 TOAST UI Editor 3.2.2(MIT)。Markdown 左侧源码、右侧实时预览,富文本使用所见即所得模式。文章可以加入多个分类,可在「管理分类」创建新分类。 -- **分类文章**支持在任意页面添加,保存区块后在「图层」中编辑分类、展示数量和合并或标签页模式。 +- **分类文章**支持在任意页面添加,保存区块后在「图层」中编辑分类、展示数量和合并或标签页模式。「查看全部动态」和翻页只列出该区块所选的分类。 - **产品与服务**(`/services`)和**支持项目与合作伙伴**(`/network`)由文章分类生成。通过文章的目录卡片设置图片、链接和排序,使用草稿状态可从目录撤下。 - **网站设置**分别编辑页头标志、导航及按钮,和页脚的公司信息、链接与备注。CDN 设置接受 HTTPS 源站地址。浏览器看到的公开 `/assets/…` 路径使用该源站。 - 文章支持摘要和标签。状态选「草稿」可撤回公开文章。已发布文章改网址标识后,旧标识会自动跳转。 @@ -70,7 +70,7 @@ location = /admin/media { | `LAYSENSE_SECURE_COOKIES` | 默认关闭 · 本地 HTTP 使用默认值。生产 HTTPS 设置为 `1`。 | | `LAYSENSE_TRUSTED_PROXIES` | 默认 `127.0.0.1,::1` · 逗号分隔的受信反代 IP,设为空字符串可关闭信任 | -SQLite 已启用 WAL。本版需要新的 SQLite 文件。将 `LAYSENSE_DB` 指向新文件,执行 `php bin/install.php`,再按上面的步骤创建管理员并重启 Webman。安装会预载网站自带页面、文章、产品和伙伴目录。服务用户需要对 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 diff --git a/app/Content/BlockTemplates.php b/app/Content/BlockTemplates.php index 5ed679d..a04ec0c 100644 --- a/app/Content/BlockTemplates.php +++ b/app/Content/BlockTemplates.php @@ -8,12 +8,25 @@ final class BlockTemplates { public const ARTICLE_FEED = '{"categories":["announcement","news","product"],"mode":"merged","limit":6}'; + public const ELEMENTS = [ + 'paragraph' => ['段落', '

填写正文。

'], + 'subheading' => ['小标题', '

填写小标题

'], + 'bullet-list' => ['项目列表', ''], + 'button' => ['按钮', '

联系来笙

'], + 'separator' => ['分割线', '
'], + 'code' => ['代码块', '
填写代码
'], + 'image' => ['图片', '', 'image/'], + 'video' => ['视频', '', 'video/'], + 'audio' => ['音频', '', 'audio/'], + ]; + public const GROUPS = [ 'content' => ['标题与正文', [ 'headline' => ['标题与简介', '

填写区块标题

用一句话补充背景或说明。

'], 'text' => ['正文', '

在这里输入区块内容。

'], 'articles' => ['分类文章', ''], 'list' => ['步骤列表', '
  1. 填写第一步
  2. 填写第二步
  3. 填写第三步
'], + 'notice' => ['重点提示', '

填写重要提示

说明访客需要知悉的事项、条件或时间。

'], ]], 'cover' => ['封面与横幅', [ 'cover' => ['图文封面', '

用一句话介绍你的产品

在首段说明访客能获得什么。

查看服务
'], @@ -23,17 +36,26 @@ final class BlockTemplates 'image' => ['图文', '

介绍主题

在这里说明图片或产品。

'], 'grid' => ['双栏网格', '

第一栏

填写主要内容。

第二栏

补充相关信息。

'], ]], + 'media' => ['媒体', [ + 'gallery' => ['三图画廊', ''], + 'video-demo' => ['视频演示', '

演示视频

说明视频涵盖的功能与操作。

'], + ]], 'features' => ['特性与口碑', [ 'features' => ['特性卡片', '

特点一

介绍这个特点。

特点二

介绍这个特点。

特点三

介绍这个特点。

'], 'quote' => ['引文', '

在这里填写引用或用户反馈。

'], + 'metrics' => ['关键数据', '
累计项目
100
服务覆盖
12
合作伙伴
8
'], + 'testimonials' => ['用户评价', '

填写用户的评价,并说明他们获得的结果。

用户姓名 · 公司或角色

填写另一条用户评价。

用户姓名 · 公司或角色

'], ]], 'details' => ['表格与问答', [ 'table' => ['对比表格', '
项目说明
项目一填写说明
项目二填写说明
'], 'faq' => ['常见问题', '
请输入问题

请输入答案。

'], + 'timeline' => ['时间线', '
  1. 确定目标

    填写这一阶段需要完成的事项。

  2. 实施与验收

    填写交付时间与验收标准。

'], + 'checklist' => ['清单', ''], ]], 'actions' => ['导航与引导', [ 'navigation' => ['快速导航', ''], 'cta' => ['行动按钮', '

说明下一步。

联系来笙

'], + 'resources' => ['资料与链接', ''], ]], ]; diff --git a/app/Content/Database.php b/app/Content/Database.php index 7c8aeaa..2ce7641 100644 --- a/app/Content/Database.php +++ b/app/Content/Database.php @@ -44,6 +44,12 @@ final class Database throw new RuntimeException('请将 LAYSENSE_DB 指向一个新的 SQLite 文件,再运行安装命令。'); } $pdo->exec(file_get_contents($root . '/resources/schema.sql')); + foreach (['pages', 'sections'] as $table) { + $columns = array_column($pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(), 'name'); + if (!in_array('alignments', $columns, true)) { + $pdo->exec("ALTER TABLE $table ADD COLUMN alignments TEXT NOT NULL DEFAULT '{}'"); + } + } $site = $pdo->prepare('INSERT OR IGNORE INTO site_settings (id, payload) VALUES (1, ?)'); $site->execute([self::json($seed['site'])]); diff --git a/app/Content/Html.php b/app/Content/Html.php index a993ea2..60df8c5 100644 --- a/app/Content/Html.php +++ b/app/Content/Html.php @@ -12,6 +12,8 @@ use RuntimeException; final class Html { + public const ALIGNMENTS = ['left', 'center', 'right']; + private const TAGS = [ 'a' => ['href'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [], 'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'], diff --git a/app/Content/Repository.php b/app/Content/Repository.php index 27725c4..3d35699 100644 --- a/app/Content/Repository.php +++ b/app/Content/Repository.php @@ -52,7 +52,7 @@ final class Repository if (!$page) { return null; } - foreach (['actions', 'quicklinks'] as $key) { + foreach (['actions', 'quicklinks', 'alignments'] as $key) { $page[$key] = json_decode($page[$key], true, flags: JSON_THROW_ON_ERROR); } $query = $this->pdo->prepare('SELECT * FROM sections WHERE page_slug = ? ORDER BY position, key'); @@ -67,14 +67,21 @@ final class Repository return $this->one('SELECT * FROM sections WHERE page_slug = ? AND key = ?', [$page, $key]); } + public function publishedFeed(string $page, string $key): ?array + { + return $this->one("SELECT sections.title, sections.feed FROM sections + JOIN pages ON pages.slug = sections.page_slug + WHERE pages.slug = ? AND pages.status = 'published' AND sections.key = ? AND sections.feed IS NOT NULL", [$page, $key]); + } + public function savePage(string $slug, array $data, int $version, array $sections = []): void { Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections): void { $query = $pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?, - image = ?, alt = ?, image_scale = ?, actions = ?, quicklinks = ?, status = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?'); + image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, status = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?'); $query->execute([ $data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'], - $data['image'], $data['alt'], $data['image_scale'], Database::json($data['actions']), Database::json($data['quicklinks']), + $data['image'], $data['alt'], $data['image_scale'], Database::json($data['alignments']), Database::json($data['actions']), Database::json($data['quicklinks']), $data['status'], self::now(), $slug, $version, ]); self::checkVersion($query->rowCount()); @@ -98,9 +105,9 @@ final class Repository private static function updateSection(PDO $pdo, string $page, string $key, array $data, int $version): void { - $query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, feed = ?, version = version + 1 + $query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, feed = ?, alignments = COALESCE(?, alignments), version = version + 1 WHERE page_slug = ? AND key = ? AND version = ?'); - $query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $data['feed'] ?? null, $page, $key, $version]); + $query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $data['feed'] ?? null, $data['alignments'] ?? null, $page, $key, $version]); self::checkVersion($query->rowCount()); } @@ -114,9 +121,9 @@ final class Repository private static function insertSection(PDO $pdo, string $page, string $key, array $data): void { - $query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, position) - SELECT ?, ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?'); - $query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $page]); + $query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, alignments, position) + SELECT ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?'); + $query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $data['alignments'] ?? '{}', $page]); if ($query->rowCount() !== 1) { throw new RuntimeException('此区块锚点已被使用。'); } diff --git a/app/Content/View.php b/app/Content/View.php index 848b172..470e9c5 100644 --- a/app/Content/View.php +++ b/app/Content/View.php @@ -65,6 +65,20 @@ final class View return $value ? date($format, strtotime($value)) : ''; } + public static function alignmentClass(?string $alignment): string + { + return in_array($alignment, Html::ALIGNMENTS, true) ? ' studio-align-' . $alignment : ''; + } + + public static function archivePage(string $path, int $page): string + { + if ($page === 1) { + return $path; + } + + return $path . (str_contains($path, '?') ? '&' : '?') . 'page=' . $page; + } + public static function redirect(string $path, int $status = 303): Response { return new Response($status, ['Location' => $path, 'Cache-Control' => $status === 301 ? 'public, max-age=300' : 'no-store'], ''); diff --git a/app/Controller/AdminController.php b/app/Controller/AdminController.php index 7ff0c89..7f9d57b 100644 --- a/app/Controller/AdminController.php +++ b/app/Controller/AdminController.php @@ -255,6 +255,9 @@ class AdminController } $page = array_replace($page, $data, ['version' => $this->version($request)]); try { + $data['alignments'] = $request->post('alignments') === null ? $page['alignments'] + : $this->alignmentMap(json_decode($this->input($request, 'alignments'), true), ['heading', 'lead', 'actions', 'image']); + $page['alignments'] = $data['alignments']; $data['quicklinks'] = $request->post('quicklinks') === null ? $page['quicklinks'] : SiteDesign::parseLinks($this->input($request, 'quicklinks')); if ($data['name'] === '' || mb_strlen($data['name']) > 100 || !in_array($data['status'], ['draft', 'published'], true) || $data['title'] === '' || mb_strlen($data['title']) > 160 || @@ -334,8 +337,9 @@ class AdminController $key = $change['key'] ?? null; $version = $change['version'] ?? null; $fields = $change['fields'] ?? null; + $alignments = $change['alignments'] ?? null; $isNew = is_array($change) && array_key_exists('version', $change) && $version === null; - if (!is_string($key) || isset($updates[$key]) || !is_array($fields) || $fields === [] + if (!is_string($key) || isset($updates[$key]) || !is_array($fields) || ($fields === [] && $alignments === null) || ($isNew ? (isset($available[$key]) || !preg_match('/^block-[a-f0-9]{32}$/D', $key)) : (!isset($available[$key]) || !is_int($version) || $version !== (int) $available[$key]['version']))) { throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。'); @@ -353,6 +357,9 @@ class AdminController } $section[$field] = trim($value); } + if ($alignments !== null) { + $section['alignments'] = Database::json($this->alignmentMap($alignments, ['title', 'lead'])); + } $this->checkSection($section, $section['style']); if (isset($fields['body'])) { $section['body'] = Html::sanitize($section['body']); @@ -367,6 +374,20 @@ class AdminController return $updates; } + private function alignmentMap(mixed $alignments, array $fields): array + { + if (!is_array($alignments) || array_diff(array_keys($alignments), $fields)) { + throw new RuntimeException('画布对齐设置无效。'); + } + foreach ($alignments as $value) { + if (!in_array($value, Html::ALIGNMENTS, true)) { + throw new RuntimeException('画布对齐设置无效。'); + } + } + + return $alignments; + } + private function checkSection(array $section, string $savedStyle): void { if ($section['title'] === '' || mb_strlen($section['title']) > 100 || mb_strlen($section['lead']) > 500 diff --git a/app/Controller/SiteController.php b/app/Controller/SiteController.php index ae3e9af..1e9585f 100644 --- a/app/Controller/SiteController.php +++ b/app/Controller/SiteController.php @@ -39,10 +39,12 @@ final class SiteController $feed = json_decode($section['feed'], true, flags: JSON_THROW_ON_ERROR); $tabs = $feed['mode'] === 'tabs' && count($feed['categories']) > 1; $section['articleFeed'] = []; + $section['archivePath'] = $page['status'] === 'published' ? '/articles/feed/' . $slug . '/' . $section['key'] : null; foreach ($tabs ? $feed['categories'] : [''] as $category) { + $selected = $category === '' ? $feed['categories'] : [$category]; $section['articleFeed'][] = [ - 'label' => $categories[$category] ?? '', - 'articles' => $repo->articles($category === '' ? $feed['categories'] : $category, limit: $feed['limit']), + 'categories' => $selected, 'label' => $categories[$category] ?? '', + 'articles' => $repo->articles($selected, limit: $feed['limit']), ]; } } @@ -102,6 +104,60 @@ final class SiteController } $title = $category ? $categories[$category] : ($tag ?: '来笙动态'); $path = '/articles' . ($category ? '/category/' . $category : ($tag ? '/tag/' . rawurlencode($tag) : '')); + + $categoryLinks = []; + foreach (array_keys($categories) as $key) { + $categoryLinks[$key] = '/articles/category/' . $key; + } + + return $this->renderArchive($request, $repo, $category, $tag, [ + 'headline' => $title, 'description' => '查看来笙的公告、新闻和产品动态。', + 'archivePath' => $path, 'allPath' => '/articles', + 'categoryLinks' => $categoryLinks, + 'categories' => $categories, 'category' => $category, 'tag' => $tag, + 'backPath' => $category || $tag ? '/articles' : null, 'backLabel' => '全部动态', + ]); + } + + public function feedArchive(Request $request, string $slug, string $key): Response + { + $repo = new Repository(); + $section = $repo->publishedFeed($slug, $key); + if (!$section) { + return $this->missing($request); + } + $feed = json_decode($section['feed'], true, flags: JSON_THROW_ON_ERROR); + $labels = $repo->categories(); + $categories = []; + foreach ($feed['categories'] as $value) { + if (isset($labels[$value])) { + $categories[$value] = $labels[$value]; + } + } + $category = $request->get('category'); + if (!$categories || ($category !== null && (!is_string($category) || !isset($categories[$category])))) { + return $this->missing($request); + } + + $allPath = '/articles/feed/' . $slug . '/' . $key; + $returnPath = ($slug === 'home' ? '/' : '/' . $slug) . '#' . $key; + $categoryLinks = []; + foreach (array_keys($categories) as $value) { + $categoryLinks[$value] = $allPath . '?category=' . rawurlencode((string) $value); + } + + return $this->renderArchive($request, $repo, $category ?? array_keys($categories), null, [ + 'headline' => $section['title'] . ($category !== null ? ' · ' . $categories[$category] : ''), + 'description' => '查看' . implode('、', $categories) . '分类下的文章。', + 'archivePath' => $category === null ? $allPath : $categoryLinks[$category], 'allPath' => $allPath, + 'categoryLinks' => $categoryLinks, 'categories' => $categories, 'category' => $category, 'tag' => null, + 'categoryScope' => $category === null ? array_keys($categories) : [$category], + 'backPath' => $returnPath, 'backLabel' => '返回原页面', 'noindex' => true, + ]); + } + + private function renderArchive(Request $request, Repository $repo, string|array|null $category, ?string $tag, array $view): Response + { $number = $request->get('page', '1'); if (!is_scalar($number) || !preg_match('/^[1-9][0-9]{0,4}$/D', (string) $number)) { return $this->missing($request); @@ -111,13 +167,12 @@ final class SiteController if ($page > 1 && $articles === []) { return $this->missing($request); } + $path = $view['archivePath']; - return View::render('archive', [ - 'site' => $repo->site(), 'title' => $title . ' · 来笙', 'headline' => $title, - 'description' => '查看来笙的公告、新闻和产品动态。', - 'path' => $path . ($page > 1 ? '?page=' . $page : ''), 'archivePath' => $path, - 'categories' => $categories, 'category' => $category, 'tag' => $tag, 'pageNumber' => $page, - 'hasNext' => count($articles) > 20, 'articles' => array_slice($articles, 0, 20), + return View::render('archive', $view + [ + 'site' => $repo->site(), 'title' => $view['headline'] . ' · 来笙', + 'path' => $page > 1 ? View::archivePage($path, $page) : $path, + 'pageNumber' => $page, 'hasNext' => count($articles) > 20, 'articles' => array_slice($articles, 0, 20), 'noindex' => $articles === [], ]); } diff --git a/app/view/admin-articles.php b/app/view/admin-articles.php index e8b18af..cc13ab2 100644 --- a/app/view/admin-articles.php +++ b/app/view/admin-articles.php @@ -15,7 +15,7 @@ $filters = $category ? 'category=' . rawurlencode($category) . '&' : '';
diff --git a/app/view/admin-category-checkboxes.php b/app/view/admin-category-checkboxes.php index 166bdae..208f97d 100644 --- a/app/view/admin-category-checkboxes.php +++ b/app/view/admin-category-checkboxes.php @@ -2,12 +2,13 @@ use App\Content\View; $e = View::escape(...); +$checked = array_fill_keys($selected, true); ?>
$label): ?> - +
diff --git a/app/view/admin-page.php b/app/view/admin-page.php index 4f2b0a1..c43649b 100644 --- a/app/view/admin-page.php +++ b/app/view/admin-page.php @@ -1,4 +1,5 @@
-

单击画布中的元素可打开浮动工具条。选中媒体后可拖动边缘手柄调整宽度。

+

单击画布元素可设置对齐、复制或删除。选中媒体后可拖动边缘手柄调整宽度。

编辑属性

@@ -130,6 +136,7 @@ $previewUrl = '/admin/pages/' . $slug . '/preview'; + diff --git a/app/view/archive.php b/app/view/archive.php index 2d9cc4d..e08f665 100644 --- a/app/view/archive.php +++ b/app/view/archive.php @@ -6,22 +6,22 @@ $e = View::escape(...);
- 全部动态 +

-

来笙的公告、新闻和产品动态。

+

- $articles]) ?> + $articles, 'categoryScope' => $categoryScope ?? null]) ?> 1 || $hasNext): ?>
diff --git a/app/view/article-feed.php b/app/view/article-feed.php index c120834..f10942e 100644 --- a/app/view/article-feed.php +++ b/app/view/article-feed.php @@ -14,7 +14,10 @@ $e = View::escape(...); $group): ?>

- $group['articles']]) ?> + $group['articles'], 'categoryScope' => $group['categories']]) ?>
+ +

查看全部动态

+ diff --git a/app/view/article-list.php b/app/view/article-list.php index 94deec9..8bde699 100644 --- a/app/view/article-list.php +++ b/app/view/article-list.php @@ -2,13 +2,15 @@ use App\Content\View; $e = View::escape(...); +$scope = isset($categoryScope) ? array_flip($categoryScope) : null; ?>
    +
  • - + diff --git a/app/view/page.php b/app/view/page.php index 3efa202..f33dad0 100644 --- a/app/view/page.php +++ b/app/view/page.php @@ -5,6 +5,8 @@ use App\Content\View; $e = View::escape(...); $home = $page['slug'] === 'home'; $service = in_array($page['slug'], ['sc', 'shnu-sc'], true); +$alignments = $page['alignments']; +$alignField = static fn (string $name): string => $canvas ? ' data-studio-align-field="' . $name . '"' : ''; $field = static fn (string $name): string => $canvas ? ' data-studio-field="' . $name . '"' : ''; ?>
    @@ -25,16 +27,16 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' .

    -

    >>

    -

    >

    -
    -
    > +
    > alt="" width="1448" height="1086" fetchpriority="high">

    查看全部动态

    ') { + $body = ''; +} ?>
    >
    -

    >

    - >

    +

    >

    + >

    - $section['articleFeed'], 'sectionKey' => $section['key']]) ?> + $section['articleFeed'], 'sectionKey' => $section['key'], 'archivePath' => $section['archivePath']]) ?> -
    >
    +
    >
    diff --git a/app/view/studio-templates.php b/app/view/studio-templates.php index a66c3a5..b966722 100644 --- a/app/view/studio-templates.php +++ b/app/view/studio-templates.php @@ -6,6 +6,19 @@ use App\Content\View; $e = View::escape(...); ?>
    +
    + 基础元素 +
    + $element): ?> + + + + +
    +

    选中画布正文后插入。

    +
    diff --git a/config/route.php b/config/route.php index 2548d3c..cc00566 100644 --- a/config/route.php +++ b/config/route.php @@ -16,6 +16,7 @@ Route::get('/assets/uploads/{name:[a-f0-9]{32}\.[a-z0-9]+}', [MediaController::c Route::get('/articles', [SiteController::class, 'archive']); Route::get('/articles/category/{category:[a-z0-9-]+}', [SiteController::class, 'archive']); Route::get('/articles/tag/{tag:[^/]+}', [SiteController::class, 'tagged']); +Route::get('/articles/feed/{slug:[a-z0-9-]+}/{key:[a-z0-9-]+}', [SiteController::class, 'feedArchive']); Route::get('/articles/{slug:[a-z0-9-]+}', [SiteController::class, 'article']); Route::get('/main', static fn () => View::redirect('/articles', 301)); Route::get('/main/category/{id:[0-9]+}.html', [SiteController::class, 'legacyCategory']); diff --git a/public/assets/admin.css b/public/assets/admin.css index d16d9f7..74f5ee9 100644 --- a/public/assets/admin.css +++ b/public/assets/admin.css @@ -234,3 +234,15 @@ .article-editor-heading { display: flex; align-items: center; justify-content: space-between; gap: .6rem; margin-bottom: .45rem; } .article-editor-heading > .button { min-height: 2.1rem; padding: .25rem .6rem; } .article-editor-help:empty { display: none; } + +.studio-element-library { padding: .55rem .65rem; border: 1px solid var(--line); border-radius: .5rem; } +.studio-element-library summary { font-size: .9rem; font-weight: 650; cursor: pointer; } +.studio-element-library [role="group"] { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .35rem; margin-top: .55rem; } +.studio-element-library button { + min-height: 2.35rem; padding: .2rem; border: 1px solid var(--line); + border-radius: .4rem; color: var(--ink); background: var(--white); font-size: .8rem; cursor: pointer; +} +.studio-element-library .field-note { margin: .45rem 0 0; font-size: .78rem; } +.studio-element-align { display: flex; gap: .05rem; padding-inline-end: .2rem; border-inline-end: 1px solid #ffffff55; } +.studio-element-align button { padding-inline: .38rem; } +.studio-element-align button[aria-pressed="true"] { background: white; color: #244bc8; } diff --git a/public/assets/site.css b/public/assets/site.css index dcad82e..28d978e 100644 --- a/public/assets/site.css +++ b/public/assets/site.css @@ -647,3 +647,58 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); } .article-tabs button { padding: .38rem .8rem; background: white; border: 1px solid var(--line); border-radius: .45rem; color: inherit; cursor: pointer; } .article-tabs button[aria-selected="true"] { border-color: var(--accent); color: var(--accent); background: var(--accent-light); } .network-list .network-detail { min-height: 0; padding-block: .2rem; font-size: .85rem; } + +.article-feed-archive { margin: 1rem 0 0; } +.studio-notice { padding: clamp(1rem, 3vw, 1.8rem); border-inline-start: 3px solid var(--accent); border-radius: .55rem; background: var(--accent-light); } +.studio-notice p, .studio-testimonials p:last-child, .studio-timeline li p:last-child { margin-bottom: 0; } +.studio-gallery, .studio-metrics { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1rem; } +.studio-gallery img { width: 100%; aspect-ratio: 4 / 3; object-fit: contain; border: 1px solid var(--line); background: var(--paper); } +.studio-split video { width: 100%; aspect-ratio: 16 / 9; border-radius: .6rem; background: var(--navy); object-fit: contain; } +.studio-metrics { margin-block: 0 1rem; } +.studio-metrics div { padding: 1rem; border-block-start: 1px solid var(--line); } +.studio-metrics dd { margin: .4rem 0 0; color: var(--accent); font-size: clamp(1.65rem, 5vw, 3rem); font-weight: 700; } +.studio-testimonials blockquote { margin: 0; padding: 1.1rem 1.3rem; border: 1px solid var(--line); border-radius: .6rem; } +.studio-testimonials .studio-attribution { font-size: .88rem; color: var(--muted); } +.rich .studio-timeline { padding-inline-start: 1.4rem; border-inline-start: 1px solid var(--line); } +.studio-timeline li + li, .studio-checklist li + li { margin-top: .7rem; } +.studio-timeline li::marker, .studio-checklist li::marker { color: var(--accent); font-weight: 700; } +.studio-timeline h3 { font-size: 1.15rem; margin-bottom: .2rem; } +.rich .studio-resources { list-style: none; padding: 0; border-block-start: 1px solid var(--line); } +.studio-resources li { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: .35rem 1rem; padding: .7rem 0; border-block-end: 1px solid var(--line); } +.studio-resources span { font-size: .875rem; color: var(--muted); } +.studio-divider { width: 100%; margin-block: 1.25rem; border: 0; border-block-start: 1px solid var(--line); } +.studio-code { max-width: 100%; overflow: auto; padding: .8rem 1rem; border: 1px solid var(--line); border-radius: .5rem; background: var(--paper); } +@media (max-width: 36rem) { + .studio-gallery { grid-template-columns: 1fr; } + .studio-metrics { gap: .45rem; } + .studio-metrics div { padding: .55rem .3rem; } +} + +.studio-align-left { + --studio-margin-left: 0; --studio-margin-right: auto; --studio-justify: start; + text-align: left; justify-self: start; +} +.studio-align-center { + --studio-margin-left: auto; --studio-margin-right: auto; --studio-justify: center; + text-align: center; justify-self: center; +} +.studio-align-right { + --studio-margin-left: auto; --studio-margin-right: 0; --studio-justify: end; + text-align: right; justify-self: end; +} +:is(.hero-lead, .section-heading > p, .rich > p)[class*="studio-align-"] { + margin-left: var(--studio-margin-left); + margin-right: var(--studio-margin-right); +} +.rich > p:is(.studio-align-left, .studio-align-center, .studio-align-right) { max-width: 47rem; } +:is(.rich, .editor-preview) :is(img, video, audio, a, ol, ul)[class*="studio-align-"] { + margin-left: var(--studio-margin-left); + margin-right: var(--studio-margin-right); +} +:is(.rich, .editor-preview) :is(img, video, audio)[class*="studio-align-"] { display: block; max-width: 100%; } +:is(.rich, .editor-preview) a[class*="studio-align-"] { display: flex; width: fit-content; max-width: 100%; } +:is(.rich, .editor-preview) :is(ol, ul)[class*="studio-align-"] { width: fit-content; max-width: 100%; } +.rich > img[class*="studio-align-"]:not([class*="studio-media-"]) { max-width: min(100%, 46rem); } +.rich table[class*="studio-align-"] :is(th, td) { text-align: inherit; } +.hero-visual[class*="studio-align-"] { justify-self: var(--studio-justify); } +.hero-actions[class*="studio-align-"] { justify-content: var(--studio-justify); } diff --git a/public/assets/studio.js b/public/assets/studio.js index f5dbd96..6477245 100644 --- a/public/assets/studio.js +++ b/public/assets/studio.js @@ -265,7 +265,11 @@ jQuery(function ($) { const $settings = $layout.find('.studio-inspector'); const $sizing = $studio.find('[data-media-sizing]'); const $elementTools = $studio.find('[data-element-tools]'); + const $alignTools = $elementTools.find('[data-element-align]'); + const alignments = ['left', 'center', 'right']; + 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 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 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]'); @@ -328,7 +332,14 @@ jQuery(function ($) { function sectionChanges(withEdits = true) { return sections.flatMap(({key, version, fields, source, template}) => { const changes = {}; - for (const [field, {node, initial}] of Object.entries(fields)) { + const aligned = {}; + let alignmentChanged = false; + for (const [field, {node, initial, initialAlignment}] of Object.entries(fields)) { + if (field !== 'body') { + const value = getAlignment(node); + if (value) aligned[field] = value; + if (value !== initialAlignment) alignmentChanged = true; + } let value = field === 'body' ? node.innerHTML : node.textContent; if (field === 'body' && node.contains(selectedElement)) { const copy = node.cloneNode(true); @@ -339,7 +350,8 @@ jQuery(function ($) { changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value; } } - return Object.keys(changes).length ? [{key, version, fields: changes, ...(template ? {template} : {})}] : []; + if (!Object.keys(changes).length && !alignmentChanged) return []; + return [{key, version, fields: changes, ...(alignmentChanged ? {alignments: aligned} : {}), ...(template ? {template} : {})}]; }); } @@ -616,7 +628,7 @@ jQuery(function ($) { } else { configureText(node, label, part === 'lead'); } - fields[part] = {node, initial: body ? node.innerHTML : node.textContent}; + fields[part] = {node, initial: body ? node.innerHTML : node.textContent, initialAlignment: body ? '' : getAlignment(node)}; } const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from( atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0) @@ -662,11 +674,12 @@ jQuery(function ($) { const node = sizingTarget(); if (node) { const bounds = previewBounds(node); + const x = getAlignment(node) === 'right' ? bounds.left : bounds.right; const y = (bounds.top + bounds.bottom) / 2; const visible = bounds.width > 0 && y >= 0 && y <= container.clientHeight - && bounds.right > 0 && bounds.right <= container.clientWidth + 1; + && x >= 0 && x <= container.clientWidth + 1; $handle.prop('hidden', !mediaDrag && !visible); - $handle.css({left: Math.min(bounds.right, container.clientWidth - 11), top: y}); + $handle.css({left: Math.max(11, Math.min(x, container.clientWidth - 11)), top: y}); } else { $handle.prop('hidden', true); } @@ -706,6 +719,24 @@ jQuery(function ($) { return element !== body && body.contains(element) ? element : null; } + function getAlignment(node) { + return alignments.find((value) => node.classList.contains('studio-align-' + value)) || ''; + } + + function alignmentTarget(node) { + if (!node) return null; + const hero = node.closest('[data-studio-align-field]'); + if (hero) return hero; + return node.matches('[data-studio-part="title"], [data-studio-part="lead"]') || node.closest('[data-studio-part="body"]') + ? node : null; + } + + function syncAlignmentButtons(target) { + $alignTools.prop('hidden', !target).find('[data-align]').each(function () { + $(this).attr('aria-pressed', String(Boolean(target) && getAlignment(target) === this.dataset.align)); + }); + } + function selectElement(node) { selectionObserver?.disconnect(); selectedElement?.removeAttribute('data-studio-selected'); @@ -719,10 +750,13 @@ jQuery(function ($) { const inBody = node.closest('[data-studio-part="body"]') !== null; const canCopy = inBody || (nav && $(node).siblings().length < 19); const hasProperties = selectedMedia || node.matches('a'); + const aligned = alignmentTarget(node); + syncAlignmentButtons(aligned); $elementTools.find('[data-element-copy]').prop('hidden', !canCopy); + $elementTools.find('[data-element-delete]').prop('hidden', !inBody && !selectedMedia && !node.matches(heroOrOptional)); $elementTools.find('[data-element-properties]').prop('hidden', !hasProperties); if (target) showMediaWidth(currentMediaWidth(target)); - selectionObserver?.observe(target || node); + selectionObserver?.observe(target || aligned || node); } positionSelection(); } @@ -760,7 +794,22 @@ jQuery(function ($) { } } - $elementTools.on('click', '[data-element-copy]', () => changeElement(true)) + $elementTools.on('click', '[data-align]', function () { + const target = alignmentTarget(selectedElement); + const alignment = this.dataset.align; + if (!target || !alignments.includes(alignment)) return; + target.classList.remove(...alignmentClasses); + target.classList.add('studio-align-' + alignment); + const field = target.dataset.studioAlignField; + if (field) { + const $value = pageInput('alignments'); + const values = {...JSON.parse($value.val())}; + values[field] = alignment; + $value.val(JSON.stringify(values)); + } + syncAlignmentButtons(target); + positionSelection(); + }).on('click', '[data-element-copy]', () => changeElement(true)) .on('click', '[data-element-delete]', () => changeElement(false)) .on('click', '[data-element-properties]', () => { if (selectedMedia) replaceMedia(); @@ -790,9 +839,10 @@ jQuery(function ($) { const narrow = node.getBoundingClientRect(); if (classes === null) node.removeAttribute('class'); else node.setAttribute('class', classes); - const rightEdgeTravel = (full.right - narrow.right) / .9; - const available = rightEdgeTravel > full.width * .15 ? rightEdgeTravel : full.width; - return {available, initialWidth: width || Math.round(100 * natural / (full.width || natural || 1))}; + const fromLeft = getAlignment(node) === 'right'; + const edgeTravel = (fromLeft ? narrow.left - full.left : full.right - narrow.right) / .9; + const available = edgeTravel > full.width * .15 ? edgeTravel : full.width; + return {available, fromLeft, initialWidth: width || Math.round(100 * natural / (full.width || natural || 1))}; } function resizeMedia(width) { @@ -817,7 +867,8 @@ jQuery(function ($) { if (!mediaDrag || mediaDrag.id !== pointer.pointerId || !mediaDrag.available) return; if (pointer.clientX !== mediaDrag.x || mediaDrag.moved) { mediaDrag.moved = true; - resizeMedia(mediaDrag.initialWidth + 100 * (pointer.clientX - mediaDrag.x) / (mediaDrag.available * mediaDrag.scale)); + const distance = (pointer.clientX - mediaDrag.x) * (mediaDrag.fromLeft ? -1 : 1); + resizeMedia(mediaDrag.initialWidth + 100 * distance / (mediaDrag.available * mediaDrag.scale)); } }).on('lostpointercapture', () => { mediaDrag = null; @@ -836,7 +887,44 @@ jQuery(function ($) { $layout.on('click', '[data-hero-control]', function () { heroControls.get(this.dataset.heroControl)?.(); }); - $presets.on('mousedown', '[data-canvas-template]', (event) => event.preventDefault()); + function insertInBody(markup, body, range) { + if (!body.isConnected) return; + const insertion = doc.createRange(); + // Insert between blocks so the browser doesn't split a paragraph or duplicate its ID. + let node = range?.endContainer; + if (!node || !body.contains(node)) { + insertion.selectNodeContents(body); + insertion.collapse(false); + } else if (node === body) { + insertion.setStart(body, range.endOffset); + } else { + while (node.parentNode !== body) node = node.parentNode; + insertion.setStartAfter(node); + } + editBody(body, insertion, 'insertHTML', markup); + } + + $presets.on('mousedown', '[data-canvas-template], [data-canvas-element]', (event) => event.preventDefault()); + $presets.on('click', '[data-canvas-element]', function () { + const $status = $presets.find('[data-element-status]'); + const body = activeBody; + const range = savedRange?.cloneRange(); + if (!body) { + $status.text('请先在画布中选中要插入的正文。'); + return; + } + const add = (markup) => { + if (!markup) return; + insertInBody(markup, body, range); + selectElement(null); + $status.text('已插入' + $(this).text() + '。'); + }; + if (this.dataset.elementMime) { + openPicker(this.dataset.elementMime, (file) => add(mediaMarkup(file))); + } else { + add($presets.find('template[data-element="' + this.dataset.canvasElement + '"]').get(0).innerHTML); + } + }); $presets.on('click', '[data-canvas-template]', function () { const markup = $presets.find('template[data-preset="' + this.dataset.canvasTemplate + '"]').get(0).innerHTML; const template = this.dataset.canvasTemplate; @@ -849,10 +937,8 @@ jQuery(function ($) { $templateStatus.text('先在画布中选择要插入的区块正文。'); return; } - // Insert at the saved caret without replacing any selected text. - const insertion = savedRange?.cloneRange(); - insertion?.collapse(false); - editBody(activeBody, insertion, 'insertHTML', markup); + insertInBody(markup, activeBody, savedRange); + selectElement(null); $templateStatus.text('已插入当前正文。'); return; } @@ -920,8 +1006,8 @@ jQuery(function ($) { }); $doc.on('click.canvas', (event) => { const node = event.target; - const optional = node.closest?.(heroOrOptional); - selectElement(doc.getSelection()?.isCollapsed ? optional || editableBodyElement(node) : null); + const field = node.closest?.(canvasFields); + selectElement(doc.getSelection()?.isCollapsed ? field || editableBodyElement(node) : null); }); $doc.on('dblclick.canvas', '[data-studio-part="body"] a', function (event) { event.preventDefault(); @@ -950,7 +1036,7 @@ jQuery(function ($) { }); $toolbar.prop('hidden', false); $layout.find('[data-canvas-jump]').prop('hidden', false); - $layout.find('[data-canvas-template], [data-hero-control]').prop('disabled', false); + $layout.find('[data-canvas-template], [data-canvas-element], [data-hero-control]').prop('disabled', false); $presets.triggerHandler('studio:canvas-ready'); } diff --git a/public/assets/template-previews/checklist.webp b/public/assets/template-previews/checklist.webp new file mode 100644 index 0000000..41a66a2 Binary files /dev/null and b/public/assets/template-previews/checklist.webp differ diff --git a/public/assets/template-previews/gallery.webp b/public/assets/template-previews/gallery.webp new file mode 100644 index 0000000..0c649b4 Binary files /dev/null and b/public/assets/template-previews/gallery.webp differ diff --git a/public/assets/template-previews/metrics.webp b/public/assets/template-previews/metrics.webp new file mode 100644 index 0000000..6fd9e70 Binary files /dev/null and b/public/assets/template-previews/metrics.webp differ diff --git a/public/assets/template-previews/notice.webp b/public/assets/template-previews/notice.webp new file mode 100644 index 0000000..96c99cf Binary files /dev/null and b/public/assets/template-previews/notice.webp differ diff --git a/public/assets/template-previews/resources.webp b/public/assets/template-previews/resources.webp new file mode 100644 index 0000000..6bb55f7 Binary files /dev/null and b/public/assets/template-previews/resources.webp differ diff --git a/public/assets/template-previews/testimonials.webp b/public/assets/template-previews/testimonials.webp new file mode 100644 index 0000000..ec20ec3 Binary files /dev/null and b/public/assets/template-previews/testimonials.webp differ diff --git a/public/assets/template-previews/timeline.webp b/public/assets/template-previews/timeline.webp new file mode 100644 index 0000000..a8cbda3 Binary files /dev/null and b/public/assets/template-previews/timeline.webp differ diff --git a/public/assets/template-previews/video-demo.webp b/public/assets/template-previews/video-demo.webp new file mode 100644 index 0000000..e0e9787 Binary files /dev/null and b/public/assets/template-previews/video-demo.webp differ diff --git a/resources/schema.sql b/resources/schema.sql index eebca91..ff03c17 100644 --- a/resources/schema.sql +++ b/resources/schema.sql @@ -13,6 +13,7 @@ CREATE TABLE IF NOT EXISTS pages ( image TEXT NOT NULL, alt TEXT NOT NULL, image_scale INTEGER NOT NULL DEFAULT 0, + alignments TEXT NOT NULL DEFAULT '{}', actions TEXT NOT NULL, quicklinks TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('draft', 'published')), @@ -26,6 +27,7 @@ CREATE TABLE IF NOT EXISTS sections ( lead TEXT NOT NULL, style TEXT NOT NULL DEFAULT 'plain', feed TEXT, + alignments TEXT NOT NULL DEFAULT '{}', body TEXT NOT NULL, position INTEGER NOT NULL, version INTEGER NOT NULL DEFAULT 0, diff --git a/resources/seed.json b/resources/seed.json index 6360b6e..11d52fc 100644 --- a/resources/seed.json +++ b/resources/seed.json @@ -49,7 +49,7 @@ "title": "来笙动态", "lead": "", "style": "plain", - "body": "

    查看全部动态

    ", + "body": "", "feed": { "categories": [ "announcement", diff --git a/tests/studio-browser.cjs b/tests/studio-browser.cjs index 55f4ba0..f6afcf0 100644 --- a/tests/studio-browser.cjs +++ b/tests/studio-browser.cjs @@ -54,6 +54,8 @@ async function run(browser) { const frame = page.frameLocator('iframe[title="可编辑页面画布"]'); const sizing = page.locator('[data-media-sizing]'); const properties = page.locator('[data-canvas-properties]'); + const tools = page.getByRole('group', {name: '所选元素'}); + const align = (label) => tools.getByRole('button', {name: label, exact: true}).click(); const closeProperties = () => properties.locator('[data-property-close]').click(); const image = frame.locator('#fixtures img'); @@ -77,6 +79,18 @@ async function run(browser) { await properties.locator('[name=url]').fill('/assets/original/home-hero.webp'); await properties.locator('button[type=submit]').click(); assert.equal(await image.getAttribute('src'), '/assets/original/home-hero.webp'); + await image.click(); + await align('居右'); + const rightEdge = await image.boundingBox(); + const leftHandle = await handle.boundingBox(); + assert(Math.abs(rightEdge.x - (leftHandle.x + leftHandle.width / 2)) < 2); + await align('居中'); + const centeredImage = await image.evaluate((node) => { + const bounds = node.getBoundingClientRect(); + const parent = node.parentElement.getBoundingClientRect(); + return Math.abs((bounds.left + bounds.right) / 2 - (parent.left + parent.right) / 2) < 2; + }); + assert(centeredImage); const hero = frame.locator('[data-studio-hero-image]'); await page.locator('iframe[title="可编辑页面画布"]').evaluate((iframe) => iframe.contentWindow.scrollTo(0, 0)); @@ -88,8 +102,11 @@ async function run(browser) { await sizing.locator('[data-replace-media]').click(); assert.equal(await properties.locator('h2').textContent(), '首屏图片'); await closeProperties(); + const heroTitle = frame.locator('[data-studio-field=heading]'); + await heroTitle.click(); + await align('居右'); + assert.equal(await heroTitle.evaluate((node) => getComputedStyle(node.parentElement).textAlign), 'right'); - const tools = page.getByRole('group', {name: '所选元素'}); await frame.locator('#fixtures a').click(); await tools.getByRole('button', {name: '属性'}).click(); await properties.waitFor({state: 'visible'}); @@ -108,6 +125,11 @@ async function run(browser) { const copyText = frame.locator('#fixtures').getByText('待复制段落', {exact: true}); await copyText.click(); + await align('居中'); + await align('居左'); + assert.equal(await copyText.evaluate((node) => getComputedStyle(node).textAlign), 'left'); + await align('居右'); + assert.equal(await copyText.evaluate((node) => getComputedStyle(node).textAlign), 'right'); await tools.getByRole('button', {name: '复制'}).click(); assert.equal(await copyText.count(), 2); assert.equal(await frame.locator('#copy-fixture').count(), 1); @@ -119,9 +141,19 @@ async function run(browser) { await tools.getByRole('button', {name: '删除'}).click(); assert.equal(await page.locator('[name=lead]').inputValue(), ''); + const sectionTitle = frame.locator('#fixtures [data-studio-part=title]'); + await sectionTitle.click(); + await align('居中'); + assert.equal(await sectionTitle.evaluate((node) => getComputedStyle(node).textAlign), 'center'); + const gallery = page.locator('[data-canvas-presets]'); - assert.equal(await gallery.locator('[data-template-group]').count(), 6); - assert.equal(await gallery.locator('[data-template-card]').count(), 14); + await copyText.first().click(); + await gallery.getByText('基础元素', {exact: true}).click(); + await gallery.getByRole('button', {name: '插入分割线'}).click(); + await frame.locator('#fixtures .studio-divider').waitFor(); + await gallery.getByText('基础元素', {exact: true}).click(); + assert.equal(await gallery.locator('[data-template-group]').count(), 7); + assert.equal(await gallery.locator('[data-template-card]').count(), 22); const brokenPreviews = await gallery.locator('[data-template-card] img').evaluateAll(async (images) => { for (const image of images) image.loading = 'eager'; await Promise.all(images.map((image) => image.decode())); @@ -149,6 +181,9 @@ async function run(browser) { await gallery.locator('[data-template-empty]').waitFor({state: 'visible'}); await search.fill('双栏'); assert.equal(await gallery.locator('[data-template-card]:visible').count(), 1); + await search.fill('重点提示'); + await gallery.locator('[data-canvas-template=notice]').click(); + await frame.locator('.studio-notice').waitFor(); await search.fill('分类文章'); await gallery.locator('[data-canvas-template=articles]').click(); await frame.locator('section[id^=block-] h2').filter({hasText: '分类文章'}).waitFor(); @@ -161,7 +196,12 @@ async function run(browser) { await frame.locator('section[id^=block-] .studio-cover').waitFor(); assert.equal(await frame.locator('#fixtures a').getAttribute('href'), '/articles'); assert.equal(await frame.locator('#fixtures img').getAttribute('src'), '/assets/original/home-hero.webp'); - assert.equal(await frame.locator('#fixtures img').getAttribute('class'), imageSize); + assert.deepEqual((await image.getAttribute('class')).split(/\s+/).sort(), [imageSize, 'studio-align-center'].sort()); + assert.equal(await heroTitle.evaluate((node) => getComputedStyle(node.parentElement).textAlign), 'right'); + assert.equal(await sectionTitle.evaluate((node) => getComputedStyle(node).textAlign), 'center'); + assert.deepEqual(await copyText.evaluateAll((nodes) => nodes.map((node) => getComputedStyle(node).textAlign)), ['right', 'right']); + await frame.locator('.studio-notice').waitFor(); + await frame.locator('#fixtures .studio-divider').waitFor(); assert.match(await frame.locator('[data-visual]').getAttribute('class'), /studio-media-99/); assert.equal(await copyText.count(), 2); assert.equal(await frame.locator('#copy-fixture').count(), 1); @@ -190,7 +230,7 @@ async function run(browser) { } async function verifyArticleLibrary(browser, context, page, post, slug, feedId) { - const category = slug + '-category'; + const category = String(Date.now()); await post('/admin/article-categories', {slug: category, name: '自定义测试分类'}); const articleSlug = slug + '-article'; await page.goto('/admin/articles/new'); @@ -202,6 +242,7 @@ async function verifyArticleLibrary(browser, context, page, post, slug, feedId) await page.locator('[name=title]').fill('测试 Markdown 和富文本'); await page.locator('[name=slug]').fill(articleSlug); await page.locator('[name="categories[]"][value="' + category + '"]').check(); + await page.locator('[name="categories[]"][value=product]').check(); await page.locator('[name=status]').selectOption('published'); await markdown.fill('**Markdown 分屏**'); await preview.locator('strong').getByText('Markdown 分屏').waitFor(); @@ -211,7 +252,7 @@ async function verifyArticleLibrary(browser, context, page, post, slug, feedId) const publishedPath = '/articles/' + articleSlug; const sourcePage = await context.newPage(); await sourcePage.goto(publishedPath); - assert.equal(await sourcePage.locator('[itemprop=articleSection]').count(), 2); + assert.equal(await sourcePage.locator('[itemprop=articleSection]').count(), 3); await sourcePage.locator('[itemprop=articleBody] strong').getByText('Markdown 分屏').waitFor(); await page.goto(articleAdmin); await editor.locator('.toastui-editor-mode-switch').getByText('所见即所得', {exact: true}).click(); @@ -241,6 +282,7 @@ async function verifyArticleLibrary(browser, context, page, post, slug, feedId) await page.locator('[name="feed_categories[]"][value="' + category + '"]').check(); await page.getByRole('button', {name: '保存区块'}).click(); await page.locator('[data-save-confirmation]').waitFor({state: 'visible'}); + assert(await page.locator('[name="feed_categories[]"][value="' + category + '"]').isChecked()); let contentVersion = await page.locator('[name=version]').inputValue(); assert.equal(contentVersion, '1'); const canvasPath = '/admin/pages/' + slug + '/preview'; @@ -268,6 +310,7 @@ async function verifyArticleLibrary(browser, context, page, post, slug, feedId) assert.equal(await noJSPage.locator('#' + feedId + ' a[href="' + publishedPath + '"]:visible').count(), 2); await noJS.close(); assert((await context.request.get('/articles/category/' + category)).ok()); + await verifyScopedArchive(context, page, sourcePage, post, slug, feedId, category, publishedPath); await sourcePage.goto('/services'); await sourcePage.locator('.catalog-card').first().waitFor(); await sourcePage.goto('/network'); @@ -275,11 +318,61 @@ async function verifyArticleLibrary(browser, context, page, post, slug, feedId) await sourcePage.close(); } +async function verifyScopedArchive(context, admin, page, post, slug, feedId, category, articlePath) { + const scope = '/articles/feed/' + slug + '/' + feedId; + const scopedResponse = (query = '') => context.request.get(scope + query); + assert.equal((await scopedResponse()).status(), 404); + await admin.goto('/admin/pages/' + slug); + await admin.locator('[name=description]').fill('公开文章区块筛选测试。'); + await admin.locator('[name=status]').selectOption('published'); + await admin.getByRole('button', {name: '保存页面', exact: true}).first().click(); + await admin.locator('[data-save-confirmation]').waitFor({state: 'visible'}); + + const excluded = await post('/admin/articles/new', { + title: '分类范围外测试文章', slug: slug + '-excluded', body_format: 'markdown', + body: '只属于公告分类。', status: 'published', 'categories[]': 'announcement', + }); + assert(excluded.redirect); + await page.goto('/' + slug); + const archiveLink = page.locator('#' + feedId).getByRole('link', {name: '查看全部动态'}); + assert.equal(await archiveLink.getAttribute('href'), scope); + await archiveLink.click(); + await page.waitForURL('**' + scope); + const list = page.locator('main .article-list'); + assert.equal(await list.locator('a[href="' + articlePath + '"]').count(), 1); + assert.equal(await list.locator('a[href="/articles/' + slug + '-excluded"]').count(), 0); + assert.doesNotMatch(await list.locator('a[href="' + articlePath + '"] .article-category').textContent(), /产品/); + const filters = page.getByRole('navigation', {name: '动态分类'}); + assert.deepEqual(await filters.getByRole('link').allTextContents(), ['全部', '新闻', '自定义测试分类']); + assert.equal((await scopedResponse('?category=announcement')).status(), 404); + assert.equal((await scopedResponse('?category[]=news')).status(), 404); + assert.equal((await scopedResponse('?categories=announcement')).status(), 200); + assert.doesNotMatch(await (await scopedResponse('?categories=announcement')).text(), /分类范围外测试文章/); + + for (let index = 0; index < 21; index++) { + await post('/admin/articles/new', { + title: '分类分页样例 ' + index, slug: slug + '-sample-' + index, body_format: 'markdown', + body: '所选分类中的分页样例。', status: 'published', 'categories[]': category, + }); + } + const categoryPath = scope + '?category=' + category; + await filters.getByRole('link', {name: '自定义测试分类'}).click(); + await page.waitForURL('**' + categoryPath); + const next = page.getByRole('link', {name: '下一页'}); + assert.equal(await next.getAttribute('href'), categoryPath + '&page=2'); + await next.click(); + await page.waitForURL('**' + categoryPath + '&page=2'); + assert.equal(await list.locator('a').count(), 2); + assert.equal(await page.getByRole('link', {name: '上一页'}).getAttribute('href'), categoryPath); + assert.equal(await filters.getByRole('link', {name: '全部'}).getAttribute('href'), scope); + assert.equal(await page.getByRole('link', {name: '返回原页面'}).getAttribute('href'), '/' + slug + '#' + feedId); +} + (async () => { const browser = await chromium.launch({executablePath: process.env.CHROMIUM_EXECUTABLE || undefined}); try { await run(browser); - console.log('Passed Chromium canvas media/link interactions, template gallery, persistence, and the article library.'); + console.log('Passed Chromium canvas alignment, editor elements and modules, persistence, and scoped article archives.'); } finally { await browser.close(); }