Compare commits

..
Author SHA1 Message Date
ChatGPT abccb8c004 Restore the original Laysense footer 2026-11-21 23:49:21 +08:00
DeepSeek 2ef38bd716 Merge pull request #8: 修复 /network 指向空白文章的死链,统一目录兜底规则
目录卡片:有网址用网址,无网址且有内容才回退文章页,否则不渲染链接。21 项断言 + 三套端到端回归通过。
2026-11-21 23:26:34 +08:00
DeepSeek 62c10b09bc Skip links to empty directory articles 2026-11-21 23:26:15 +08:00
DeepSeek 935bc7f071 Skip links to empty directory articles 2026-11-21 23:26:14 +08:00
DeepSeek 1a025353b2 Merge pull request #7: 修复产品目录卡片标题指向文章页
标题与主按钮统一使用卡片配置的网址,未配置时回退文章页。21 项链接断言通过。
2026-11-21 23:23:56 +08:00
DeepSeek ef1ff93904 Point product cards at their configured URL
The services directory built each card title from the backing article, so
/services linked to /articles/service-1..4 instead of the product pages the
card already carries (PAGEPAN, HighSpeaker, /sc, /shnu-sc). Only the primary
button used card.url, which made the title and the button disagree.

Use the card URL for both, keeping the article page as fallback for entries
without a configured URL, and add a dependency-free regression test.
2026-11-21 23:23:23 +08:00
DeepSeek 74e0de84a6 Merge pull request #6: 限制文章区块归档范围,扩展编辑组件与对齐工具
审计通过(405 项断言 + 浏览器实测对齐链路),合并。合并后需对现有 LAYSENSE_DB 运行 php bin/install.php 补 alignments 列并重启 Webman。
2026-11-21 23:16:53 +08:00
ChatGPT 9bc0ee0e45 Scope article feeds and expand canvas editing 2026-11-21 22:55:59 +08:00
DeepSeek a2fc628f08 Merge pull request #5: 画布元素工具条、媒体拖拽和多分类文章
审计通过(47 项专项断言 + 浏览器交互验证 + 旧库拒绝安装验证),合并。破坏式更新按新库部署。
2026-11-21 22:36:28 +08:00
ChatGPT a5b3408358 Add canvas element tools and categorized article editing 2026-11-21 22:24:58 +08:00
DeepSeek 6efcdefadf Merge pull request #4: 按分类预览区块模板,修复画布媒体和链接交互
审计通过(297 项断言 + 真实浏览器交互验证),合并。替代 #3。
2026-11-21 21:17:46 +08:00
ChatGPT d4548393d5 Add categorized template previews and fix canvas event delegation 2026-11-21 21:10:50 +08:00
ChatGPT e7c7a8928e Build a full-width CMS canvas and restore featured home products 2026-11-21 21:33:15 +09:00
DeepSeek 00d7d6f9ad Merge pull request #2: 扩展 CMS 页面画布的所见即所得编辑
审计通过(244 项断言 + 真实浏览器交互验证),合并。
2026-11-21 20:16:13 +08:00
ChatGPT faba214971 Enable in-place editing for page sections and media 2026-11-21 21:06:34 +09:00
enoch a910f03929 Merge pull request '可视化 CMS、媒体库、产品目录与软著页面优化' (#1) from ChatGPT/laysense.cn:cms-visual-editor into main
Reviewed-on: laysense/laysense.cn#1
Reviewed-by: DeepSeek鲸鱼娘 <deepseek@laysense.com>
2026-11-21 19:57:54 +08:00
ChatGPT 173ad30726 Preserve HTML during CDN rewrites and refine SHNU benefits layout 2026-11-21 20:53:45 +09:00
ChatGPT 474008b06e Add visual CMS, media library and product directory 2026-11-21 19:27:46 +08:00
88 changed files with 4866 additions and 423 deletions
+35 -7
View File
@@ -4,7 +4,7 @@ PHP Webman、原生 CSS 和 SQLite 实现的来笙官网。公开页面由服务
## 本地启动
需要 Linux、PHP 8.2+ CLI、Composer 2,以及启用 `pcntl`、`posix`、`pdo_sqlite`、`dom` 和 `mbstring` 的 PHP 环境。
需要 Linux、PHP 8.2+ CLI、Composer 2,以及启用 `pcntl`、`posix`、`pdo_sqlite`、`dom`、`fileinfo` 和 `mbstring` 的 PHP 环境。
```sh
composer install
@@ -27,8 +27,13 @@ php bin/admin.php reset admin@example.com
## 后台编辑
- **页面**可修改首屏标题、简介、图片、按钮,以及每页的 SEO 标题和描述。页面正文按区块编辑,支持受限 HTML 和预览。
- **文章与动态**使用 Markdown,支持正文预览、摘要、标签和公告、新闻、产品分类。状态选「草稿」可撤回公开文章。已发布文章改网址标识后,旧标识会自动跳转。
- **页面设计**支持新建草稿、发布和撤回。首屏标题与简介可在桌面或手机画布中直接编辑。区块支持新增、排序、删除、可视化编辑、媒体插入和 HTML 源码。单击画布元素可用浮动工具条复制或删除。选中媒体后,可拖动边缘手柄调整宽度。浮动工具条可将正文元素、区块标题和首屏元素对齐到左侧、中央或右侧。编辑器左侧可插入基础元素,或按分类和名称查找区块模板。悬停或键盘聚焦缩略图可放大,点击可打开预览。
- **媒体库**集中列出项目静态文件及上传文件,支持查找、选取、复制路径、改名和归档。归档资源的已有 URL 保持可访问。上传文件放在 `LAYSENSE_MEDIA_DIR`,由 `/assets/uploads/` 提供。
- **文章**使用自托管的 TOAST UI Editor 3.2.2(MIT)。Markdown 左侧源码、右侧实时预览,富文本使用所见即所得模式。文章可以加入多个分类,可在「管理分类」创建新分类。
- **分类文章**支持在任意页面添加,保存区块后在「图层」中编辑分类、展示数量和合并或标签页模式。「查看全部动态」和翻页只列出该区块所选的分类。
- **产品与服务**(`/services`)和**支持项目与合作伙伴**(`/network`)由文章分类生成。通过文章的目录卡片设置图片、链接和排序,使用草稿状态可从目录撤下。
- **网站设置**分别编辑页头标志、导航及按钮,和页脚的公司信息、产品、公司及资源链接和备注。页脚设置可恢复原站内容。CDN 设置接受 HTTPS 源站地址。浏览器看到的公开 `/assets/…` 路径使用该源站。
- 文章支持摘要和标签。状态选「草稿」可撤回公开文章。已发布文章改网址标识后,旧标识会自动跳转。
- 首页动态、分类列表和站点地图随发布状态更新。源代码和 SQLite 数据分开管理。安装命令可重复执行,已编辑的内容会保留。
## 生产运行
@@ -40,13 +45,19 @@ php bin/admin.php reset admin@example.com
下面的 Nginx 片段可放入现有 HTTPS 虚拟主机。Nginx 会覆盖请求携带的 `X-Real-IP`,应用默认信任本机回环地址传来的该请求头。密码验证失败的请求按来源计数,超过阈值后返回 429。正确密码仍可登录。
```nginx
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
location / {
proxy_pass http://127.0.0.1:8787;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
client_max_body_size 2m;
}
location = /admin/media {
proxy_pass http://127.0.0.1:8787;
client_max_body_size 66m;
}
```
| 环境变量 | 默认值与用途 |
@@ -55,10 +66,15 @@ location / {
| `LAYSENSE_LISTEN` | `http://127.0.0.1:8787` · Webman 监听地址 |
| `LAYSENSE_WORKERS` | `2` · Webman worker 数量 |
| `LAYSENSE_DB` | `storage/laysense.sqlite` · SQLite 文件路径。生产可指向独立的持久化目录 |
| `LAYSENSE_MEDIA_DIR` | `storage/media` · 上传资源的持久化目录 |
| `LAYSENSE_SECURE_COOKIES` | 默认关闭 · 本地 HTTP 使用默认值。生产 HTTPS 设置为 `1`。 |
| `LAYSENSE_TRUSTED_PROXIES` | 默认 `127.0.0.1,::1` · 逗号分隔的受信反代 IP,设为空字符串可关闭信任 |
SQLite 已启用 WAL。迁移服务器或做线上备份时,可用 `sqlite3 storage/laysense.sqlite ".backup 'laysense-backup.sqlite'"` 取得一致备份。更新代码时保留数据库文件及其存放目录,以同一 `LAYSENSE_DB` 执行 `php bin/install.php` 应用迁移,然后重启服务。已有数据库会补回 PAGEPAN 原始功能图标,保留已编辑的文案和已有图像。服务用户需要对 SQLite 目录和 `runtime/` 有写权限。
SQLite 已启用 WAL。使用上一版多分类文章结构的站点,可用当前 `LAYSENSE_DB` 运行 `php bin/install.php` 增加对齐字段,之后重启 Webman。全新安装时,将 `LAYSENSE_DB` 指向新文件并按上面的步骤初始化和创建管理员。安装会预载网站自带页面、文章、产品和伙伴目录。服务用户需要对 SQLite 目录、媒体目录和 `runtime/` 有写权限。备份可用 `sqlite3 storage/laysense.sqlite ".backup 'laysense-backup.sqlite'"`,媒体目录单独保存。
### CDN
先让 CDN 的 `/assets/` 转发到 Webman 站点,再在「网站设置 → CDN」填写地址。CDN 需要保留静态资源的 CORS 响应头和视频 Range 请求。配置留空时,公开资源由站点直接提供。后台登录和编辑资源始终由站点提供。
## 迁移范围
@@ -67,3 +83,15 @@ SQLite 已启用 WAL。迁移服务器或做线上备份时,可用 `sqlite3 st
- 旧站 2024 年 11 月 10 日关于减少全球服务器部署的公告返回空白正文。迁移保留标题、日期、标签和旧链接,正文补录前会标记为不索引。
- SHNU 旧页首屏写 ¥69,详细报价表与正文写 ¥66。新版保留报价表中的 ¥66,并保留旧页学生资格及学分说明。两处普通软著页面的咨询按钮现在直达该页既有的企业微信入口。
- 中文公开页复用页头、页尾、首屏、内容区块、动态列表及同一套 CSS。历史迁移内容见 `resources/seed.json`,结构见 `resources/schema.sql`。
## 画布浏览器回归
`tests/studio-browser.cjs` 用 Playwright 在真实 Chromium 内检查媒体拖拽、链接、模板预览、编辑器、文章分类和公开页面。使用已启动的测试实例、独立的 SQLite 数据库和管理员账户。测试会在该库创建页面、分类和测试文章。
```sh
LAYSENSE_TEST_URL=http://127.0.0.1:8787 \
LAYSENSE_TEST_EMAIL=studio-test@example.com \
node tests/studio-browser.cjs
```
先安装 Playwright 和 Chromium,并在测试进程的环境里设置 `LAYSENSE_TEST_PASSWORD`。已安装在独立目录的 Playwright 可通过 `PLAYWRIGHT_MODULE` 指定模块路径。系统 Chromium 可通过 `CHROMIUM_EXECUTABLE` 指定。
+63
View File
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace App\Content;
use RuntimeException;
final class Assets
{
public static function cdn(string $value): string
{
$value = rtrim(trim($value), '/');
if ($value !== '' && (strlen($value) > 263 || !preg_match('~^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?::[0-9]{1,5})?$~iD', $value))) {
throw new RuntimeException('请填写 HTTPS CDN 源站地址,例如 https://cdn.laysense.cn。');
}
if (($port = parse_url($value, PHP_URL_PORT)) !== null && ($port === false || $port < 1)) {
throw new RuntimeException('CDN 端口无效。');
}
return $value;
}
public static function url(string $path, string $cdn): string
{
return str_starts_with($path, '/assets/') ? $cdn . $path : $path;
}
public static function rewrite(string $html, string $cdn): string
{
if ($cdn === '') {
return $html;
}
// Match opening tags separately from comments and text-only elements' contents.
$tags = <<<'REGEX'
~<!--.*?(?:-->|\z)|(?<opening><(?:(?<textTag>script|style|textarea|title)|[a-z][\w:-]*)(?=[\s/>])(?:[^<>"']++|"[^"]*"|'[^']*')*+>)(?(textTag)(?<tail>.*?(?:</\k<textTag>\s*>|\z)))~is
REGEX;
$attributes = <<<'REGEX'
~(\s+)([^\s/<>="']+)(?:(\s*=\s*)("[^"]*"|'[^']*'|[^\s<>"'=`]+))?~
REGEX;
return preg_replace_callback($tags, static function (array $tag) use ($attributes, $cdn): string {
if (!isset($tag['opening'])) {
return $tag[0];
}
$opening = preg_replace_callback($attributes, static function (array $attribute) use ($cdn): string {
if (!isset($attribute[4]) || !in_array(strtolower($attribute[2]), ['src', 'href', 'poster'], true)) {
return $attribute[0];
}
$value = $attribute[4];
$quote = str_starts_with($value, '"') || str_starts_with($value, "'") ? $value[0] : '';
$path = $quote === '' ? $value : substr($value, 1, -1);
return $attribute[1] . $attribute[2] . $attribute[3] . $quote . self::url($path, $cdn) . $quote;
}, $tag['opening']) ?? $tag['opening'];
return $opening . ($tag['tail'] ?? '');
}, $html) ?? $html;
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace App\Content;
final class BlockTemplates
{
public const ARTICLE_FEED = '{"categories":["announcement","news","product"],"mode":"merged","limit":6}';
public const ELEMENTS = [
'paragraph' => ['段落', '<p>填写正文。</p>'],
'subheading' => ['小标题', '<h3>填写小标题</h3>'],
'bullet-list' => ['项目列表', '<ul><li>填写列表项</li><li>填写列表项</li></ul>'],
'button' => ['按钮', '<p><a class="button button-primary" href="#contact">联系来笙</a></p>'],
'separator' => ['分割线', '<hr class="studio-divider">'],
'code' => ['代码块', '<pre class="studio-code"><code>填写代码</code></pre>'],
'image' => ['图片', '', 'image/'],
'video' => ['视频', '', 'video/'],
'audio' => ['音频', '', 'audio/'],
];
public const GROUPS = [
'content' => ['标题与正文', [
'headline' => ['标题与简介', '<div class="studio-intro"><h3>填写区块标题</h3><p>用一句话补充背景或说明。</p></div>'],
'text' => ['正文', '<p>在这里输入区块内容。</p>'],
'articles' => ['分类文章', ''],
'list' => ['步骤列表', '<ol><li>填写第一步</li><li>填写第二步</li><li>填写第三步</li></ol>'],
'notice' => ['重点提示', '<div class="studio-notice"><h3>填写重要提示</h3><p>说明访客需要知悉的事项、条件或时间。</p></div>'],
]],
'cover' => ['封面与横幅', [
'cover' => ['图文封面', '<div class="studio-cover"><img src="/assets/original/pagepan-example.webp" alt="" loading="lazy"><div><h3>用一句话介绍你的产品</h3><p>在首段说明访客能获得什么。</p><a class="button button-primary" href="/services">查看服务</a></div></div>'],
'banner' => ['横幅', '<div class="studio-banner"><h3>用一句话介绍你的项目</h3><p>简要说明项目能为访客做什么。</p><a class="button button-primary" href="/services">了解更多</a></div>'],
]],
'layout' => ['图文与布局', [
'image' => ['图文', '<div class="studio-split"><img src="/assets/original/home-hero.webp" alt="" loading="lazy"><div><h3>介绍主题</h3><p>在这里说明图片或产品。</p></div></div>'],
'grid' => ['双栏网格', '<div class="studio-two-column"><article class="content-card"><h3>第一栏</h3><p>填写主要内容。</p></article><article class="content-card"><h3>第二栏</h3><p>补充相关信息。</p></article></div>'],
]],
'media' => ['媒体', [
'gallery' => ['三图画廊', '<div class="studio-gallery"><img src="/assets/original/pagepan-editor-optimized.webp" alt="PAGEPAN 编辑器" loading="lazy"><img src="/assets/original/highspeaker-ui-optimized.webp" alt="HighSpeaker DNS 管理界面" loading="lazy"><img src="/assets/original/home-hero.webp" alt="云端服务插画" loading="lazy"></div>'],
'video-demo' => ['视频演示', '<div class="studio-split"><video controls preload="none" poster="/assets/original/pagepan-editor-optimized.webp" src="/assets/original/drag-in-components.mp4"></video><div><h3>演示视频</h3><p>说明视频涵盖的功能与操作。</p></div></div>'],
]],
'features' => ['特性与口碑', [
'features' => ['特性卡片', '<div class="card-grid feature-grid"><article class="content-card feature-card"><h3>特点一</h3><p>介绍这个特点。</p></article><article class="content-card feature-card"><h3>特点二</h3><p>介绍这个特点。</p></article><article class="content-card feature-card"><h3>特点三</h3><p>介绍这个特点。</p></article></div>'],
'quote' => ['引文', '<blockquote><p>在这里填写引用或用户反馈。</p></blockquote>'],
'metrics' => ['关键数据', '<dl class="studio-metrics"><div><dt>累计项目</dt><dd>100</dd></div><div><dt>服务覆盖</dt><dd>12</dd></div><div><dt>合作伙伴</dt><dd>8</dd></div></dl>'],
'testimonials' => ['用户评价', '<div class="studio-two-column studio-testimonials"><blockquote><p>填写用户的评价,并说明他们获得的结果。</p><p class="studio-attribution">用户姓名 · 公司或角色</p></blockquote><blockquote><p>填写另一条用户评价。</p><p class="studio-attribution">用户姓名 · 公司或角色</p></blockquote></div>'],
]],
'details' => ['表格与问答', [
'table' => ['对比表格', '<table><thead><tr><th scope="col">项目</th><th scope="col">说明</th></tr></thead><tbody><tr><td>项目一</td><td>填写说明</td></tr><tr><td>项目二</td><td>填写说明</td></tr></tbody></table>'],
'faq' => ['常见问题', '<div class="faq"><details><summary>请输入问题</summary><div><p>请输入答案。</p></div></details></div>'],
'timeline' => ['时间线', '<ol class="studio-timeline"><li><h3>确定目标</h3><p>填写这一阶段需要完成的事项。</p></li><li><h3>实施与验收</h3><p>填写交付时间与验收标准。</p></li></ol>'],
'checklist' => ['清单', '<ul class="studio-checklist"><li>填写必备材料</li><li>填写提交条件</li><li>填写确认事项</li></ul>'],
]],
'actions' => ['导航与引导', [
'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>'],
'resources' => ['资料与链接', '<ul class="studio-resources"><li><a href="/pagepan#download">获取 PAGEPAN</a><span>应用下载</span></li><li><a href="/articles">浏览动态与文档</a><span>网站资源</span></li></ul>'],
]],
];
public static function find(string $key): ?array
{
foreach (self::GROUPS as [, $templates]) {
if (isset($templates[$key])) {
return $templates[$key];
}
}
return null;
}
}
+37 -23
View File
@@ -39,20 +39,30 @@ final class Database
$pdo->exec('PRAGMA journal_mode = WAL');
self::write(function (PDO $pdo) use ($root, $seed): void {
$articleColumns = array_column($pdo->query('PRAGMA table_info(articles)')->fetchAll(), 'name');
if (in_array('category', $articleColumns, true)) {
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'])]);
$pageQuery = $pdo->prepare('INSERT OR IGNORE INTO pages
(slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks, partners)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
(slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$sectionQuery = $pdo->prepare('INSERT OR IGNORE INTO sections
(page_slug, key, title, lead, style, body, position) VALUES (?, ?, ?, ?, ?, ?, ?)');
(page_slug, key, title, lead, style, body, feed, position) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
foreach ($seed['pages'] as $page) {
$pageQuery->execute([
$page['slug'], $page['name'], $page['title'], $page['description'], $page['heading'],
$page['accent'], $page['lead'], $page['image'], $page['alt'],
self::json($page['actions']), self::json($page['quicklinks']), self::json($page['partners'] ?? []),
self::json($page['actions']), self::json($page['quicklinks']),
]);
if ($pageQuery->rowCount() !== 1) {
continue;
@@ -60,30 +70,34 @@ final class Database
foreach ($page['sections'] as $index => $section) {
$sectionQuery->execute([
$page['slug'], $section['key'], $section['title'], $section['lead'],
$section['style'], Html::sanitize($section['body']), $index,
$section['style'], Html::sanitize($section['body']), isset($section['feed']) ? self::json($section['feed']) : null, $index,
]);
}
}
$article = $pdo->prepare('INSERT OR IGNORE INTO articles
(slug, title, category, summary, body, tags, status, published_at, updated_at, legacy_path)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
foreach ($seed['articles'] as $item) {
$exists = $pdo->prepare('SELECT 1 FROM article_redirects WHERE slug = ?');
$exists->execute([$item['slug']]);
if ($exists->fetchColumn()) {
continue;
}
$article->execute([
$item['slug'], $item['title'], $item['category'], $item['summary'], $item['body'],
self::json($item['tags']), $item['status'], $item['date'], $item['date'], $item['legacy'],
]);
$category = $pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
foreach (Repository::CATEGORIES as $slug => $name) {
$category->execute([$slug, $name]);
}
$migration = $pdo->prepare('INSERT OR IGNORE INTO schema_migrations (name) VALUES (?)');
$migration->execute(['restore_pagepan_feature_icons']);
if ($migration->rowCount() === 1) {
PagepanFeatureIcons::migrate($pdo);
$article = $pdo->prepare("INSERT OR IGNORE INTO articles
(slug, title, summary, body, body_format, card, tags, status, published_at, updated_at, legacy_path)
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM article_redirects WHERE slug = ?)");
$link = $pdo->prepare('INSERT INTO article_category_links (article_id, category_slug) VALUES (?, ?)');
foreach ($seed['articles'] as $item) {
$format = $item['body_format'] ?? 'markdown';
$date = $item['date'] ?? null;
$article->execute([
$item['slug'], $item['title'], $item['summary'] ?? '',
$format === 'html' ? Html::sanitize($item['body']) : $item['body'], $format,
self::json($item['card'] ?? []), self::json($item['tags'] ?? []),
$item['status'] ?? 'published', $date, $date ?? gmdate(DATE_ATOM), $item['legacy'] ?? null, $item['slug'],
]);
if ($article->rowCount() === 1) {
$id = $pdo->lastInsertId();
foreach ($item['categories'] as $slug) {
$link->execute([$id, $slug]);
}
}
}
});
}
+43 -4
View File
@@ -7,12 +7,15 @@ namespace App\Content;
use DOMDocument;
use DOMElement;
use DOMNode;
use League\CommonMark\CommonMarkConverter;
use League\CommonMark\GithubFlavoredMarkdownConverter;
use RuntimeException;
final class Html
{
public const ALIGNMENTS = ['left', 'center', 'right'];
private const TAGS = [
'a' => ['href'], 'article' => [], 'b' => [], 'blockquote' => [], 'br' => [],
'a' => ['href'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [],
'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
'dl' => [], 'dt' => [], 'em' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [],
'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'],
@@ -20,7 +23,7 @@ final class Html
'small' => [], 'source' => ['src', 'type'], 'span' => [], 'strong' => [], 'summary' => [],
'table' => [], 'tbody' => [], 'td' => ['colspan', 'rowspan'], 'tfoot' => [],
'th' => ['scope', 'colspan', 'rowspan'], 'thead' => [], 'tr' => [], 'ul' => [],
'video' => ['controls', 'muted', 'playsinline', 'poster', 'preload'],
'video' => ['src', 'controls', 'muted', 'playsinline', 'poster', 'preload'],
];
public static function url(string $value, bool $media = false): bool
@@ -42,13 +45,49 @@ final class Html
public static function markdown(string $text): string
{
static $converter;
$converter ??= new CommonMarkConverter(['html_input' => 'strip', 'allow_unsafe_links' => false, 'max_nesting_level' => 30]);
$converter ??= new GithubFlavoredMarkdownConverter(['html_input' => 'strip', 'allow_unsafe_links' => false, 'max_nesting_level' => 30]);
$html = $converter->convert($text)->getContent();
return str_replace(['<h1>', '</h1>'], ['<h2>', '</h2>'], $html);
}
public static function articleBody(array $article): string
{
return $article['body_format'] === 'html' ? self::sanitize($article['body']) : self::markdown($article['body']);
}
public static function applyCanvasEdits(string $body, array $edits): string
{
if (!array_is_list($edits) || count($edits) > 512) {
throw new RuntimeException('正文增量无效。');
}
$size = strlen($body);
$cursor = 0;
$result = '';
foreach ($edits as $edit) {
if (!is_array($edit) || !array_is_list($edit) || count($edit) !== 3) {
throw new RuntimeException('正文增量无效。');
}
[$offset, $remove, $insert] = $edit;
if (!is_int($offset) || !is_int($remove) || !is_string($insert)
|| $offset < $cursor || $offset > $size || $remove < 0 || $remove > $size - $offset) {
throw new RuntimeException('正文增量无效。');
}
$result .= substr($body, $cursor, $offset - $cursor) . $insert;
$cursor = $offset + $remove;
if (strlen($result) > 300000) {
throw new RuntimeException('正文太长。');
}
}
$result .= substr($body, $cursor);
if (strlen($result) > 300000 || !mb_check_encoding($result, 'UTF-8')) {
throw new RuntimeException('正文太长或编码无效。');
}
return $result;
}
public static function sanitize(string $html): string
{
$document = new DOMDocument('1.0', 'UTF-8');
+135
View File
@@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMElement;
use DOMXPath;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RuntimeException;
use Throwable;
use Webman\Http\UploadFile;
final class Media
{
public const MAX_BYTES = 64 * 1024 * 1024;
private const EXTENSIONS = [
'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp',
'image/avif' => 'avif', 'image/x-icon' => 'ico', 'image/vnd.microsoft.icon' => 'ico', 'image/svg+xml' => 'svg',
'video/mp4' => 'mp4', 'video/webm' => 'webm', 'video/quicktime' => 'mov',
'audio/mpeg' => 'mp3', 'audio/ogg' => 'ogg', 'audio/wav' => 'wav',
'application/pdf' => 'pdf', 'font/woff' => 'woff', 'font/woff2' => 'woff2',
];
public static function all(bool $includeArchived = false): array
{
$query = 'SELECT name, label, mime, size, created_at, archived FROM media' . ($includeArchived ? '' : ' WHERE archived = 0');
$files = Database::connect()->query($query . ' ORDER BY created_at DESC, name')->fetchAll();
foreach ($files as &$file) {
$file['url'] = '/assets/uploads/' . $file['name'];
}
unset($file);
$root = dirname(__DIR__, 2) . '/public/assets';
$builtIn = [];
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root)) as $file) {
if (!$file->isFile() || $file->isLink() || str_starts_with($file->getFilename(), '.')) {
continue;
}
$path = str_replace(DIRECTORY_SEPARATOR, '/', substr($file->getPathname(), strlen($root) + 1));
$label = $file->getFilename();
$type = array_search(strtolower($file->getExtension()), self::EXTENSIONS, true) ?: 'application/octet-stream';
$builtIn[] = ['label' => $label, 'name' => '', 'mime' => $type, 'size' => $file->getSize(),
'url' => '/assets/' . $path, 'archived' => 0];
}
usort($builtIn, static fn (array $left, array $right): int => strnatcasecmp($left['url'], $right['url']));
return [...$files, ...$builtIn];
}
public static function upload(UploadFile $file, string $label): void
{
if (!$file->isValid() || ($size = $file->getSize()) < 1 || $size > self::MAX_BYTES) {
throw new RuntimeException('请选择大小不超过 64 MB 的有效文件。');
}
$source = $file->getPathname();
$mime = (new \finfo(FILEINFO_MIME_TYPE))->file($source);
$extension = self::EXTENSIONS[$mime] ?? null;
if ($extension === null) {
throw new RuntimeException('文件类型不受支持。');
}
$content = $mime === 'image/svg+xml' ? self::safeSvg($source, $size) : null;
$name = bin2hex(random_bytes(16)) . '.' . $extension;
$directory = self::directory();
if (!is_dir($directory) && !mkdir($directory, 0750, true) && !is_dir($directory)) {
throw new RuntimeException('资源目录无法创建。');
}
$path = $directory . '/' . $name;
try {
$written = $content === null ? copy($source, $path) : file_put_contents($path, $content) === strlen($content);
if (!$written) {
throw new RuntimeException('文件写入失败。');
}
$query = Database::connect()->prepare('INSERT INTO media (name, label, mime, size, created_at) VALUES (?, ?, ?, ?, ?)');
$query->execute([$name, $label, $mime, $content === null ? $size : strlen($content), gmdate('c')]);
} catch (Throwable $error) {
if (is_file($path)) {
unlink($path);
}
throw $error;
}
}
public static function find(string $name): ?array
{
$query = Database::connect()->prepare('SELECT * FROM media WHERE name = ?');
$query->execute([$name]);
return $query->fetch() ?: null;
}
public static function update(string $name, string $label, bool $archived): void
{
Database::connect()->prepare('UPDATE media SET label = ?, archived = ? WHERE name = ?')
->execute([$label, (int) $archived, $name]);
}
public static function directory(): string
{
return rtrim(getenv('LAYSENSE_MEDIA_DIR') ?: dirname(__DIR__, 2) . '/storage/media', '/');
}
private static function safeSvg(string $source, int $size): string
{
if ($size > 512 * 1024) {
throw new RuntimeException('SVG 图标最大支持 512 KB。');
}
$svg = new DOMDocument();
if (!$svg->loadXML(file_get_contents($source), LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) || $svg->doctype
|| $svg->documentElement?->namespaceURI !== 'http://www.w3.org/2000/svg' || $svg->documentElement->localName !== 'svg') {
throw new RuntimeException('SVG 图标格式无效。');
}
$tags = ['svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'title', 'desc'];
$attributes = ['viewBox', 'width', 'height', 'fill', 'fill-rule', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-linecap',
'stroke-linejoin', 'stroke-dasharray', 'stroke-opacity', 'curve', 'clip-rule', 'opacity', 'd', 'x', 'y',
'rx', 'ry', 'cx', 'cy', 'r', 'x1', 'x2', 'y1', 'y2', 'points', 'transform'];
foreach ((new DOMXPath($svg))->query('//*') as $element) {
if (!$element instanceof DOMElement || $element->namespaceURI !== 'http://www.w3.org/2000/svg'
|| !in_array($element->localName, $tags, true)) {
throw new RuntimeException('SVG 仅支持基础矢量元素。');
}
foreach ($element->attributes as $attribute) {
if ($attribute->namespaceURI !== null || !in_array($attribute->localName, $attributes, true)
|| !preg_match('/^[a-z0-9#.,%\s()+-]*$/iD', $attribute->value) || preg_match('/url\s*\(/i', $attribute->value)) {
throw new RuntimeException('SVG 包含不支持的属性或外部引用。');
}
}
}
return $svg->saveXML($svg->documentElement);
}
}
-55
View File
@@ -1,55 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMElement;
use DOMXPath;
use PDO;
final class PagepanFeatureIcons
{
public static function migrate(PDO $pdo): void
{
$query = $pdo->query("SELECT body FROM sections WHERE page_slug = 'pagepan' AND key = 'features'");
$body = $query->fetchColumn();
if (!is_string($body) || $body === '') {
return;
}
$paths = json_decode(file_get_contents(dirname(__DIR__, 2) . '/resources/pagepan-feature-icons.json'), true, flags: JSON_THROW_ON_ERROR);
$document = new DOMDocument('1.0', 'UTF-8');
$document->loadHTML('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' . $body . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
$xpath = new DOMXPath($document);
$changed = false;
foreach ($xpath->query('//article[contains(concat(" ", normalize-space(@class), " "), " feature-card ")]') as $card) {
$heading = $xpath->query('(./h2 | ./h3 | ./h4)[1]', $card)->item(0);
if (!$heading instanceof DOMElement || $card->getElementsByTagName('img')->length > 0) {
continue;
}
$title = trim($heading->textContent);
if (!isset($paths[$title])) {
continue;
}
$icon = $document->createElement('img');
foreach (['src' => $paths[$title], 'alt' => '', 'width' => '50', 'height' => '50', 'loading' => 'lazy'] as $key => $value) {
$icon->setAttribute($key, $value);
}
$card->insertBefore($icon, $card->firstChild);
$changed = true;
}
if ($changed) {
$updated = '';
foreach ($document->getElementsByTagName('body')->item(0)->childNodes as $child) {
$updated .= $document->saveHTML($child);
}
$pdo->prepare("UPDATE sections SET body = ?, version = version + 1 WHERE page_slug = 'pagepan' AND key = 'features'")
->execute([trim($updated)]);
$pdo->prepare("UPDATE pages SET updated_at = ? WHERE slug = 'pagepan'")
->execute([(new \DateTimeImmutable('now', new \DateTimeZone('Asia/Shanghai')))->format('Y-m-d H:i:s')]);
}
}
}
+174 -40
View File
@@ -9,7 +9,13 @@ use RuntimeException;
final class Repository
{
public const CATEGORIES = ['announcement' => '公告', 'news' => '新闻', 'product' => '产品'];
public const DIRECTORIES = [
'services' => '产品与服务', 'supported-projects' => '来笙支持项目', 'partners' => '来笙合作伙伴',
];
public const CATEGORIES = ['announcement' => '公告', 'news' => '新闻', 'product' => '产品'] + self::DIRECTORIES;
private const ARTICLE_FIELDS = 'articles.*, (SELECT json_group_object(c.slug, c.name)
FROM article_category_links l JOIN article_categories c ON c.slug = l.category_slug
WHERE l.article_id = articles.id) AS categories';
private PDO $pdo;
public function __construct()
@@ -22,9 +28,22 @@ final class Repository
return json_decode((string) $this->pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
}
public function pages(): array
public function pages(bool $publishedOnly = false): array
{
return $this->pdo->query('SELECT slug, name, title, updated_at FROM pages ORDER BY rowid')->fetchAll();
$where = $publishedOnly ? " WHERE status = 'published'" : '';
return $this->pdo->query('SELECT slug, name, title, updated_at, status FROM pages' . $where . ' ORDER BY rowid')->fetchAll();
}
public function createPage(string $slug, string $name): void
{
$query = $this->pdo->prepare("INSERT OR IGNORE INTO pages (slug, name, title, description, heading, accent,
lead, image, alt, actions, quicklinks, status, updated_at)
VALUES (?, ?, ?, '', ?, '', '', '', '', '[]', '[]', 'draft', ?)");
$query->execute([$slug, $name, $name . ' · 来笙', $name, self::now()]);
if ($query->rowCount() !== 1) {
throw new RuntimeException('此页面地址已存在。');
}
}
public function page(string $slug): ?array
@@ -33,7 +52,7 @@ final class Repository
if (!$page) {
return null;
}
foreach (['actions', 'quicklinks', 'partners'] 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');
@@ -48,46 +67,149 @@ final class Repository
return $this->one('SELECT * FROM sections WHERE page_slug = ? AND key = ?', [$page, $key]);
}
public function savePage(string $slug, array $data, int $version): void
public function publishedFeed(string $page, string $key): ?array
{
$query = $this->pdo->prepare('UPDATE pages SET title = ?, description = ?, heading = ?, accent = ?, lead = ?,
image = ?, alt = ?, actions = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?');
$query->execute([
$data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'],
$data['image'], $data['alt'], Database::json($data['actions']), self::now(), $slug, $version,
]);
self::checkVersion($query->rowCount());
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 = ?, 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['alignments']), Database::json($data['actions']), Database::json($data['quicklinks']),
$data['status'], self::now(), $slug, $version,
]);
self::checkVersion($query->rowCount());
foreach ($sections as $section) {
if ($section['version'] === null) {
self::insertSection($pdo, $slug, $section['key'], $section);
} else {
self::updateSection($pdo, $slug, $section['key'], $section, $section['version']);
}
}
});
}
public function saveSection(string $page, string $key, array $data, int $version): void
{
Database::write(function (PDO $pdo) use ($page, $key, $data, $version): void {
$query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, version = version + 1
WHERE page_slug = ? AND key = ? AND version = ?');
$query->execute([$data['title'], $data['lead'], $data['body'], $page, $key, $version]);
self::checkVersion($query->rowCount());
$query = $pdo->prepare('UPDATE pages SET updated_at = ? WHERE slug = ?');
$query->execute([self::now(), $page]);
self::updateSection($pdo, $page, $key, $data, $version);
self::touchPage($pdo, $page);
});
}
public function articles(?string $category = null, ?string $tag = null, bool $public = true, int $limit = 30, int $offset = 0): array
private static function updateSection(PDO $pdo, string $page, string $key, array $data, int $version): void
{
$sql = 'SELECT * FROM articles WHERE 1 = 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, $data['alignments'] ?? null, $page, $key, $version]);
self::checkVersion($query->rowCount());
}
public function createSection(string $page, string $key, string $title, string $style, string $body, ?string $feed = null): void
{
Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body, $feed): void {
self::insertSection($pdo, $page, $key, compact('title', 'style', 'body', 'feed') + ['lead' => '']);
self::touchPage($pdo, $page, structureChanged: true);
});
}
private static function insertSection(PDO $pdo, string $page, string $key, array $data): void
{
$query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, alignments, position)
SELECT ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?');
$query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $data['alignments'] ?? '{}', $page]);
if ($query->rowCount() !== 1) {
throw new RuntimeException('此区块锚点已被使用。');
}
}
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 {
$current = $pdo->prepare('SELECT version FROM pages WHERE slug = ?');
$current->execute([$page]);
$revision = $current->fetchColumn();
self::checkVersion($revision !== false && (int) $revision === $pageVersion ? 1 : 0);
if ($operation === 'delete') {
$query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?');
$query->execute([$page, $key, $version]);
self::checkVersion($query->rowCount());
self::touchPage($pdo, $page, structureChanged: true);
return;
}
$query = $pdo->prepare('SELECT key, version FROM sections WHERE page_slug = ? ORDER BY position, key');
$query->execute([$page]);
$revisions = $query->fetchAll(PDO::FETCH_KEY_PAIR);
if (!array_key_exists($key, $revisions)) {
throw new RuntimeException('找不到该区块。');
}
self::checkVersion((int) $revisions[$key] === $version ? 1 : 0);
$keys = array_map('strval', array_keys($revisions));
$index = array_search($key, $keys, true);
$other = $index + ($operation === 'up' ? -1 : 1);
if (!isset($keys[$other])) {
return;
}
[$keys[$index], $keys[$other]] = [$keys[$other], $keys[$index]];
$query = $pdo->prepare('UPDATE sections SET position = ? WHERE page_slug = ? AND key = ?');
foreach ($keys as $position => $section) {
$query->execute([$position, $page, $section]);
}
self::touchPage($pdo, $page, structureChanged: true);
});
}
private static function touchPage(PDO $pdo, string $slug, bool $structureChanged = false): void
{
$revision = $structureChanged ? ', version = version + 1' : '';
$pdo->prepare('UPDATE pages SET updated_at = ?' . $revision . ' WHERE slug = ?')->execute([self::now(), $slug]);
}
public function categories(): array
{
return $this->pdo->query('SELECT slug, name FROM article_categories ORDER BY rowid')->fetchAll(PDO::FETCH_KEY_PAIR);
}
public function createCategory(string $slug, string $name): void
{
$query = $this->pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
$query->execute([$slug, $name]);
if ($query->rowCount() !== 1) {
throw new RuntimeException('此分类网址标识已被使用。');
}
}
public function articles(string|array|null $category = null, ?string $tag = null, bool $public = true,
int $limit = 30, int $offset = 0, bool $directoryOrder = false): array
{
if ($category === []) {
return [];
}
$sql = 'SELECT ' . self::ARTICLE_FIELDS . ' FROM articles WHERE 1 = 1';
$args = [];
if ($public) {
$sql .= " AND status = 'published' AND published_at IS NOT NULL";
$sql .= " AND status = 'published'";
}
if ($category !== null) {
$sql .= ' AND category = ?';
$args[] = $category;
$args = (array) $category;
$marks = implode(', ', array_fill(0, count($args), '?'));
$sql .= " AND EXISTS (SELECT 1 FROM article_category_links
WHERE article_id = articles.id AND category_slug IN ($marks))";
}
if ($tag !== null) {
$sql .= ' AND EXISTS (SELECT 1 FROM json_each(articles.tags) WHERE value = ?)';
$args[] = $tag;
}
$order = $public ? 'published_at' : 'updated_at';
$query = $this->pdo->prepare($sql . ' ORDER BY ' . $order . ' DESC, id DESC LIMIT ? OFFSET ?');
$order = $directoryOrder ? "COALESCE(json_extract(card, '$.position'), 0), id" : "$order DESC, id DESC";
$query = $this->pdo->prepare($sql . ' ORDER BY ' . $order . ' LIMIT ? OFFSET ?');
$query->execute([...$args, $limit, $offset]);
return array_map(self::decodeArticle(...), $query->fetchAll());
@@ -95,12 +217,12 @@ final class Repository
public function articleById(int $id): ?array
{
return self::decodeArticle($this->one('SELECT * FROM articles WHERE id = ?', [$id]));
return self::decodeArticle($this->one('SELECT ' . self::ARTICLE_FIELDS . ' FROM articles WHERE id = ?', [$id]));
}
public function published(string $slug): ?array
{
return self::decodeArticle($this->one("SELECT * FROM articles WHERE slug = ? AND status = 'published'", [$slug]));
return self::decodeArticle($this->one('SELECT ' . self::ARTICLE_FIELDS . " FROM articles WHERE slug = ? AND status = 'published'", [$slug]));
}
public function articleRedirect(string $slug): ?array
@@ -127,26 +249,34 @@ final class Repository
if (($existing && $existing['id'] !== $id) || ($redirect && $redirect['article_id'] !== $id)) {
throw new RuntimeException('此网址标识已被使用。');
}
$publishedAt = $old['published_at'] ?? ($data['status'] === 'published' ? self::now() : null);
$publishedAt = $old['published_at'] ?? ($data['status'] === 'published' && ($old['status'] ?? '') !== 'published' ? self::now() : null);
$values = [
$data['slug'], $data['title'], $data['category'], $data['summary'], $data['body'],
$data['slug'], $data['title'], $data['summary'], $data['body'],
$data['body_format'], Database::json($data['card']),
Database::json($data['tags']), $data['status'], $publishedAt, self::now(),
];
if ($id === null) {
$query = $pdo->prepare('INSERT INTO articles
(slug, title, category, summary, body, tags, status, published_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
(slug, title, summary, body, body_format, card, tags, status, published_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$query->execute($values);
return (int) $pdo->lastInsertId();
$id = (int) $pdo->lastInsertId();
} else {
if ($old['slug'] !== $data['slug']) {
$pdo->prepare('DELETE FROM article_redirects WHERE slug = ? AND article_id = ?')->execute([$data['slug'], $id]);
$pdo->prepare('INSERT INTO article_redirects (slug, article_id) VALUES (?, ?)')->execute([$old['slug'], $id]);
}
$query = $pdo->prepare('UPDATE articles SET slug = ?, title = ?, summary = ?, body = ?,
body_format = ?, card = ?, tags = ?, status = ?, published_at = ?, updated_at = ?, version = version + 1
WHERE id = ? AND version = ?');
$query->execute([...$values, $id, $version]);
self::checkVersion($query->rowCount());
$pdo->prepare('DELETE FROM article_category_links WHERE article_id = ?')->execute([$id]);
}
if ($old['slug'] !== $data['slug']) {
$pdo->prepare('DELETE FROM article_redirects WHERE slug = ? AND article_id = ?')->execute([$data['slug'], $id]);
$pdo->prepare('INSERT INTO article_redirects (slug, article_id) VALUES (?, ?)')->execute([$old['slug'], $id]);
$link = $pdo->prepare('INSERT INTO article_category_links (article_id, category_slug) VALUES (?, ?)');
foreach ($data['categories'] as $category) {
$link->execute([$id, $category]);
}
$query = $pdo->prepare('UPDATE articles SET slug = ?, title = ?, category = ?, summary = ?, body = ?, tags = ?,
status = ?, published_at = ?, updated_at = ?, version = version + 1 WHERE id = ? AND version = ?');
$query->execute([...$values, $id, $version]);
self::checkVersion($query->rowCount());
return $id;
});
@@ -154,7 +284,9 @@ final class Repository
public function sitemapArticles(): iterable
{
$query = $this->pdo->query("SELECT slug, updated_at FROM articles WHERE status = 'published' AND trim(body) <> '' ORDER BY slug");
$query = $this->pdo->query("SELECT slug, updated_at FROM articles WHERE status = 'published'
AND (trim(body) <> '' OR trim(summary) <> '' OR json_extract(card, '$.image') <> '' OR json_extract(card, '$.url') <> '')
ORDER BY slug");
yield from $query;
}
@@ -209,7 +341,9 @@ final class Repository
private static function decodeArticle(?array $article): ?array
{
if ($article !== null) {
$article['tags'] = json_decode($article['tags'], true, flags: JSON_THROW_ON_ERROR);
foreach (['tags', 'categories', 'card'] as $field) {
$article[$field] = json_decode($article[$field], true, flags: JSON_THROW_ON_ERROR);
}
}
return $article;
+87
View File
@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use RuntimeException;
final class SiteDesign
{
public const DEFAULT_HEADER = [
'logo' => '/assets/wordmark.webp', 'alt' => 'Laysense 来笙',
'links' => [['/', '首页'], ['/services', '产品与服务'], ['/articles', '动态'], ['/#about', '关于来笙']],
'button' => ['#contact', '联系来笙'],
];
public const DEFAULT_FOOTER = [
'logo' => '/assets/original/footer-wordmark.webp', 'alt' => '来笙 Laysense',
'name' => '上海来笙信息科技有限公司',
'address' => '中国(上海)自由贸易试验区世博村路231号2单元3层328室',
'email' => 'public@laysense.cn',
'products_title' => '产品与服务',
'products' => [['/highspeaker', 'HighSpeaker DNS'], ['/pagepan', 'PAGEPAN'], ['/sc', '软著代理服务']],
'company_title' => '公司',
'company' => [['/#about', '关于来笙'], ['#contact', '联系来笙']],
'resources_title' => '资源',
'resources' => [['https://git.laysense.com', 'Laysense Git'], ['https://www.layso.de', 'LaySo']],
'phones' => [['tel:+16699004532', '+1 (669) 900 4532'], ['tel:+85257012856', '+852 5701 2856']],
'copyright' => '© Shanghai Laysense Information Technology Co. Ltd. 2024',
'terms' => '本网站中产品价格仅作展示,不作为订立合同、邀约或要约邀请的有效因素。',
'registration' => '沪ICP备2024051698号-1',
];
public static function footer(array $site): array
{
$saved = $site['footer'] ?? null;
if ($saved === null) {
return self::DEFAULT_FOOTER;
}
// Older configurations store the entire footer navigation in two columns.
if (!array_key_exists('resources', $saved)) {
$saved += ['resources' => [], 'resources_title' => ''];
if (!empty($saved['copyright'])) {
$saved['copyright'] .= ' 2024–' . date('Y');
}
}
return $saved + self::DEFAULT_FOOTER;
}
public static function parseLinks(string $value): array
{
$links = [];
foreach (preg_split('/\R/u', $value, -1, PREG_SPLIT_NO_EMPTY) as $line) {
if (trim($line) === '') {
continue;
}
[$label, $url] = array_map('trim', array_pad(explode('|', $line, 2), 2, ''));
if ($label === '' || mb_strlen($label) > 70 || strlen($url) > 1000 || !Html::url($url) || count($links) >= 20) {
throw new RuntimeException('每行填写「文案 | 链接」,最多 20 条。');
}
$links[] = [$url, $label];
}
return $links;
}
public static function linkText(array $links): string
{
return implode("\n", array_map(static fn (array $link): string => $link[1] . ' | ' . $link[0], $links));
}
public static function saveSettings(string $part, array $data, int $version): void
{
Database::write(function (PDO $pdo) use ($part, $data, $version): void {
$site = json_decode((string) $pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
if (($site['revisions'][$part] ?? 0) !== $version) {
throw new RuntimeException('设置已在另一页面更新。请复制本次修改后重新打开。');
}
$site[$part] = $data;
$site['revisions'][$part] = $version + 1;
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
});
}
}
+26 -5
View File
@@ -10,17 +10,24 @@ final class View
{
public static function render(string $template, array $data, int $status = 200, bool $admin = false): Response
{
$cdn = $admin || !empty($data['previewMode']) ? '' : ($data['site']['cdn']['origin'] ?? '');
$data['cdn'] = $cdn;
$html = self::fragment($template, $data);
$page = self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]);
$page = Assets::rewrite(self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]), $cdn);
$assetSources = $cdn === '' ? "'self'" : "'self' " . $cdn;
$articleEditor = $admin && !empty($data['articleEditor']);
$editorImages = $articleEditor ? ' data:' : '';
$editorStyles = $articleEditor ? "style-src-attr 'unsafe-inline'; " : '';
$headers = [
'Content-Type' => 'text/html; charset=utf-8',
'X-Content-Type-Options' => 'nosniff',
'Referrer-Policy' => 'strict-origin-when-cross-origin',
'X-Frame-Options' => 'DENY',
'Content-Security-Policy' => "default-src 'self'; img-src 'self' https:; media-src 'self' https:; "
. "style-src 'self'; script-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'; object-src 'none'",
'X-Frame-Options' => !empty($data['previewMode']) ? 'SAMEORIGIN' : 'DENY',
'Content-Security-Policy' => "default-src 'self'; img-src 'self' https:$editorImages; media-src 'self' https:; "
. "style-src $assetSources; {$editorStyles}script-src $assetSources; font-src $assetSources; frame-src 'self'; frame-ancestors "
. (!empty($data['previewMode']) ? "'self'" : "'none'") . "; form-action 'self'; base-uri 'none'; object-src 'none'",
];
if ($admin) {
if ($admin || !empty($data['previewMode'])) {
$headers['Cache-Control'] = 'no-store';
$headers['X-Robots-Tag'] = 'noindex, nofollow';
} elseif (($data['noindex'] ?? false) || $status >= 400) {
@@ -58,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'], '');
+208 -25
View File
@@ -4,16 +4,18 @@ declare(strict_types=1);
namespace App\Controller;
use App\Content\BlockTemplates;
use App\Content\Database;
use App\Content\Html;
use App\Content\Passwords;
use App\Content\Repository;
use App\Content\SiteDesign;
use App\Content\View;
use App\Http\Request;
use RuntimeException;
use support\Response;
final class AdminController
class AdminController
{
private ?array $user = null;
@@ -124,22 +126,58 @@ final class AdminController
return $failure;
}
$page = max(1, min(10000, (int) $request->get('page', 1)));
$articles = (new Repository())->articles(public: false, limit: 31, offset: ($page - 1) * 30);
$repo = new Repository();
$categories = $repo->categories();
$category = $request->get('category');
$category = is_string($category) && isset($categories[$category]) ? $category : null;
$articles = $repo->articles($category, public: false, limit: 31, offset: ($page - 1) * 30);
return $this->render($request, 'admin-articles', [
'title' => '文章与动态', 'articles' => array_slice($articles, 0, 30), 'pageNumber' => $page, 'hasNext' => count($articles) > 30,
'title' => '文章与动态', 'articles' => array_slice($articles, 0, 30), 'pageNumber' => $page,
'hasNext' => count($articles) > 30, 'categories' => $categories, 'category' => $category,
]);
}
public function articleCategories(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$repo = new Repository();
$name = $slug = $error = '';
if ($request->method() === 'POST') {
$slug = $this->input($request, 'slug');
$name = $this->input($request, 'name');
try {
if (!preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/D', $slug) || strlen($slug) > 60 || $name === '' || mb_strlen($name) > 60) {
throw new RuntimeException('请填写分类名称及网址标识。');
}
$repo->createCategory($slug, $name);
return $this->success($request, '/admin/article-categories?saved=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
}
}
return $this->render($request, 'admin-article-categories', [
'title' => '文章分类', 'categories' => $repo->categories(), 'name' => $name, 'slug' => $slug,
'error' => $error, 'saved' => $request->get('saved') === '1',
], $error === '' ? 200 : 422);
}
public function article(Request $request, ?string $id = null): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$repo = new Repository();
$categories = $repo->categories();
$preset = $request->get('category');
$preset = is_string($preset) && isset($categories[$preset]) ? $preset : 'news';
$article = $id !== null ? $repo->articleById((int) $id) : [
'title' => '', 'slug' => '', 'summary' => '', 'category' => 'news', 'body' => '',
'tags' => [], 'status' => 'draft', 'version' => 0,
'title' => '', 'slug' => '', 'summary' => '', 'body' => '', 'body_format' => 'markdown',
'categories' => [$preset => $categories[$preset]], 'card' => [], 'tags' => [], 'status' => 'draft', 'version' => 0,
];
if (!$article) {
return $this->error($request, '找不到这篇文章。', 404);
@@ -147,16 +185,26 @@ final class AdminController
$error = '';
if ($request->method() === 'POST') {
$data = $this->articleInput($request);
$article = array_replace($article, $data, ['version' => $this->version($request)]);
$article = array_replace($article, $data, [
'categories' => array_intersect_key($categories, array_flip($data['categories'])),
'version' => $this->version($request),
]);
try {
if (mb_strlen($data['title']) < 1 || mb_strlen($data['title']) > 120
|| !preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/D', $data['slug']) || strlen($data['slug']) > 100
|| mb_strlen($data['summary']) > 250 || strlen($data['body']) > 200000
|| !isset(Repository::CATEGORIES[$data['category']])
|| $data['categories'] === [] || array_diff($data['categories'], array_keys($categories))
|| !in_array($data['body_format'], ['markdown', 'html'], true)
|| !in_array($data['status'], ['draft', 'published'], true)) {
throw new RuntimeException('请检查标题、网址标识、分类、摘要和正文长度。');
}
if ($data['status'] === 'published' && trim(Html::markdown($data['body'])) === '') {
$this->checkArticleCard($data['card']);
if ($data['body_format'] === 'html') {
$data['body'] = Html::sanitize($data['body']);
}
if ($data['status'] === 'published' && trim(Html::articleBody($data)) === ''
&& (!array_intersect($data['categories'], array_keys(Repository::DIRECTORIES))
|| ($data['summary'] === '' && empty($data['card']['url']) && empty($data['card']['image'])))) {
throw new RuntimeException('发布前请填写文章正文。');
}
$saved = $repo->saveArticle($id === null ? null : (int) $id, $data, $this->version($request));
@@ -169,7 +217,7 @@ final class AdminController
return $this->render($request, 'admin-article', [
'title' => $id === null ? '新建文章' : '编辑文章', 'article' => $article, 'error' => $error,
'articleId' => $id, 'saved' => $request->get('saved') === '1',
'articleId' => $id, 'categories' => $categories, 'articleEditor' => true, 'saved' => $request->get('saved') === '1',
], $error !== '' ? 422 : 200);
}
@@ -189,6 +237,11 @@ final class AdminController
foreach (['title', 'description', 'heading', 'accent', 'lead', 'image', 'alt'] as $field) {
$data[$field] = $this->input($request, $field);
}
$data['name'] = $request->post('name') === null ? $page['name'] : $this->input($request, 'name');
$data['status'] = $request->post('status') === null || $slug === 'home' ? $page['status'] : $this->input($request, 'status');
$scale = $this->input($request, 'image_scale');
$data['image_scale'] = $request->post('image_scale') === null ? (int) $page['image_scale']
: (ctype_digit($scale) ? (int) $scale : -1);
$data['actions'] = [];
$validButtons = true;
foreach ([1, 2] as $index) {
@@ -202,14 +255,21 @@ final class AdminController
}
$page = array_replace($page, $data, ['version' => $this->version($request)]);
try {
if ($data['title'] === '' || mb_strlen($data['title']) > 160 ||
$data['description'] === '' || mb_strlen($data['description']) > 300 ||
$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 ||
($data['status'] === 'published' && $data['description'] === '') || mb_strlen($data['description']) > 300 ||
$data['heading'] === '' || mb_strlen($data['heading'] . $data['accent']) > 110 ||
mb_strlen($data['lead']) > 600 || mb_strlen($data['alt']) > 200 ||
($data['image_scale'] !== 0 && ($data['image_scale'] < 10 || $data['image_scale'] > 100)) ||
strlen($data['image']) > 1000 || ($data['image'] !== '' && !Html::url($data['image'], true)) || !$validButtons) {
throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。');
}
$repo->savePage($slug, $data, $this->version($request));
$sections = $this->canvasSections($request->post('canvas_sections', ''), $page['sections']);
$repo->savePage($slug, $data, $this->version($request), $sections);
return $this->success($request, '/admin/pages/' . $slug . '?saved=1');
} catch (RuntimeException $exception) {
@@ -218,7 +278,7 @@ final class AdminController
}
return $this->render($request, 'admin-page', [
'title' => '编辑 ' . $page['name'], 'page' => $page, 'error' => $error, 'saved' => $request->get('saved') === '1',
'title' => '编辑 ' . $page['name'], 'page' => $page, 'wideAdmin' => true, 'error' => $error, 'saved' => $request->get('saved') === '1',
], $error !== '' ? 422 : 200);
}
@@ -232,17 +292,22 @@ final class AdminController
if (!$section) {
return $this->error($request, '找不到此区块。', 404);
}
$savedStyle = $section['style'];
$categories = $repo->categories();
$error = '';
if ($request->method() === 'POST') {
$data = [
'title' => $this->input($request, 'title'), 'lead' => $this->input($request, 'lead'),
'body' => $this->input($request, 'body'),
'style' => $request->post('style') === null ? $section['style'] : $this->input($request, 'style'),
'feed' => $section['feed'],
];
$section = array_replace($section, $data, ['version' => $this->version($request)]);
try {
if ($data['title'] === '' || mb_strlen($data['title']) > 100 || mb_strlen($data['lead']) > 500 || strlen($data['body']) > 300000) {
throw new RuntimeException('请填写区块标题,并检查说明及正文长度。');
if ($request->post('feed_mode') !== null) {
$data['feed'] = $section['feed'] = $this->feedInput($request, $categories);
}
$this->checkSection($data, $savedStyle);
$data['body'] = Html::sanitize($data['body']);
$repo->saveSection($slug, $key, $data, $this->version($request));
@@ -253,10 +318,84 @@ final class AdminController
}
return $this->render($request, 'admin-section', [
'title' => '编辑区块', 'section' => $section, 'error' => $error, 'saved' => $request->get('saved') === '1',
'title' => '编辑区块', 'section' => $section, 'categories' => $categories, 'savedStyle' => $savedStyle, 'error' => $error, 'saved' => $request->get('saved') === '1',
], $error !== '' ? 422 : 200);
}
private function canvasSections(mixed $payload, array $sections): array
{
if ($payload === '') {
return [];
}
$changes = is_string($payload) ? json_decode($payload, true) : null;
if (!is_array($changes) || !array_is_list($changes) || count($changes) > count($sections) + 50) {
throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。');
}
$available = array_column($sections, null, 'key');
$updates = [];
foreach ($changes as $change) {
$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 === [] && $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('区块已变更或画布内容无效,请重新打开编辑页。');
}
$section = $available[$key] ?? ['key' => $key, 'title' => '', 'lead' => '', 'body' => '', 'style' => 'plain'];
foreach ($fields as $field => $value) {
if (!in_array($field, ['title', 'lead', 'body'], true)) {
throw new RuntimeException('画布内容无效。');
}
if ($field === 'body' && is_array($value)) {
$value = Html::applyCanvasEdits($section['body'], $value);
}
if (!is_string($value)) {
throw new RuntimeException('画布内容无效。');
}
$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']);
}
if ($isNew && ($change['template'] ?? null) === 'articles') {
$section['feed'] = BlockTemplates::ARTICLE_FEED;
}
$section['version'] = $version;
$updates[$key] = $section;
}
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
|| strlen($section['body']) > 300000 || !in_array($section['style'], [$savedStyle, 'plain', 'tinted'], true)) {
throw new RuntimeException('请填写区块标题,并检查说明及正文长度。');
}
}
public function preview(Request $request): Response
{
if ($failure = $this->guard($request)) {
@@ -274,7 +413,7 @@ final class AdminController
], $html);
}
private function guard(Request $request): ?Response
protected function guard(Request $request): ?Response
{
if (!$this->signedIn($request)) {
return $request->isAjax()
@@ -340,7 +479,7 @@ final class AdminController
return is_string($token) && hash_equals($token, $this->input($request, 'csrf'));
}
private function input(Request $request, string $key, bool $trimValue = true): string
protected function input(Request $request, string $key, bool $trimValue = true): string
{
$value = $request->post($key, '');
if (!is_string($value) || !mb_check_encoding($value, 'UTF-8')) {
@@ -350,7 +489,7 @@ final class AdminController
return $trimValue ? trim($value) : $value;
}
private function version(Request $request): int
protected function version(Request $request): int
{
$version = $this->input($request, 'version');
@@ -360,9 +499,14 @@ final class AdminController
private function articleInput(Request $request): array
{
$data = [];
foreach (['title', 'slug', 'category', 'summary', 'body', 'status'] as $key) {
foreach (['title', 'slug', 'summary', 'body', 'status'] as $key) {
$data[$key] = $this->input($request, $key);
}
$data['body_format'] = $this->input($request, 'body_format');
$data['categories'] = $this->selectedCategories($request->post('categories'));
foreach (['image', 'alt', 'url', 'label', 'extra_url', 'extra_label', 'category_label', 'position'] as $field) {
$data['card'][$field] = $this->input($request, 'card_' . $field);
}
$tags = preg_split('/[,,\r\n]+/u', $this->input($request, 'tags'));
$data['tags'] = array_values(array_unique(array_slice(array_filter(
array_map('trim', $tags),
@@ -372,7 +516,46 @@ final class AdminController
return $data;
}
private function validationMessage(RuntimeException $exception): string
private function checkArticleCard(array &$card): void
{
foreach (['image', 'url', 'extra_url'] as $field) {
if (!empty($card[$field]) && (strlen($card[$field]) > 2000 || !Html::url($card[$field], $field === 'image'))) {
throw new RuntimeException('请检查目录卡片的媒体地址和链接。');
}
}
foreach (['alt', 'label', 'extra_label', 'category_label'] as $field) {
if (mb_strlen($card[$field] ?? '') > 120) {
throw new RuntimeException('目录卡片的文字不得超过 120 字。');
}
}
$position = filter_var(($card['position'] ?? '') === '' ? 0 : $card['position'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 9999]]);
if ($position === false) {
throw new RuntimeException('目录排序应为 0 到 9999 的整数。');
}
$card['position'] = $position;
}
private function selectedCategories(mixed $input): array
{
return is_array($input) ? array_values(array_unique(array_filter($input, 'is_string'))) : [];
}
private function feedInput(Request $request, array $available): ?string
{
$mode = $this->input($request, 'feed_mode');
if ($mode === 'off') {
return null;
}
$categories = $this->selectedCategories($request->post('feed_categories'));
$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) {
throw new RuntimeException('请选择文章分类,并将展示数量设为 1 至 30。');
}
return Database::json(compact('categories', 'mode', 'limit'));
}
protected function validationMessage(RuntimeException $exception): string
{
if ($exception instanceof \PDOException) {
error_log($exception->getMessage());
@@ -383,12 +566,12 @@ final class AdminController
return $exception->getMessage();
}
private function success(Request $request, string $path): Response
protected function success(Request $request, string $path): Response
{
return $request->isAjax() ? $this->json(['redirect' => $path]) : View::redirect($path);
}
private function json(array $payload, int $status = 200): Response
protected function json(array $payload, int $status = 200): Response
{
return new Response($status, [
'Content-Type' => 'application/json; charset=utf-8',
@@ -398,7 +581,7 @@ final class AdminController
], Database::json($payload));
}
private function render(Request $request, string $view, array $data, int $status = 200): Response
protected function render(Request $request, string $view, array $data, int $status = 200): Response
{
$token = $this->token($request);
if ($request->isAjax() && $status >= 400) {
@@ -411,7 +594,7 @@ final class AdminController
return View::render($view, $data + ['token' => $token, 'user' => $this->user], $status, true);
}
private function error(Request $request, string $message, int $status): Response
protected function error(Request $request, string $message, int $status): Response
{
return $this->render($request, 'admin-error', ['title' => $message], $status);
}
+45
View File
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\Media;
use support\Request;
use support\Response;
final class MediaController
{
public function file(Request $request, string $name): Response
{
$media = Media::find($name);
$path = Media::directory() . '/' . $name;
if (!$media || !is_file($path)) {
return new Response(404);
}
$length = (int) $media['size'];
$headers = [
'Content-Type' => $media['mime'], 'X-Content-Type-Options' => 'nosniff',
'Content-Security-Policy' => "default-src 'none'; sandbox",
'Cache-Control' => 'public, max-age=31536000, immutable',
'Access-Control-Allow-Origin' => '*', 'Accept-Ranges' => 'bytes',
];
$range = $request->header('range');
if ($range === null) {
return (new Response(200, $headers + ['Content-Length' => (string) $length]))->withFile($path);
}
if (!preg_match('/^bytes=(\d*)-(\d*)$/D', $range, $parts) || $parts[1] === '' && $parts[2] === '') {
return new Response(416, $headers + ['Content-Range' => "bytes */$length"]);
}
$start = $parts[1] === '' ? max(0, $length - (int) $parts[2]) : (int) $parts[1];
$end = $parts[1] === '' || $parts[2] === '' ? $length - 1 : min($length - 1, (int) $parts[2]);
if ($end < $start) {
return new Response(416, $headers + ['Content-Range' => "bytes */$length"]);
}
$count = $end - $start + 1;
return (new Response(206, $headers + ['Content-Length' => (string) $count, 'Content-Range' => "bytes $start-$end/$length"]))
->withFile($path, $start, $count);
}
}
+133 -13
View File
@@ -21,10 +21,34 @@ final class SiteController
{
$repo = new Repository();
$page = $repo->page($slug);
if (!$page) {
if (!$page || $page['status'] !== 'published' || $slug === 'home' && $request->path() !== '/') {
return $this->missing($request);
}
return $this->renderPage($repo, $page);
}
public function renderPage(Repository $repo, array $page, bool $preview = false, bool $canvas = false): Response
{
$slug = $page['slug'];
$isHome = $slug === 'home';
$categories = $repo->categories();
foreach ($page['sections'] as &$section) {
if (!$section['feed']) {
continue;
}
$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'][] = [
'categories' => $selected, 'label' => $categories[$category] ?? '',
'articles' => $repo->articles($selected, limit: $feed['limit']),
];
}
}
unset($section);
return View::render('page', [
'site' => $repo->site(),
@@ -34,15 +58,106 @@ final class SiteController
'description' => $page['description'],
'socialImage' => $page['image'],
'socialAlt' => $page['alt'],
'articles' => $isHome ? $repo->articles(limit: 3) : [],
'network' => $isHome ? $this->networkGroups($repo) : [],
'previewMode' => $preview, 'canvas' => $preview && $canvas, 'noindex' => $preview,
]);
}
public function services(Request $request): Response
{
$repo = new Repository();
return View::render('services', [
'site' => $repo->site(), 'path' => '/services',
'title' => '产品与服务 · 来笙 Laysense',
'description' => '浏览来笙的建站工具、智能 DNS 和软件著作权服务。',
'products' => $repo->articles('services', limit: -1, directoryOrder: true),
]);
}
public function network(Request $request): Response
{
$repo = new Repository();
return View::render('network', [
'site' => $repo->site(), 'path' => '/network', 'title' => '支持项目与合作伙伴 · 来笙',
'description' => '浏览来笙支持的开源项目和合作伙伴。', 'network' => $this->networkGroups($repo),
]);
}
private function networkGroups(Repository $repo): array
{
$groups = [];
foreach (array_diff_key(Repository::DIRECTORIES, ['services' => true]) as $slug => $name) {
$groups[$slug] = ['name' => $name, 'articles' => $repo->articles($slug, limit: -1, directoryOrder: true)];
}
return $groups;
}
public function archive(Request $request, ?string $category = null, ?string $tag = null): Response
{
$repo = new Repository();
$title = $category ? Repository::CATEGORIES[$category] : ($tag ?: '来笙动态');
$categories = $repo->categories();
if ($category !== null && !isset($categories[$category])) {
return $this->missing($request);
}
$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);
@@ -52,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,
'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 === [],
]);
}
@@ -82,13 +196,15 @@ final class SiteController
return $redirect ? View::redirect('/articles/' . $redirect['slug'], 301) : $this->missing($request);
}
$articleHtml = Html::markdown($article['body']);
$articleHtml = Html::articleBody($article);
return View::render('article', [
'site' => $repo->site(), 'article' => $article, 'articleHtml' => $articleHtml,
'title' => $article['title'] . ' · 来笙',
'description' => $article['summary'] ?: mb_substr(trim(strip_tags($articleHtml)), 0, 150) ?: $article['title'],
'path' => '/articles/' . $article['slug'], 'noindex' => trim($articleHtml) === '',
'path' => '/articles/' . $article['slug'],
'socialImage' => $article['card']['image'] ?? '', 'socialAlt' => $article['card']['alt'] ?? '',
'noindex' => trim($articleHtml) === '' && !$article['summary'] && empty($article['card']['url']) && empty($article['card']['image']),
]);
}
@@ -118,7 +234,9 @@ final class SiteController
{
$repo = new Repository();
$xml = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'];
$pages = $repo->pages();
$pages = $repo->pages(publishedOnly: true);
$pages[] = ['slug' => 'services', 'updated_at' => null];
$pages[] = ['slug' => 'network', 'updated_at' => null];
if ($repo->articles(limit: 1)) {
$pages[] = ['slug' => 'articles', 'updated_at' => null];
}
@@ -144,7 +262,9 @@ final class SiteController
$path = $request->path();
if ($request->method() === 'GET' && strlen($path) > 1 && str_ends_with($path, '/')) {
$normal = rtrim($path, '/');
if (preg_match('~^/(?:pagepan|highspeaker|sc|shnu-sc|articles(?:/[a-z0-9-]+){0,2})$~D', $normal)) {
$single = preg_match('~^/[a-z0-9-]+$~D', $normal);
$known = $single && ((new Repository())->page(substr($normal, 1))['status'] ?? null) === 'published' && $normal !== '/home';
if ($known || in_array($normal, ['/services', '/network'], true) || preg_match('~^/articles(?:/[a-z0-9-]+){0,2}$~D', $normal)) {
$query = $request->queryString();
return View::redirect($normal . ($query !== '' ? '?' . $query : ''), 301);
+223
View File
@@ -0,0 +1,223 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\Assets;
use App\Content\BlockTemplates;
use App\Content\Html;
use App\Content\Media;
use App\Content\Repository;
use App\Content\SiteDesign;
use App\Http\Request;
use RuntimeException;
use support\Response;
use Webman\Http\UploadFile;
final class StudioController extends AdminController
{
public function newPage(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$data = ['title' => '新建页面', 'name' => '', 'slug' => '', 'error' => ''];
if ($request->method() === 'POST') {
$data['name'] = $this->input($request, 'name');
$data['slug'] = $this->input($request, 'slug');
try {
if (!$this->slug($data['slug']) || in_array($data['slug'], ['admin', 'assets', 'articles', 'home', 'services', 'network', 'news', 'main', 'favicon'], true)
|| $data['name'] === '' || mb_strlen($data['name']) > 100) {
throw new RuntimeException('请填写页面名称及可用的网址标识。');
}
(new Repository())->createPage($data['slug'], $data['name']);
return $this->success($request, '/admin/pages/' . $data['slug']);
} catch (RuntimeException $error) {
$data['error'] = $this->validationMessage($error);
}
}
return $this->render($request, 'studio-new-page', $data, $data['error'] === '' ? 200 : 422);
}
public function previewPage(Request $request, string $slug): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$repo = new Repository();
$page = $repo->page($slug);
return $page ? (new SiteController())->renderPage($repo, $page, true, $request->get('canvas') === '1') : $this->error($request, '找不到此页面。', 404);
}
public function blocks(Request $request, string $slug): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$repo = new Repository();
if (!$repo->page($slug)) {
return $this->error($request, '找不到此页面。', 404);
}
$action = $this->input($request, 'operation');
$key = $this->input($request, 'key');
try {
if (!$this->slug($key) || in_array($key, ['preview', 'home', 'contact', 'main-content', 'partners', 'supported-projects'], true)) {
throw new RuntimeException('区块锚点不可用。');
}
if ($action === 'create') {
$type = $this->input($request, 'preset');
$preset = BlockTemplates::find($type);
if ($preset === null) {
throw new RuntimeException('请选择区块类型。');
}
$repo->createSection($slug, $key, $preset[0], 'plain', $preset[1], $type === 'articles' ? BlockTemplates::ARTICLE_FEED : null);
return $this->success($request, "/admin/pages/$slug/$key");
}
if (!in_array($action, ['up', 'down', 'delete'], true)) {
throw new RuntimeException('操作不可用。');
}
$pageVersion = $this->input($request, 'page_version');
$repo->arrangeSection($slug, $key, $action, $this->version($request), ctype_digit($pageVersion) ? (int) $pageVersion : -1);
return $this->success($request, "/admin/pages/$slug#blocks");
} catch (RuntimeException $error) {
return $this->error($request, $this->validationMessage($error), 422);
}
}
public function settings(Request $request, string $part): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$site = (new Repository())->site();
$defaults = match ($part) {
'header' => SiteDesign::DEFAULT_HEADER,
'footer' => SiteDesign::DEFAULT_FOOTER,
'cdn' => ['origin' => ''],
};
$config = $part === 'footer' ? SiteDesign::footer($site) : ($site[$part] ?? []) + $defaults;
$version = $site['revisions'][$part] ?? 0;
$error = '';
if ($request->method() === 'POST') {
try {
$config = $part === 'footer' && $request->post('operation') === 'restore-footer'
? $defaults : $this->settingsInput($request, $part, $defaults, $config);
SiteDesign::saveSettings($part, $config, $this->version($request));
return $this->success($request, '/admin/settings/' . $part . '?saved=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
$version = $this->version($request);
}
}
return $this->render($request, 'studio-settings', [
'part' => $part, 'config' => $config, 'revision' => $version, 'error' => $error, 'saved' => $request->get('saved') === '1',
'title' => ['header' => '页头', 'footer' => '页脚', 'cdn' => '静态资源 CDN'][$part],
], $error === '' ? 200 : 422);
}
public function media(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$error = '';
if ($request->method() === 'POST') {
try {
$file = $request->file('file');
if (!$file instanceof UploadFile || !$file->isValid()) {
throw new RuntimeException('请选择要上传的文件。');
}
$label = $this->input($request, 'label') ?: mb_substr((string) $file->getUploadName(), 0, 160);
if (mb_strlen($label) > 160) {
throw new RuntimeException('资源名称最多 160 个字符。');
}
Media::upload($file, $label);
return $this->success($request, '/admin/media?uploaded=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
}
}
return $this->render($request, 'studio-media', [
'title' => '媒体库', 'files' => Media::all(true), 'error' => $error, 'saved' => $request->get('uploaded') === '1',
], $error === '' ? 200 : 422);
}
public function mediaOptions(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
return $this->json(['files' => Media::all()]);
}
public function mediaMeta(Request $request, string $name): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$label = $this->input($request, 'label');
if (!Media::find($name)) {
return $this->error($request, '找不到此资源。', 404);
}
if ($label === '' || mb_strlen($label) > 160) {
return $this->error($request, '请输入资源名称,最多 160 个字符。', 422);
}
Media::update($name, $label, $this->input($request, 'archived') === '1');
return $this->success($request, '/admin/media');
}
private function settingsInput(Request $request, string $part, array $defaults, array $current): array
{
if ($part === 'cdn') {
return ['origin' => Assets::cdn($this->input($request, 'origin'))];
}
$result = [];
$hasResources = $request->post('resources') !== null;
foreach ($defaults as $key => $default) {
if ($part === 'footer' && !$hasResources && in_array($key, ['resources', 'resources_title'], true)) {
$result[$key] = $current[$key];
continue;
}
$input = $this->input($request, $key);
if (is_array($default)) {
$result[$key] = SiteDesign::parseLinks($input);
if ($key === 'button') {
if (count($result[$key]) > 1) {
throw new RuntimeException('页头按钮只接受一条链接。');
}
$result[$key] = $result[$key][0] ?? [];
}
} else {
if (mb_strlen($input) > 1000) {
throw new RuntimeException('设置字段过长。');
}
$result[$key] = $input;
}
}
if ($result['logo'] !== '' && !Html::url($result['logo'], true)) {
throw new RuntimeException('请输入有效的标志图片地址。');
}
if ($part === 'footer' && ($result['name'] === '' || ($result['email'] !== '' && !filter_var($result['email'], FILTER_VALIDATE_EMAIL)))) {
throw new RuntimeException('请填写公司名称及有效的联系邮箱。');
}
return $result;
}
private function slug(string $value): bool
{
return strlen($value) <= 70 && preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/D', $value) === 1;
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Middleware;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
final class PublicAssets implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
$response = $handler($request);
$path = $request->path();
if (str_starts_with($path, '/assets/')) {
$response->withHeader('Access-Control-Allow-Origin', '*');
if ($path === '/assets/jquery-4.0.0.min.js') {
$response->withHeader('Cache-Control', 'public, max-age=31536000, immutable');
}
}
return $response;
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<a class="back-link" href="/admin/articles">返回文章列表</a>
<header class="admin-heading"><h1>文章分类</h1></header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/article-categories">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<div class="form-grid">
<label>分类名称<input name="name" value="<?= $e($name) ?>" required maxlength="60"></label>
<label>网址标识<input name="slug" value="<?= $e($slug) ?>" required maxlength="60" pattern="[a-z0-9]+(-[a-z0-9]+)*"></label>
</div>
<div class="form-submit"><button class="button button-primary" type="submit">创建分类</button></div>
</form>
<nav class="filter-nav" aria-label="查看分类">
<?php foreach ($categories as $key => $label): ?>
<a href="/admin/articles?category=<?= $e($key) ?>"><?= $e($label) ?></a>
<?php endforeach ?>
</nav>
+1 -2
View File
@@ -1,5 +1,4 @@
<?php
use App\Content\Repository;
use App\Content\View;
$e = View::escape(...);
@@ -9,7 +8,7 @@ $e = View::escape(...);
<?php foreach ($articles as $item): ?>
<li>
<div><strong><?= $e($item['title']) ?></strong>
<small><?= $e(Repository::CATEGORIES[$item['category']]) ?> · <?= $item['status'] === 'published' ? '已发布' : '草稿' ?> · <?= $e(View::date($item['updated_at'])) ?></small>
<small><?= $e(implode('、', $item['categories'])) ?> · <?= $item['status'] === 'published' ? '已发布' : '草稿' ?> · <?= $e(View::date($item['updated_at'])) ?></small>
</div>
<a class="button button-outline" href="/admin/articles/<?= $e($item['id']) ?>">编辑文章</a>
</li>
+25 -9
View File
@@ -16,17 +16,33 @@ $e = View::escape(...);
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($article['version']) ?>">
<label>文章标题<input name="title" value="<?= $e($article['title']) ?>" required maxlength="120"></label>
<div class="form-grid">
<label>网址标识<input name="slug" value="<?= $e($article['slug']) ?>" required maxlength="100" pattern="[a-z0-9]+(-[a-z0-9]+)*" placeholder="product-update"><small>使用小写英文字母、数字和连字符。</small></label>
<label>分类<select name="category">
<?php foreach (Repository::CATEGORIES as $key => $label): ?>
<option value="<?= $e($key) ?>" <?= $article['category'] === $key ? 'selected' : '' ?>><?= $e($label) ?></option>
<?php endforeach ?>
</select></label>
</div>
<label>网址标识<input name="slug" value="<?= $e($article['slug']) ?>" required maxlength="100" pattern="[a-z0-9]+(-[a-z0-9]+)*" placeholder="product-update"><small>使用小写英文字母、数字和连字符。</small></label>
<?= View::fragment('admin-category-checkboxes', ['name' => 'categories', 'selected' => array_keys($article['categories']), 'categories' => $categories, 'legend' => '文章分类(可多选)']) ?>
<label>标签<input name="tags" value="<?= $e(implode(',', $article['tags'])) ?>" placeholder="用逗号分隔"></label>
<label>摘要<textarea name="summary" rows="2" maxlength="250"><?= $e($article['summary']) ?></textarea><small>用于动态列表和搜索摘要。</small></label>
<?= View::fragment('admin-editor', ['format' => 'markdown', 'body' => $article['body']]) ?>
<div class="article-editor" data-article-editor>
<div class="article-editor-heading">
<label for="article-source" data-article-editor-label>正文</label>
<button type="button" class="button button-outline" data-insert-article-image hidden>从媒体库插入图片</button>
</div>
<input type="hidden" name="body_format" value="<?= $e($article['body_format']) ?>">
<textarea id="article-source" name="body" rows="16" aria-label="文章正文"><?= $e($article['body']) ?></textarea>
<div data-editor-host hidden></div>
<p class="article-editor-help" data-article-editor-status role="status"></p>
</div>
<details class="admin-options" <?= array_intersect(array_keys($article['categories']), array_keys(Repository::DIRECTORIES)) ? 'open' : '' ?>>
<summary>目录卡片</summary>
<div class="form-grid">
<?= View::fragment('studio-asset-field', ['name' => 'card_image', 'label' => '封面或标志', 'value' => $article['card']['image'] ?? '']) ?>
<label>图片替代文字<input name="card_alt" value="<?= $e($article['card']['alt'] ?? '') ?>" maxlength="120"></label>
<label>主链接<input name="card_url" value="<?= $e($article['card']['url'] ?? '') ?>"></label>
<label>主链接文字<input name="card_label" value="<?= $e($article['card']['label'] ?? '') ?>" maxlength="120"></label>
<label>附加链接<input name="card_extra_url" value="<?= $e($article['card']['extra_url'] ?? '') ?>"></label>
<label>附加链接文字<input name="card_extra_label" value="<?= $e($article['card']['extra_label'] ?? '') ?>" maxlength="120"></label>
<label>类型说明<input name="card_category_label" value="<?= $e($article['card']['category_label'] ?? '') ?>" maxlength="120"></label>
<label>目录排序(从小到大)<input name="card_position" type="number" min="0" max="9999" value="<?= $e($article['card']['position'] ?? 0) ?>"></label>
</div>
</details>
<div class="form-submit">
<label>发布状态<select name="status">
<option value="draft" <?= $article['status'] === 'draft' ? 'selected' : '' ?>>草稿</option>
+16 -3
View File
@@ -1,17 +1,30 @@
<?php
use App\Content\View;
$e = View::escape(...);
$filters = $category ? 'category=' . rawurlencode($category) . '&' : '';
?>
<header class="admin-heading">
<h1>文章与动态</h1>
<a class="button button-primary" href="/admin/articles/new">新建文章</a>
<div class="actions">
<a class="button button-outline" href="/admin/article-categories">管理分类</a>
<a class="button button-primary" href="/admin/articles/new<?= $category ? '?category=' . $e($category) : '' ?>">新建文章</a>
</div>
</header>
<nav class="filter-nav" aria-label="筛选文章">
<a href="/admin/articles" <?= $category === null ? 'aria-current="page"' : '' ?>>全部</a>
<?php foreach ($categories as $key => $name): ?>
<a href="/admin/articles?category=<?= $e($key) ?>" <?= $category === (string) $key ? 'aria-current="page"' : '' ?>><?= $e($name) ?></a>
<?php endforeach ?>
</nav>
<div class="admin-panel">
<?= View::fragment('admin-article-list', ['articles' => $articles]) ?>
</div>
<?php if ($pageNumber > 1 || $hasNext): ?>
<nav class="pagination" aria-label="文章分页">
<?php if ($pageNumber > 1): ?><a class="button button-outline" href="/admin/articles?page=<?= $pageNumber - 1 ?>">上一页</a><?php endif ?>
<?php if ($pageNumber > 1): ?><a class="button button-outline" href="/admin/articles?<?= $e($filters) ?>page=<?= $pageNumber - 1 ?>">上一页</a><?php endif ?>
<span>第 <?= $pageNumber ?> 页</span>
<?php if ($hasNext): ?><a class="button button-outline" href="/admin/articles?page=<?= $pageNumber + 1 ?>">下一页</a><?php endif ?>
<?php if ($hasNext): ?><a class="button button-outline" href="/admin/articles?<?= $e($filters) ?>page=<?= $pageNumber + 1 ?>">下一页</a><?php endif ?>
</nav>
<?php endif ?>
+14
View File
@@ -0,0 +1,14 @@
<?php
use App\Content\View;
$e = View::escape(...);
$checked = array_fill_keys($selected, true);
?>
<fieldset class="category-checks">
<legend><?= $e($legend) ?></legend>
<div>
<?php foreach ($categories as $key => $label): ?>
<label><input type="checkbox" name="<?= $e($name) ?>[]" value="<?= $e($key) ?>" <?= isset($checked[$key]) ? 'checked' : '' ?>> <?= $e($label) ?></label>
<?php endforeach ?>
</div>
</fieldset>
+3 -2
View File
@@ -5,14 +5,15 @@ $e = View::escape(...);
?>
<header class="admin-heading">
<div><h1>内容管理</h1><p>管理网站页面、文章、公告和产品动态。</p></div>
<a class="button button-primary" href="/admin/articles/new">新建文章</a>
<div class="actions"><a class="button button-primary" href="/admin/new-page">新建页面</a>
<a class="button button-outline" href="/admin/articles/new">新建文章</a></div>
</header>
<section class="admin-panel" aria-labelledby="pages-title">
<h2 id="pages-title">网站页面</h2>
<ul class="admin-list">
<?php foreach ($pages as $page): ?>
<li>
<div><strong><?= $e($page['name']) ?></strong><small><?= $e($page['slug'] === 'home' ? '/' : '/' . $page['slug']) ?></small></div>
<div><strong><?= $e($page['name']) ?></strong><small><?= $e($page['slug'] === 'home' ? '/' : '/' . $page['slug']) ?> · <?= $page['status'] === 'draft' ? '草稿' : '已发布' ?></small></div>
<a class="button button-outline" href="/admin/pages/<?= $e($page['slug']) ?>">编辑页面</a>
</li>
<?php endforeach ?>
+12 -2
View File
@@ -1,5 +1,6 @@
<?php
use App\Content\View;
use App\Content\Html;
$e = View::escape(...);
?>
@@ -12,11 +13,20 @@ $e = View::escape(...);
<button type="button" data-insert="list">列表</button>
<button type="button" data-insert="link">链接</button>
</div>
<button data-preview-button type="button" aria-controls="editor-preview" aria-expanded="false">预览正文</button>
<?php if ($format === 'html'): ?>
<button type="button" data-rich-media>插入媒体</button>
<button type="button" data-source-toggle aria-pressed="false">HTML 源码</button>
<?php else: ?>
<button data-preview-button type="button" aria-controls="editor-preview" aria-expanded="false">预览正文</button>
<?php endif ?>
</div>
<?php if ($format === 'html'): ?>
<div class="rich studio-rich" contenteditable="true" role="textbox" aria-multiline="true" aria-label="可视化正文" data-rich-canvas hidden><?= Html::sanitize($body) ?></div>
<p class="field-note" data-rich-status role="status" hidden></p>
<?php endif ?>
<textarea id="editor-text" name="body" rows="15" spellcheck="false"><?= $e($body) ?></textarea>
<?php if ($format === 'html'): ?>
<p class="field-note">支持段落、标题、链接、图片、列表、表格和折叠问答。保存时会清理脚本、内联样式等标签或属性。</p>
<p class="field-note">可以直接编辑文字,插入链接、图片、音视频。复杂区块可切换到 HTML 源码调整。</p>
<?php endif ?>
<div class="editor-preview rich prose" id="editor-preview" aria-live="polite" hidden></div>
</div>
+1 -1
View File
@@ -1,3 +1,3 @@
<?php use App\Content\View; ?>
<?php if ($error): ?><p class="feedback error" role="alert"><?= View::escape($error) ?></p><?php endif ?>
<?php if ($saved && !$error): ?><p class="feedback success" role="status">已保存。</p><?php endif ?>
<?php if ($saved && !$error): ?><p class="feedback success" data-save-confirmation role="status">已保存。</p><?php endif ?>
+19 -1
View File
@@ -15,6 +15,13 @@ $e = View::escape(...);
<link rel="stylesheet" href="/assets/admin.css">
<script src="/assets/jquery-4.0.0.min.js" defer></script>
<script src="/assets/admin.js" defer></script>
<script src="/assets/studio.js" defer></script>
<?php if (!empty($articleEditor)): ?>
<link rel="stylesheet" href="/assets/vendor/toastui/toastui-editor.min.css">
<script src="/assets/vendor/toastui/toastui-editor.min.js" defer></script>
<script src="/assets/vendor/toastui/zh-cn.js" defer></script>
<script src="/assets/article-editor.js" defer></script>
<?php endif ?>
</head>
<body class="admin-body">
<a class="skip-link" href="#admin-content">跳到内容</a>
@@ -25,6 +32,8 @@ $e = View::escape(...);
<nav aria-label="后台导航">
<a href="/admin">页面</a>
<a href="/admin/articles">文章</a>
<a href="/admin/media">媒体库</a>
<a href="/admin/settings/header">网站设置</a>
<a href="/admin/password">修改密码</a>
<a href="/">访问网站</a>
<form method="post" action="/admin/logout">
@@ -37,6 +46,15 @@ $e = View::escape(...);
<?php endif ?>
</div>
</header>
<main class="admin-wrap admin-main" id="admin-content"><?= $content ?></main>
<main class="admin-wrap admin-main<?= !empty($wideAdmin) ? ' admin-wide' : '' ?>" id="admin-content"><?= $content ?></main>
<?php if ($user): ?>
<dialog class="media-picker" id="media-picker" aria-labelledby="picker-heading">
<header class="admin-heading compact"><h2 id="picker-heading">从媒体库选择</h2><button class="button button-outline" type="button" data-close-picker>关闭</button></header>
<label>查找资源<input type="search" data-media-query placeholder="搜索文件名或资源路径"></label>
<p data-picker-status role="status"></p>
<div class="picker-grid" data-picker-items></div>
<a class="back-link" href="/admin/media" target="_blank" rel="noopener">打开媒体库上传</a>
</dialog>
<?php endif ?>
</body>
</html>
+156 -35
View File
@@ -1,46 +1,167 @@
<?php
use App\Content\Database;
use App\Content\SiteDesign;
use App\Content\View;
use App\Content\BlockTemplates;
$e = View::escape(...);
$slug = $page['slug'];
$path = $slug === 'home' ? '/' : '/' . $slug;
$previewUrl = '/admin/pages/' . $slug . '/preview';
?>
<a class="back-link" href="/admin">返回内容管理</a>
<a class="back-link" href="/admin">返回页面</a>
<header class="admin-heading">
<h1><?= $e($title) ?></h1>
<a class="button button-outline" href="<?= $e($slug === 'home' ? '/' : '/' . $slug) ?>">查看公开页面</a>
<div><h1><?= $e($title) ?></h1><p><?= $e($path) ?> · <?= $page['status'] === 'draft' ? '草稿' : '已发布' ?></p></div>
<div class="actions">
<?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>
</div>
</header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/pages/<?= $e($slug) ?>">
<h2>首屏与 SEO</h2>
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($page['version']) ?>">
<label>SEO 标题<input name="title" value="<?= $e($page['title']) ?>" required maxlength="160"></label>
<label>SEO 描述<textarea name="description" rows="3" required maxlength="300"><?= $e($page['description']) ?></textarea></label>
<div class="form-grid">
<label>首屏标题<input name="heading" value="<?= $e($page['heading']) ?>" required maxlength="110"></label>
<label>标题第二行<input name="accent" value="<?= $e($page['accent']) ?>" maxlength="110"></label>
<div class="studio-layout">
<aside class="admin-panel studio-library" aria-labelledby="studio-library-title">
<h2 id="studio-library-title">区块模板</h2>
<?= View::fragment('studio-templates') ?>
<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">
<summary>区块顺序</summary>
<ul class="admin-list studio-blocks">
<?php foreach ($page['sections'] as $index => $item): ?>
<li>
<div><strong><?= $e($item['title']) ?></strong><small>#<?= $e($item['key']) ?></small></div>
<div class="actions studio-block-actions">
<button class="button button-outline" type="button" data-canvas-jump="<?= $e($item['key']) ?>" hidden>在画布编辑</button>
<a class="button button-outline" href="/admin/pages/<?= $e($slug) ?>/<?= $e($item['key']) ?>">区块设置</a>
<form method="post" action="/admin/page-blocks/<?= $e($slug) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="key" value="<?= $e($item['key']) ?>">
<input type="hidden" name="page_version" value="<?= $e($page['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="down" type="submit" <?= $index === count($page['sections']) - 1 ? 'disabled' : '' ?>>下移</button>
<button class="button button-outline" name="operation" value="delete" type="submit" data-confirm="删除这个区块?">删除</button>
</form>
</div>
</li>
<?php endforeach ?>
</ul>
</details>
</aside>
<div class="studio-workspace">
<section class="admin-panel studio-preview" data-preview-studio aria-labelledby="studio-preview-title">
<div class="admin-heading compact">
<h2 id="studio-preview-title">页面画布</h2>
<div class="preview-selector" aria-label="预览尺寸">
<button type="button" class="button button-outline" data-preview-size="desktop" aria-pressed="true">桌面</button>
<button type="button" class="button button-outline" data-preview-size="phone" aria-pressed="false">手机</button>
</div>
</div>
<div class="editor-toolbar studio-canvas-toolbar" data-canvas-toolbar hidden aria-label="正文工具">
<div>
<button type="button" data-canvas-command="heading">小标题</button>
<button type="button" data-canvas-command="bold">粗体</button>
<button type="button" data-canvas-command="list">列表</button>
<button type="button" data-canvas-command="link">插入链接</button>
<button type="button" data-canvas-command="media">插入媒体</button>
</div>
<button class="button button-primary" form="studio-page-settings" type="submit">保存页面</button>
</div>
<div class="studio-frame-window">
<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-align" data-element-align role="group" aria-label="对齐">
<button type="button" data-align="left" aria-pressed="false">居左</button>
<button type="button" data-align="center" aria-pressed="false">居中</button>
<button type="button" data-align="right" aria-pressed="false">居右</button>
</div>
<button type="button" data-element-properties>属性</button>
<button type="button" data-element-copy>复制</button>
<button type="button" data-element-delete>删除</button>
</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>
<div class="studio-media-sizing" data-media-sizing hidden>
<output data-media-size aria-hidden="true"></output>
<button class="button button-outline" type="button" data-reset-media>原始尺寸</button>
<button class="button button-outline" type="button" data-replace-media>替换媒体</button>
</div>
</div>
<p class="field-note">单击画布元素可设置对齐、复制或删除。选中媒体后可拖动边缘手柄调整宽度。</p>
<dialog class="media-picker canvas-properties" data-canvas-properties aria-labelledby="canvas-properties-heading">
<div class="admin-heading compact"><h2 id="canvas-properties-heading" data-property-heading>编辑属性</h2></div>
<form class="admin-form" method="dialog">
<label data-property-row="label">文案<input name="label"></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="quicklinks">目录链接<textarea name="quicklinks" rows="5" placeholder="概览 | #overview"></textarea><small>每行填写「文案 | 链接」。</small></label>
<label data-property-row="poster">视频封面<input name="poster" maxlength="1000"></label>
<p class="feedback error" role="alert" data-property-error hidden></p>
<div class="actions">
<button type="button" class="button button-outline" data-property-pick="url">从媒体库选择</button>
<button type="button" class="button button-outline" data-property-pick="poster">选择视频封面</button>
</div>
<div class="actions">
<button type="submit" class="button button-primary">应用</button>
<button type="button" class="button button-outline" data-property-close>取消</button>
</div>
</form>
</dialog>
</section>
</div>
<label>首屏简介<textarea name="lead" rows="3" maxlength="600"><?= $e($page['lead']) ?></textarea></label>
<div class="form-grid">
<label>首屏图片地址<input name="image" value="<?= $e($page['image']) ?>" maxlength="1000"></label>
<label>图片替代文本<input name="alt" value="<?= $e($page['alt']) ?>" maxlength="200"></label>
</div>
<?php foreach ([1, 2] as $index): ?>
<div class="form-grid">
<label>按钮 <?= $index ?> 文案<input name="label<?= $index ?>" value="<?= $e($page['actions'][$index - 1][1] ?? '') ?>" maxlength="50"></label>
<label>按钮 <?= $index ?> 链接<input name="url<?= $index ?>" value="<?= $e($page['actions'][$index - 1][0] ?? '') ?>" maxlength="1000"></label>
</div>
<?php endforeach ?>
<div class="form-submit"><button class="button button-primary" type="submit">保存页面</button></div>
</form>
<section class="admin-panel">
<h2>内容区块</h2>
<ul class="admin-list">
<?php foreach ($page['sections'] as $item): ?>
<li>
<div><strong><?= $e($item['title']) ?></strong><small>#<?= $e($item['key']) ?></small></div>
<a class="button button-outline" href="/admin/pages/<?= $e($slug) ?>/<?= $e($item['key']) ?>">编辑区块</a>
</li>
<form id="studio-page-settings" class="admin-form admin-panel studio-inspector" method="post" action="/admin/pages/<?= $e($slug) ?>">
<h2>页面设置</h2>
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($page['version']) ?>">
<input type="hidden" name="canvas_sections" value="">
<input type="hidden" name="alignments" value="<?= $e(Database::json($page['alignments'])) ?>">
<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 描述<textarea name="description" rows="2" maxlength="300"><?= $e($page['description']) ?></textarea></label>
<?php
$contentFields = [
'heading' => $page['heading'], 'accent' => $page['accent'], 'lead' => $page['lead'],
'image' => $page['image'], 'alt' => $page['alt'], 'image_scale' => $page['image_scale'],
'quicklinks' => SiteDesign::linkText($page['quicklinks']),
];
foreach ([1, 2] as $index) {
$contentFields['label' . $index] = $page['actions'][$index - 1][1] ?? '';
$contentFields['url' . $index] = $page['actions'][$index - 1][0] ?? '';
}
?>
<?php foreach ($contentFields as $field => $value): ?>
<?php if ($field === 'quicklinks'): ?>
<textarea name="quicklinks" hidden><?= $e($value) ?></textarea>
<?php else: ?>
<input type="hidden" name="<?= $e($field) ?>" value="<?= $e($value) ?>">
<?php endif ?>
<?php endforeach ?>
</ul>
</section>
<?php if ($slug !== 'home'): ?>
<label>发布状态<select name="status"><option value="draft" <?= $page['status'] === 'draft' ? 'selected' : '' ?>>草稿</option>
<option value="published" <?= $page['status'] === 'published' ? 'selected' : '' ?>>已发布</option></select></label>
<?php endif ?>
<div class="form-submit"><button class="button button-primary" type="submit">保存页面</button></div>
</form>
</div>
+19 -1
View File
@@ -4,11 +4,12 @@ use App\Content\View;
$e = View::escape(...);
$slug = $section['page_slug'];
$key = $section['key'];
$feed = json_decode($section['feed'] ?? '{}', true, flags: JSON_THROW_ON_ERROR);
?>
<a class="back-link" href="/admin/pages/<?= $e($slug) ?>">返回页面编辑</a>
<header class="admin-heading">
<div><h1><?= $e($title) ?></h1><p><?= $e($slug) ?> · #<?= $e($key) ?></p></div>
<a class="button button-outline" href="<?= $e(($slug === 'home' ? '/' : '/' . $slug) . '#' . $key) ?>">查看公开区块</a>
<a class="button button-outline" href="/admin/pages/<?= $e($slug) ?>/preview#<?= $e($key) ?>" target="_blank" rel="noopener">预览区块</a>
</header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/pages/<?= $e($slug) ?>/<?= $e($key) ?>">
@@ -16,6 +17,23 @@ $key = $section['key'];
<input type="hidden" name="version" value="<?= $e($section['version']) ?>">
<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>区块背景<select name="style">
<?php foreach (array_unique([$savedStyle, 'plain', 'tinted']) as $style): ?>
<option value="<?= $e($style) ?>" <?= $style === $section['style'] ? 'selected' : '' ?>><?= $e(['plain' => '默认', 'tinted' => '浅色背景'][$style] ?? '保留原布局') ?></option>
<?php endforeach ?>
</select></label>
<details class="admin-options" <?= $feed ? 'open' : '' ?>>
<summary>文章组件</summary>
<div class="form-grid">
<label>展示方式<select name="feed_mode">
<?php foreach (['off' => '不展示', 'merged' => '合并为一个列表', 'tabs' => '按分类分标签页'] 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" 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']]) ?>
<div class="form-submit"><button class="button button-primary" type="submit">保存区块</button></div>
</form>
+8 -9
View File
@@ -1,5 +1,4 @@
<?php
use App\Content\Repository;
use App\Content\View;
$e = View::escape(...);
@@ -7,22 +6,22 @@ $e = View::escape(...);
<section class="section article-page" aria-labelledby="archive-title" data-enter>
<div class="wrap">
<div class="section-heading">
<?php if ($tag || $category): ?><a class="back-link" href="/articles">全部动态</a><?php endif ?>
<?php if ($backPath): ?><a class="back-link" href="<?= $e($backPath) ?>"><?= $e($backLabel) ?></a><?php endif ?>
<h1 id="archive-title"><?= $e($headline) ?></h1>
<p>来笙的公告、新闻和产品动态。</p>
<p><?= $e($description) ?></p>
</div>
<nav class="filter-nav" aria-label="动态分类">
<a href="/articles" <?= !$category && !$tag ? 'aria-current="page"' : '' ?>>全部</a>
<?php foreach (Repository::CATEGORIES as $key => $label): ?>
<a href="/articles/category/<?= $e($key) ?>" <?= $category === $key ? 'aria-current="page"' : '' ?>><?= $e($label) ?></a>
<a href="<?= $e($allPath) ?>" <?= !$category && !$tag ? 'aria-current="page"' : '' ?>>全部</a>
<?php foreach ($categories as $key => $label): ?>
<a href="<?= $e($categoryLinks[$key]) ?>" <?= $category === (string) $key ? 'aria-current="page"' : '' ?>><?= $e($label) ?></a>
<?php endforeach ?>
</nav>
<?= View::fragment('article-list', ['articles' => $articles]) ?>
<?= View::fragment('article-list', ['articles' => $articles, 'categoryScope' => $categoryScope ?? null]) ?>
<?php if ($pageNumber > 1 || $hasNext): ?>
<nav class="pagination" aria-label="动态分页">
<?php if ($pageNumber > 1): ?><a class="button button-outline" href="<?= $e($archivePath . ($pageNumber > 2 ? '?page=' . ($pageNumber - 1) : '')) ?>" rel="prev">上一页</a><?php endif ?>
<?php if ($pageNumber > 1): ?><a class="button button-outline" href="<?= $e(View::archivePage($archivePath, $pageNumber - 1)) ?>" rel="prev">上一页</a><?php endif ?>
<span>第 <?= $e($pageNumber) ?> 页</span>
<?php if ($hasNext): ?><a class="button button-outline" href="<?= $e($archivePath . '?page=' . ($pageNumber + 1)) ?>" rel="next">下一页</a><?php endif ?>
<?php if ($hasNext): ?><a class="button button-outline" href="<?= $e(View::archivePage($archivePath, $pageNumber + 1)) ?>" rel="next">下一页</a><?php endif ?>
</nav>
<?php endif ?>
</div>
+23
View File
@@ -0,0 +1,23 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<div class="article-feed" <?= count($groups) > 1 ? 'data-article-tabs' : '' ?>>
<?php if (count($groups) > 1): ?>
<div class="filter-nav article-tabs" data-tab-list role="tablist" aria-labelledby="heading-<?= $e($sectionKey) ?>" hidden>
<?php foreach ($groups as $index => $group): ?>
<button type="button" role="tab" id="<?= $e($sectionKey) ?>-tab-<?= $index ?>" aria-controls="<?= $e($sectionKey) ?>-articles-<?= $index ?>"><?= $e($group['label']) ?></button>
<?php endforeach ?>
</div>
<?php endif ?>
<?php foreach ($groups as $index => $group): ?>
<div id="<?= $e($sectionKey) ?>-articles-<?= $index ?>" data-tab-panel>
<?php if ($group['label'] !== ''): ?><h3 data-tab-heading><?= $e($group['label']) ?></h3><?php endif ?>
<?= View::fragment('article-list', ['articles' => $group['articles'], 'categoryScope' => $group['categories']]) ?>
</div>
<?php endforeach ?>
<?php if ($archivePath !== null): ?>
<p class="article-feed-archive"><a class="back-link" href="<?= $e($archivePath) ?>">查看全部动态</a></p>
<?php endif ?>
</div>
+4 -3
View File
@@ -1,19 +1,20 @@
<?php
use App\Content\Repository;
use App\Content\View;
$e = View::escape(...);
$scope = isset($categoryScope) ? array_flip($categoryScope) : null;
?>
<?php if ($articles): ?>
<ul class="article-list">
<?php foreach ($articles as $item): ?>
<?php $labels = $scope === null ? $item['categories'] : array_intersect_key($item['categories'], $scope); ?>
<li>
<a class="article-row" href="/articles/<?= $e($item['slug']) ?>">
<span class="article-category"><?= $e(Repository::CATEGORIES[$item['category']]) ?></span>
<span class="article-category"><?= $e(implode('、', $labels)) ?></span>
<span class="article-row-title"><?= $e($item['title']) ?>
<?php if ($item['summary']): ?><small><?= $e($item['summary']) ?></small><?php endif ?>
</span>
<time datetime="<?= $e(View::date($item['published_at'], 'Y-m-d')) ?>"><?= $e(View::date($item['published_at'], 'Y.m.d')) ?></time>
<?php if ($item['published_at']): ?><time datetime="<?= $e(View::date($item['published_at'], 'Y-m-d')) ?>"><?= $e(View::date($item['published_at'], 'Y.m.d')) ?></time><?php endif ?>
</a>
</li>
<?php endforeach ?>
+16 -5
View File
@@ -1,29 +1,40 @@
<?php
use App\Content\Repository;
use App\Content\View;
$e = View::escape(...);
?>
<article class="section article-page" itemscope itemtype="https://schema.org/Article" data-enter>
<?php $card = $article['card']; ?>
<div class="wrap reading-wrap">
<a class="back-link" href="/articles">全部动态</a>
<header class="section-heading">
<div class="article-meta">
<a href="/articles/category/<?= $e($article['category']) ?>" itemprop="articleSection"><?= $e(Repository::CATEGORIES[$article['category']]) ?></a>
<time itemprop="datePublished" datetime="<?= $e(View::date($article['published_at'], DATE_ATOM)) ?>"><?= $e(View::date($article['published_at'])) ?></time>
<?php foreach ($article['categories'] as $key => $name): ?>
<a href="/articles/category/<?= $e($key) ?>" itemprop="articleSection"><?= $e($name) ?></a>
<?php endforeach ?>
<?php if ($article['published_at']): ?><time itemprop="datePublished" datetime="<?= $e(View::date($article['published_at'], DATE_ATOM)) ?>"><?= $e(View::date($article['published_at'])) ?></time><?php endif ?>
<meta itemprop="dateModified" content="<?= $e(View::date($article['updated_at'], DATE_ATOM)) ?>">
</div>
<h1 itemprop="headline"><?= $e($article['title']) ?></h1>
<?php if ($article['summary']): ?><p itemprop="description"><?= $e($article['summary']) ?></p><?php endif ?>
<span itemprop="author" itemscope itemtype="https://schema.org/Organization"><meta itemprop="name" content="<?= $e($site['name']) ?>"></span>
</header>
<?php if (!empty($card['image'])): ?>
<img class="article-cover" src="<?= $e($card['image']) ?>" alt="<?= $e($card['alt'] ?? '') ?>">
<?php endif ?>
<div class="rich prose" itemprop="articleBody">
<?php if (trim($articleHtml) !== ''): ?>
<?= $articleHtml ?>
<?php else: ?>
<p class="empty-state">此公告的原文暂不可用。</p>
<?php elseif (!$article['summary'] && empty($card['image']) && empty($card['url'])): ?>
<p class="empty-state">此文章的原文暂不可用。</p>
<?php endif ?>
</div>
<?php if (!empty($card['url']) || !empty($card['extra_url'])): ?>
<div class="actions">
<?php if (!empty($card['url'])): ?><a class="button button-primary" href="<?= $e($card['url']) ?>"><?= $e(($card['label'] ?? '') ?: '访问网站') ?></a><?php endif ?>
<?php if (!empty($card['extra_url'])): ?><a href="<?= $e($card['extra_url']) ?>"><?= $e(($card['extra_label'] ?? '') ?: '相关链接') ?></a><?php endif ?>
</div>
<?php endif ?>
<?php if ($article['tags']): ?>
<nav class="filter-nav" aria-label="文章标签">
<?php foreach ($article['tags'] as $tag): ?>
+57
View File
@@ -0,0 +1,57 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<footer class="site-footer" id="contact">
<div class="wrap">
<div class="footer-grid">
<div class="footer-company" itemscope itemtype="https://schema.org/Organization">
<?php if ($footer['logo'] !== ''): ?>
<a class="footer-logo" href="/" itemprop="url" aria-label="来笙 Laysense 首页">
<img src="<?= $e($footer['logo']) ?>" alt="<?= $e($footer['alt']) ?>" width="130" height="33" itemprop="logo" loading="lazy">
</a>
<?php endif ?>
<p itemprop="name"><?= $e($footer['name']) ?></p>
<?php if ($footer['address']): ?><address itemprop="address"><?= $e($footer['address']) ?></address><?php endif ?>
<?php if ($footer['email']): ?>
<a itemprop="email" href="mailto:<?= $e($footer['email']) ?>"><?= $e($footer['email']) ?></a>
<?php endif ?>
<p class="footer-payment-label">支持的付款方式</p>
<div class="payment-methods" aria-label="支持的付款方式">
<img src="/assets/original/payment-taobao.png" alt="淘宝" width="26" height="26" loading="lazy">
<img src="/assets/original/payment-alipay.png" alt="支付宝" width="26" height="26" loading="lazy">
<img src="/assets/original/payment-wechat.png" alt="微信支付" width="26" height="26" loading="lazy">
</div>
</div>
<nav class="footer-links" aria-label="页脚导航">
<?php foreach (['products', 'company', 'resources'] as $group): ?>
<?php if (!$footer[$group] && $footer[$group . '_title'] === '') { continue; } ?>
<div>
<?php if ($footer[$group . '_title'] !== ''): ?><h2 class="footer-label"><?= $e($footer[$group . '_title']) ?></h2><?php endif ?>
<?php if ($footer[$group]): ?>
<ul>
<?php foreach ($footer[$group] as [$url, $label]): ?><li><a href="<?= $e($url) ?>"><?= $e($label) ?></a></li><?php endforeach ?>
</ul>
<?php endif ?>
</div>
<?php endforeach ?>
</nav>
</div>
<div class="footer-meta">
<?php if ($footer['copyright']): ?><p><?= $e($footer['copyright']) ?></p><?php endif ?>
<?php if ($footer['email'] || $footer['phones']): ?>
<p>
<?php if ($footer['email']): ?><a href="mailto:<?= $e($footer['email']) ?>"><?= $e($footer['email']) ?></a><?php endif ?>
<?php if ($footer['phones']): ?>全球号码:
<?php foreach ($footer['phones'] as $index => [$url, $label]): ?>
<?= $index ? ' / ' : '' ?><a href="<?= $e($url) ?>"><?= $e($label) ?></a>
<?php endforeach ?>
<?php endif ?>
</p>
<?php endif ?>
<?php if ($footer['terms']): ?><p class="footer-terms"><?= $e($footer['terms']) ?></p><?php endif ?>
<?php if ($footer['registration']): ?><p><a href="https://beian.miit.gov.cn/"><?= $e($footer['registration']) ?></a></p><?php endif ?>
</div>
</div>
</footer>
+18 -46
View File
@@ -1,17 +1,21 @@
<?php
use App\Content\View;
use App\Content\Assets;
use App\Content\SiteDesign;
$e = View::escape(...);
$canonical = $path !== null ? View::absolute($path) : null;
$imageUrl = !empty($socialImage) ? $socialImage : '/assets/original/home-hero.webp';
$imageUrl = Assets::url($imageUrl, $cdn);
if (str_starts_with($imageUrl, '/')) {
$imageUrl = View::absolute($imageUrl);
}
$kind = in_array($page['slug'] ?? '', ['sc', 'shnu-sc'], true) ? 'service' : 'software';
$siteKind = $kind === 'service' ? 'other' : 'software';
$nav = [
['/', '首页'], ['/#product', '产品与服务'], ['/articles', '动态'], ['/#about', '关于来笙'],
];
$header = ($site['header'] ?? []) + SiteDesign::DEFAULT_HEADER;
$footer = SiteDesign::footer($site);
$nav = $header['links'];
$contact = $header['button'];
?>
<!doctype html>
<html lang="zh-CN" data-type="<?= $e($kind) ?>" data-buttons="solid" data-motion="on">
@@ -45,12 +49,14 @@ $nav = [
<script src="/assets/jquery-4.0.0.min.js" defer></script>
<script src="/assets/site.js" defer></script>
</head>
<body>
<body<?= $kind === 'service' ? ' class="copyright-service"' : '' ?>>
<a class="skip-link" href="#main-content">跳到内容</a>
<header class="masthead">
<div class="wrap masthead-inner">
<a class="wordmark" href="/" aria-label="来笙 Laysense 首页">
<img src="/assets/wordmark.webp" alt="Laysense 来笙" width="130" height="33">
<?php if ($header['logo'] !== ''): ?>
<img src="<?= $e($header['logo']) ?>" alt="<?= $e($header['alt']) ?>" width="130" height="33">
<?php else: ?>来笙 Laysense<?php endif ?>
</a>
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="primary-navigation" hidden>
<span></span><span></span><span class="sr-only">菜单</span>
@@ -60,50 +66,16 @@ $nav = [
<?php $current = $url === $path || ($url === '/articles' && str_starts_with($path ?? '', '/articles')); ?>
<a href="<?= $e($url) ?>" <?= $current ? 'aria-current="page"' : '' ?>><?= $e($label) ?></a>
<?php endforeach ?>
<a class="mobile-contact" href="#contact">联系来笙</a>
<?php if ($contact): ?>
<a class="mobile-contact" href="<?= $e($contact[0]) ?>"><?= $e($contact[1]) ?></a>
<?php endif ?>
</nav>
<a class="button button-outline masthead-action" href="#contact">联系来笙</a>
<?php if ($contact): ?>
<a class="button button-outline masthead-action" href="<?= $e($contact[0]) ?>"><?= $e($contact[1]) ?></a>
<?php endif ?>
</div>
</header>
<main id="main-content" tabindex="-1"><?= $content ?></main>
<footer class="site-footer" id="contact">
<div class="wrap">
<div class="footer-grid">
<div class="footer-company" itemscope itemtype="https://schema.org/Organization">
<a href="/" itemprop="url" aria-label="来笙 Laysense 首页">
<img src="/assets/wordmark.webp" alt="来笙 Laysense" width="130" height="33" itemprop="logo" loading="lazy">
</a>
<p itemprop="name"><?= $e($site['name']) ?></p>
<address itemprop="address"><?= $e($site['address']) ?></address>
<a itemprop="email" href="mailto:<?= $e($site['email']) ?>"><?= $e($site['email']) ?></a>
<div class="payment-methods" aria-label="支持的付款方式">
<img src="/assets/original/payment-taobao.png" alt="淘宝" width="26" height="26" loading="lazy">
<img src="/assets/original/payment-alipay.png" alt="支付宝" width="26" height="26" loading="lazy">
<img src="/assets/original/payment-wechat.png" alt="微信支付" width="26" height="26" loading="lazy">
</div>
</div>
<div>
<p class="footer-label">产品与服务</p>
<a href="/pagepan">PAGEPAN 小飞页</a>
<a href="/highspeaker">HighSpeaker DNS</a>
<a href="/sc">软著代理服务</a>
<a href="/shnu-sc">SHNU 学生软著服务</a>
</div>
<div>
<p class="footer-label">公司</p>
<a href="/#about">关于来笙</a>
<a href="/articles">来笙动态</a>
<a href="https://git.laysense.com">Laysense Git</a>
<a href="https://www.layso.de">LaySo</a>
</div>
</div>
<div class="footer-meta">
<p><?= $e($site['copyright']) ?> 2024–<?= $e(date('Y')) ?></p>
<p>全球号码 <a href="tel:+16699004532">+1 (669) 900 4532</a> / <a href="tel:+85257012856">+852 5701 2856</a></p>
<a href="https://beian.miit.gov.cn/"><?= $e($site['registration']) ?></a>
<p class="footer-terms"><?= $e($site['terms']) ?></p>
</div>
</div>
</footer>
<?= View::fragment('footer', ['footer' => $footer]) ?>
</body>
</html>
+43
View File
@@ -0,0 +1,43 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<section class="section network" aria-label="支持项目与合作伙伴">
<div class="wrap">
<?php if (!$standalone): ?>
<div class="section-heading inline-heading">
<h2>支持项目与合作伙伴</h2>
<a class="button button-outline" href="/network">查看全部</a>
</div>
<?php endif ?>
<?php foreach ($network as $slug => $group): ?>
<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 (!$group['articles']): ?><p class="empty-state">暂无已发布条目。</p><?php endif ?>
<ul class="network-list">
<?php foreach ($group['articles'] as $item): ?>
<?php
// 优先跳卡片配置的网址;没有网址时,只有文章本身有内容才回退到文章页,否则不渲染链接。
$card = $item['card'];
$articlePath = '/articles/' . $item['slug'];
$hasDetail = $item['body'] !== '' || $item['summary'] !== '';
$target = ($card['url'] ?? '') ?: ($hasDetail ? $articlePath : '');
?>
<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 && !empty($card['url']) && $hasDetail): ?>
<a class="network-detail" href="<?= $e($articlePath) ?>">查看详情</a>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
</div>
<?php endforeach ?>
</div>
</section>
+10
View File
@@ -0,0 +1,10 @@
<?php
use App\Content\View;
?>
<section class="section catalog-hero">
<div class="wrap">
<nav class="breadcrumbs" aria-label="面包屑"><a href="/">首页</a><span aria-hidden="true">/</span><span aria-current="page">支持项目与合作伙伴</span></nav>
<h1>支持项目与合作伙伴</h1>
</div>
</section>
<?= View::fragment('network-groups', ['network' => $network, 'standalone' => true]) ?>
+40 -50
View File
@@ -5,9 +5,12 @@ 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 . '"' : '';
?>
<section class="hero hero-<?= $e($page['slug']) ?>" id="home" data-enter>
<div class="wrap hero-inner">
<div class="wrap hero-inner<?= $page['image'] === '' ? ' hero-text-only' : '' ?>">
<div class="hero-copy">
<?php if (!$home): ?>
<nav class="breadcrumbs" aria-label="面包屑" itemscope itemtype="https://schema.org/BreadcrumbList">
@@ -17,30 +20,44 @@ $service = in_array($page['slug'], ['sc', 'shnu-sc'], true);
</span>
<span class="crumb-divider" aria-hidden="true">/</span>
<span itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
<a itemprop="item" href="/<?= $e($page['slug']) ?>" aria-current="page"><span itemprop="name"><?= $e($page['name']) ?></span></a>
<a itemprop="item" href="/<?= $e($page['slug']) ?>" aria-current="page"><span itemprop="name"<?= $field('name') ?>><?= $e($page['name']) ?></span></a>
<meta itemprop="position" content="2">
</span>
</nav>
<?php else: ?>
<p class="overline hero-label">上海来笙信息科技有限公司</p>
<p class="overline hero-label"><?= $e($site['footer']['name'] ?? $site['name']) ?></p>
<?php endif ?>
<h1><?= $e($page['heading']) ?><?php if ($page['accent'] !== ''): ?><br><span><?= $e($page['accent']) ?></span><?php endif ?></h1>
<p class="hero-lead"><?= $e($page['lead']) ?></p>
<div class="actions hero-actions">
<?php foreach ($page['actions'] as $index => [$url, $label]): ?>
<a class="button <?= $index ? 'button-outline' : 'button-primary' ?>" href="<?= $e($url) ?>"><?= $e($label) ?></a>
<h1<?= isset($alignments['heading']) ? ' class="' . trim(View::alignmentClass($alignments['heading'])) . '"' : '' ?><?= $alignField('heading') ?>><span class="hero-heading-primary"<?= $field('heading') ?>><?= $e($page['heading']) ?></span><?php if ($canvas): ?><span class="studio-accent"<?= $field('accent') ?>><?= $e($page['accent']) ?></span><?php elseif ($page['accent'] !== ''): ?><br><span><?= $e($page['accent']) ?><?php if ($home): ?><span class="home-cursor" aria-hidden="true">_</span><?php endif ?></span><?php elseif ($home): ?><span class="home-cursor" aria-hidden="true">_</span><?php endif ?></h1>
<p class="hero-lead<?= View::alignmentClass($alignments['lead'] ?? null) ?>"<?= $field('lead') ?><?= $alignField('lead') ?>><?= $e($page['lead']) ?></p>
<div class="actions hero-actions<?= View::alignmentClass($alignments['actions'] ?? null) ?>"<?= $alignField('actions') ?>>
<?php foreach ($canvas ? array_pad($page['actions'], 2, ['', '']) : $page['actions'] as $index => [$url, $label]): ?>
<a class="button <?= $index ? 'button-outline' : 'button-primary' ?>" href="<?= $e($url) ?>"<?= $canvas ? ' data-studio-action="' . ($index + 1) . '"' : '' ?><?= $label === '' && $url === '' ? ' hidden' : '' ?>><?= $e($label) ?></a>
<?php endforeach ?>
</div>
</div>
<?php if ($page['image'] !== ''): ?>
<div class="hero-visual <?= $home ? 'hero-illustration' : ($service ? 'hero-service-art' : 'app-frame') ?>" data-visual>
<img src="<?= $e($page['image']) ?>" alt="<?= $e($page['alt']) ?>" width="1448" height="1086" fetchpriority="high">
<?php if ($canvas || $page['image'] !== ''): ?>
<div class="hero-visual <?= $home ? 'hero-illustration' : ($service ? 'hero-service-art' : 'app-frame') ?><?= $page['image_scale'] ? ' studio-media-' . $e($page['image_scale']) : '' ?><?= View::alignmentClass($alignments['image'] ?? null) ?>" data-visual<?= $alignField('image') ?><?= $page['image'] === '' ? ' hidden' : '' ?>>
<img<?= $page['image'] === '' ? '' : ' src="' . $e($page['image']) . '"' ?> alt="<?= $e($page['alt']) ?>" width="1448" height="1086" fetchpriority="high"<?= $canvas ? ' data-studio-hero-image' : '' ?>>
<?php if ($home && !$canvas && $page['image'] === '/assets/original/home-hero.webp'): ?>
<svg class="home-pipe-flow" viewBox="0 0 640 480" aria-hidden="true" focusable="false">
<defs>
<path id="hero-pipe-tower" pathLength="100" d="M174 347 241 312 Q246 310 246 305 L246 299 Q246 295 252 293 L273 282"/>
<path id="hero-pipe-disk" pathLength="100" d="M409 282 428 293 Q433 296 433 300 L433 304 Q433 307 438 309 L500 337"/>
<path id="hero-pipe-node" pathLength="100" d="M119 201 125 205 Q129 207 129 212 L129 214 Q130 217 134 219 L190 243"/>
<path id="hero-pipe-chart" pathLength="100" d="M443 226 471 213 Q478 208 483 209 L488 207 Q492 205 492 200 L492 182"/>
</defs>
<g class="home-pipe-route"><use href="#hero-pipe-tower"/><use href="#hero-pipe-tower"/></g>
<g class="home-pipe-route"><use href="#hero-pipe-disk"/><use href="#hero-pipe-disk"/></g>
<g class="home-pipe-route"><use href="#hero-pipe-node"/><use href="#hero-pipe-node"/></g>
<g class="home-pipe-route"><use href="#hero-pipe-chart"/><use href="#hero-pipe-chart"/></g>
</svg>
<?php endif ?>
</div>
<?php endif ?>
</div>
<?php if ($home): ?>
<div class="wrap hero-directory">
<span class="overline">产品与服务</span>
<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>
@@ -48,8 +65,8 @@ $service = in_array($page['slug'], ['sc', 'shnu-sc'], true);
</div>
<?php endif ?>
</section>
<?php if ($page['quicklinks']): ?>
<nav class="section-nav" aria-label="本页目录">
<?php if ($canvas || $page['quicklinks']): ?>
<nav class="section-nav" aria-label="本页目录"<?= $canvas ? ' data-studio-navigation' : '' ?><?= !$page['quicklinks'] ? ' hidden' : '' ?>>
<div class="wrap section-nav-inner">
<?php foreach ($page['quicklinks'] as [$url, $label]): ?>
<a href="<?= $e($url) ?>"><?= $e($label) ?></a>
@@ -58,41 +75,14 @@ $service = in_array($page['slug'], ['sc', 'shnu-sc'], true);
</nav>
<?php endif ?>
<?php foreach ($page['sections'] as $section): ?>
<?= View::fragment('section', ['section' => $section, 'moment' => $home && $section['key'] === 'about']) ?>
<?= View::fragment('section', ['section' => $section, 'moment' => $home && $section['key'] === 'about', 'canvas' => $canvas]) ?>
<?php endforeach ?>
<?php if ($home): ?>
<section class="section home-news" id="blog" aria-labelledby="updates-heading">
<div class="wrap">
<div class="section-heading inline-heading">
<h2 id="updates-heading">来笙动态</h2>
<a class="button button-outline" href="/articles">查看全部动态</a>
</div>
<?= View::fragment('article-list', ['articles' => $articles]) ?>
</div>
</section>
<?php if ($page['partners']): ?>
<section class="section network" aria-labelledby="network-heading">
<div class="wrap">
<div class="section-heading"><h2 id="network-heading">支持项目与合作伙伴</h2></div>
<?php foreach (['来笙支持项目' => 'supported-projects', '来笙合作伙伴' => 'partners'] as $group => $id): ?>
<div class="network-group" id="<?= $e($id) ?>">
<h3><?= $e($group) ?></h3>
<ul class="network-list">
<?php foreach ($page['partners'] as $partner): ?>
<?php if ($partner['group'] !== $group) { continue; } ?>
<li>
<?php if ($partner['url']): ?><a href="<?= $e($partner['url']) ?>"><?php else: ?><div><?php endif ?>
<?php if ($partner['image']): ?>
<img src="<?= $e($partner['image']) ?>" alt="" loading="lazy" width="76" height="28">
<?php endif ?>
<span><?= $e($partner['name']) ?></span>
<?php if ($partner['url']): ?></a><?php else: ?></div><?php endif ?>
</li>
<?php endforeach ?>
</ul>
</div>
<?php endforeach ?>
</div>
</section>
<?php endif ?>
<?php if ($canvas): ?>
<template data-studio-section-end><?= View::fragment('section', [
'section' => ['style' => 'plain', 'key' => 'new', 'version' => null, 'title' => '', 'lead' => '', 'body' => ''],
'moment' => false, 'canvas' => true,
]) ?></template>
<?php endif ?>
<?php if ($home): ?>
<?= View::fragment('network-groups', ['network' => $network, 'standalone' => false]) ?>
<?php endif ?>
+13 -4
View File
@@ -2,13 +2,22 @@
use App\Content\View;
$e = View::escape(...);
$canvas ??= false;
$body = $section['body'];
$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>') {
$body = '';
}
?>
<section class="section section-<?= $e($section['style']) ?>" id="<?= $e($section['key']) ?>" aria-labelledby="heading-<?= $e($section['key']) ?>" <?= $moment ? 'data-moment="iris-opens"' : '' ?>>
<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'])) . '"' : '' ?>>
<div class="wrap">
<div class="section-heading">
<h2 id="heading-<?= $e($section['key']) ?>"><?= $e($section['title']) ?></h2>
<?php if ($section['lead']): ?><p><?= $e($section['lead']) ?></p><?php endif ?>
<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 ?>
</div>
<div class="rich"><?= $section['body'] ?></div>
<?php if (!empty($section['articleFeed'])): ?>
<?= View::fragment('article-feed', ['groups' => $section['articleFeed'], 'sectionKey' => $section['key'], 'archivePath' => $section['archivePath']]) ?>
<?php endif ?>
<?php if ($canvas || $body !== ''): ?><div class="rich<?= !empty($section['articleFeed']) ? ' article-feed-note' : '' ?>"<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $body ?></div><?php endif ?>
</div>
</section>
+48
View File
@@ -0,0 +1,48 @@
<?php
use App\Content\Html;
use App\Content\View;
$e = View::escape(...);
?>
<section class="section catalog-hero">
<div class="wrap">
<nav class="breadcrumbs" aria-label="面包屑"><a href="/">首页</a><span aria-hidden="true">/</span><span aria-current="page">产品与服务</span></nav>
<h1>产品与服务</h1>
<p>自托管建站、开源智能 DNS 与软件著作权代理服务。</p>
</div>
</section>
<section class="section catalog-listing" aria-label="产品与服务目录">
<div class="wrap">
<?php if (!$products): ?><p class="empty-state">暂无可查看的产品和服务。</p><?php endif ?>
<div class="catalog-grid">
<?php foreach ($products as $product): ?>
<?php
// 目录卡片指向卡片自己配置的网址;没有网址时,只有文章本身有内容才回退到文章页。
$card = $product['card'];
$hasDetail = $product['body'] !== '' || $product['summary'] !== '';
$target = ($card['url'] ?? '') ?: ($hasDetail ? '/articles/' . $product['slug'] : '');
?>
<article class="catalog-card">
<?php if (!empty($card['image'])): ?>
<div class="catalog-image"><img src="<?= $e($card['image']) ?>" alt="<?= $e($card['alt'] ?? '') ?>" loading="lazy"></div>
<?php endif ?>
<div class="catalog-content">
<?php if (!empty($card['category_label'])): ?><p class="overline"><?= $e($card['category_label']) ?></p><?php endif ?>
<h2><?php if ($target !== ''): ?><a href="<?= $e($target) ?>"><?= $e($product['title']) ?></a><?php else: ?><?= $e($product['title']) ?><?php endif ?></h2>
<?php if ($product['summary']): ?>
<p><?= $e($product['summary']) ?></p>
<?php else: ?>
<div class="rich"><?= Html::articleBody($product) ?></div>
<?php endif ?>
<?php if ($target !== '' || !empty($card['extra_url'])): ?>
<div class="actions">
<?php if ($target !== ''): ?><a class="button button-primary" href="<?= $e($target) ?>"><?= $e(($card['label'] ?? '') ?: '了解详情') ?></a><?php endif ?>
<?php if (!empty($card['extra_url'])): ?><a href="<?= $e($card['extra_url']) ?>"><?= $e(($card['extra_label'] ?? '') ?: '相关链接') ?></a><?php endif ?>
</div>
<?php endif ?>
</div>
</article>
<?php endforeach ?>
</div>
</div>
</section>
+9
View File
@@ -0,0 +1,9 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<div class="asset-field">
<label><?= $e($label) ?><input name="<?= $e($name) ?>" value="<?= $e($value) ?>" maxlength="1000"></label>
<button type="button" class="button button-outline" data-asset-pick="<?= $e($name) ?>" data-asset-type="image/">媒体库</button>
</div>
+50
View File
@@ -0,0 +1,50 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<header class="admin-heading"><div><h1>媒体库</h1><p>统一查找并引用静态文件、图片、图标和音视频。</p></div></header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/media" enctype="multipart/form-data">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<div class="form-grid">
<label>文件<input type="file" name="file" accept="image/*,video/*,audio/*,.pdf,.woff,.woff2" required>
<small>支持常见图片、SVG 图标、音视频、PDF、WOFF/WOFF2,单文件最大 64 MB。</small>
</label>
<label>资源名称<input name="label" maxlength="160" placeholder="默认使用文件名"></label>
</div>
<div class="form-submit"><button type="submit" class="button button-primary">上传文件</button></div>
</form>
<section class="admin-panel media-library" data-media-library aria-labelledby="library-heading">
<h2 id="library-heading">资源列表</h2>
<div class="form-grid">
<label>搜索<input type="search" data-library-query placeholder="搜索名称或路径"></label>
<label>类型<select data-library-type><option value="">全部资源</option><option value="image/">图片与图标</option><option value="video/">视频</option><option value="audio/">音频</option><option value="other">其他文件</option></select></label>
</div>
<p data-library-count role="status"></p>
<div class="media-grid">
<?php foreach ($files as $file): ?>
<article class="media-card" data-library-card data-mime="<?= $e($file['mime']) ?>" data-search="<?= $e($file['label'] . ' ' . $file['url']) ?>">
<?php if (str_starts_with($file['mime'], 'image/')): ?>
<img src="<?= $e($file['url']) ?>" alt="" loading="lazy">
<?php else: ?>
<p class="media-file-type"><?= $e(strtolower(pathinfo($file['url'], PATHINFO_EXTENSION))) ?></p>
<?php endif ?>
<h3><?= $e($file['label']) ?></h3>
<small><?= $e((string) max(1, ceil($file['size'] / 1024))) ?> KB · <?= $file['name'] === '' ? '项目文件' : ($file['archived'] ? '已归档' : '上传文件') ?></small>
<div class="actions"><a href="<?= $e($file['url']) ?>" target="_blank" rel="noopener">打开</a><button type="button" class="button button-outline" data-copy-asset="<?= $e($file['url']) ?>">复制路径</button></div>
<?php if ($file['name'] !== ''): ?>
<details><summary>管理文件</summary>
<form class="admin-form" method="post" action="/admin/media/<?= $e($file['name']) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<label>名称<input name="label" value="<?= $e($file['label']) ?>" maxlength="160" required></label>
<label class="media-archive"><input type="checkbox" name="archived" value="1" <?= $file['archived'] ? 'checked' : '' ?>>归档</label>
<small>归档从选取器隐藏文件,已有链接仍可访问。</small>
<button type="submit" class="button button-outline">保存</button>
</form>
</details>
<?php endif ?>
</article>
<?php endforeach ?>
</div>
</section>
+16
View File
@@ -0,0 +1,16 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<a class="back-link" href="/admin">返回页面</a>
<header class="admin-heading"><h1>新建页面</h1></header>
<?= View::fragment('admin-feedback', ['error' => $error, 'saved' => false]) ?>
<form class="admin-form admin-panel" method="post" action="/admin/new-page">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<label>页面名称<input name="name" maxlength="100" value="<?= $e($name) ?>" required></label>
<label>网址标识<input name="slug" maxlength="70" value="<?= $e($slug) ?>" pattern="[a-z0-9]+(-[a-z0-9]+)*" placeholder="my-page" required>
<small>创建后为草稿。可在编辑画布中预览,并自行发布。</small>
</label>
<div class="form-submit"><button type="submit" class="button button-primary">创建草稿</button></div>
</form>
+60
View File
@@ -0,0 +1,60 @@
<?php
use App\Content\SiteDesign;
use App\Content\View;
$e = View::escape(...);
?>
<header class="admin-heading"><h1><?= $e($title) ?></h1><a class="button button-outline" href="/" target="_blank" rel="noopener">查看公开网站</a></header>
<nav class="filter-nav" aria-label="网站设置">
<?php foreach (['header' => '页头', 'footer' => '页脚', 'cdn' => 'CDN'] as $key => $text): ?>
<a href="/admin/settings/<?= $key ?>" <?= $key === $part ? 'aria-current="page"' : '' ?>><?= $text ?></a>
<?php endforeach ?>
</nav>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel settings-form" method="post" action="/admin/settings/<?= $e($part) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($revision) ?>">
<?php if ($part === 'cdn'): ?>
<label>CDN 源站地址<input name="origin" type="url" value="<?= $e($config['origin']) ?>" placeholder="https://cdn.laysense.cn">
<small>留空时直接从站点提供资源。配置后,公开页面中的 /assets/ 路径会改用此域名。</small>
</label>
<?php else: ?>
<?= View::fragment('studio-asset-field', ['label' => '站点标志', 'name' => 'logo', 'value' => $config['logo']]) ?>
<label>标志替代文本<input name="alt" value="<?= $e($config['alt']) ?>" maxlength="200"></label>
<?php if ($part === 'header'): ?>
<label>主导航<textarea name="links" rows="6" placeholder="产品与服务 | /services"><?= $e(SiteDesign::linkText($config['links'])) ?></textarea>
<small>每行填写「文案 | 链接」,按输入顺序展示。</small>
</label>
<label>右侧按钮<input name="button" value="<?= $e($config['button'] ? SiteDesign::linkText([$config['button']]) : '') ?>" placeholder="联系来笙 | #contact"></label>
<?php else: ?>
<div class="form-grid">
<?php foreach (['name' => '公司名称', 'address' => '联系地址', 'email' => '邮箱', 'registration' => '备案号', 'copyright' => '版权信息'] as $key => $text): ?>
<label><?= $text ?><input name="<?= $key ?>" value="<?= $e($config[$key] ?? '') ?>" <?= $key === 'name' ? 'required' : '' ?>></label>
<?php endforeach ?>
</div>
<label>联系号码<textarea name="phones" rows="3"><?= $e(SiteDesign::linkText($config['phones'])) ?></textarea>
<small>每行填写「显示号码 | tel:号码」。</small>
</label>
<div class="form-grid">
<?php foreach (['products' => '第一列', 'company' => '第二列', 'resources' => '第三列'] as $key => $text): ?>
<div class="admin-form">
<label><?= $text ?>标题<input name="<?= $key ?>_title" value="<?= $e($config[$key . '_title']) ?>"></label>
<label><?= $text ?>链接<textarea name="<?= $key ?>" rows="6"><?= $e(SiteDesign::linkText($config[$key])) ?></textarea>
<small>每行填写「文案 | 链接」。</small>
</label>
</div>
<?php endforeach ?>
</div>
<label>页脚备注<textarea name="terms" rows="2"><?= $e($config['terms'] ?? '') ?></textarea></label>
<?php endif ?>
<?php endif ?>
<div class="form-submit"><button class="button button-primary" type="submit">保存设置</button></div>
</form>
<?php if ($part === 'footer'): ?>
<form method="post" action="/admin/settings/footer">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($revision) ?>">
<input type="hidden" name="operation" value="restore-footer">
<button class="button button-outline" type="submit" data-confirm="用原站的页脚内容覆盖当前页脚设置?">恢复原站页脚</button>
</form>
<?php endif ?>
+68
View File
@@ -0,0 +1,68 @@
<?php
use App\Content\BlockTemplates;
use App\Content\View;
$e = View::escape(...);
?>
<div class="studio-presets" data-canvas-presets>
<details class="studio-element-library">
<summary>基础元素</summary>
<div role="group" aria-label="添加基础元素">
<?php foreach (BlockTemplates::ELEMENTS as $key => $element): ?>
<?php [$label, $markup, $mime] = array_pad($element, 3, ''); ?>
<button type="button" disabled data-canvas-element="<?= $e($key) ?>"
<?php if ($mime): ?>data-element-mime="<?= $e($mime) ?>"<?php endif ?>
aria-label="插入<?= $e($label) ?>"><?= $e($label) ?></button>
<template data-element="<?= $e($key) ?>"><?= $markup ?></template>
<?php endforeach ?>
</div>
<p class="field-note" data-element-status role="status">选中画布正文后插入。</p>
</details>
<label class="studio-template-search">搜索模板<input type="search" data-template-search placeholder="按名称或分类搜索" autocomplete="off"></label>
<div class="studio-template-filters" role="group" aria-label="模板分类">
<button type="button" data-template-filter="" aria-pressed="true">全部</button>
<?php foreach (BlockTemplates::GROUPS as $group => [$category]): ?>
<button type="button" data-template-filter="<?= $e($group) ?>" aria-pressed="false"><?= $e($category) ?></button>
<?php endforeach ?>
</div>
<label class="studio-insert-mode"><input type="checkbox" data-template-inline> 插入当前正文</label>
<p class="field-note" data-template-status role="status"></p>
<ul class="studio-pending" data-template-pending hidden></ul>
<p class="field-note" data-template-empty hidden role="status">没有找到匹配的模板。</p>
<div class="studio-template-groups">
<?php foreach (BlockTemplates::GROUPS as $group => [$category, $templates]): ?>
<section class="studio-template-group" data-template-group="<?= $e($group) ?>" aria-labelledby="studio-template-<?= $e($group) ?>">
<h3 id="studio-template-<?= $e($group) ?>"><?= $e($category) ?></h3>
<div class="studio-template-cards">
<?php foreach ($templates as $preset => [$label, $markup]): ?>
<article class="studio-template-card" data-template-card data-template-search-text="<?= $e($label . ' ' . $category . ' ' . $preset) ?>">
<button type="button" class="studio-template-image" data-template-preview="<?= $e($preset) ?>" data-template-title="<?= $e($label) ?>"
aria-label="预览<?= $e($label) ?>模板">
<img src="/assets/template-previews/<?= $e($preset) ?>.webp" alt="" width="768" height="480" loading="lazy">
</button>
<div class="studio-template-meta">
<span><?= $e($label) ?></span>
<button type="button" class="button button-outline" disabled data-canvas-template="<?= $e($preset) ?>"
data-template-title="<?= $e($label) ?>" aria-label="添加<?= $e($label) ?>模板">添加</button>
</div>
<template data-preset="<?= $e($preset) ?>"><?= $markup ?></template>
</article>
<?php endforeach ?>
</div>
</section>
<?php endforeach ?>
</div>
<div class="studio-template-peek" data-template-peek aria-hidden="true" hidden>
<img alt="">
<p></p>
</div>
<dialog class="media-picker studio-template-dialog" data-template-dialog aria-labelledby="studio-template-preview-title">
<header class="admin-heading compact">
<h2 id="studio-template-preview-title"></h2>
<button type="button" class="button button-outline" data-template-close>关闭</button>
</header>
<img alt="" width="768" height="480">
<div class="actions"><button type="button" class="button button-primary" data-template-use>添加到画布</button></div>
</dialog>
</div>
+1
View File
@@ -5,6 +5,7 @@
"require": {
"php": "^8.2",
"ext-dom": "*",
"ext-fileinfo": "*",
"ext-mbstring": "*",
"ext-pdo_sqlite": "*",
"league/commonmark": "^2.8",
Generated
+2 -1
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "c9d25a83ed6ca15405ef7765391c2f0d",
"content-hash": "b550e1c39f23f72dcd3480e7d01e9b56",
"packages": [
{
"name": "dflydev/dot-access-data",
@@ -1098,6 +1098,7 @@
"platform": {
"php": "^8.2",
"ext-dom": "*",
"ext-fileinfo": "*",
"ext-mbstring": "*",
"ext-pdo_sqlite": "*"
},
+17 -2
View File
@@ -2,16 +2,21 @@
use App\Controller\AdminController;
use App\Controller\SiteController;
use App\Controller\StudioController;
use App\Controller\MediaController;
use App\Content\View;
use support\Request;
use Webman\Route;
Route::disableDefaultRoute();
Route::get('/', [SiteController::class, 'home']);
Route::get('/{slug:pagepan|highspeaker|sc|shnu-sc}', [SiteController::class, 'page']);
Route::get('/services', [SiteController::class, 'services']);
Route::get('/network', [SiteController::class, 'network']);
Route::get('/assets/uploads/{name:[a-f0-9]{32}\.[a-z0-9]+}', [MediaController::class, 'file']);
Route::get('/articles', [SiteController::class, 'archive']);
Route::get('/articles/category/{category:announcement|news|product}', [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']);
@@ -24,11 +29,21 @@ Route::add(['GET', 'POST'], '/admin/login', [AdminController::class, 'login']);
Route::post('/admin/logout', [AdminController::class, 'logout']);
Route::add(['GET', 'POST'], '/admin/password', [AdminController::class, 'password']);
Route::get('/admin', [AdminController::class, 'dashboard']);
Route::add(['GET', 'POST'], '/admin/article-categories', [AdminController::class, 'articleCategories']);
Route::get('/admin/articles', [AdminController::class, 'articles']);
Route::add(['GET', 'POST'], '/admin/articles/new', [AdminController::class, 'article']);
Route::add(['GET', 'POST'], '/admin/articles/{id:[0-9]+}', [AdminController::class, 'article']);
Route::add(['GET', 'POST'], '/admin/new-page', [StudioController::class, 'newPage']);
Route::get('/admin/pages/{slug:[a-z0-9-]+}/preview', [StudioController::class, 'previewPage']);
Route::post('/admin/page-blocks/{slug:[a-z0-9-]+}', [StudioController::class, 'blocks']);
Route::add(['GET', 'POST'], '/admin/settings/{part:header|footer|cdn}', [StudioController::class, 'settings']);
Route::add(['GET', 'POST'], '/admin/media', [StudioController::class, 'media']);
Route::get('/admin/media/options', [StudioController::class, 'mediaOptions']);
Route::post('/admin/media/{name:[a-f0-9]{32}\.[a-z0-9]+}', [StudioController::class, 'mediaMeta']);
Route::add(['GET', 'POST'], '/admin/pages/{slug:[a-z0-9-]+}', [AdminController::class, 'page']);
Route::add(['GET', 'POST'], '/admin/pages/{slug:[a-z0-9-]+}/{key:[a-z0-9-]+}', [AdminController::class, 'section']);
Route::post('/admin/preview', [AdminController::class, 'preview']);
Route::get('/{slug:[a-z0-9-]+}', [SiteController::class, 'page']);
Route::fallback(static fn (Request $request) => (new SiteController())->missing($request));
+1 -1
View File
@@ -6,5 +6,5 @@ return [
'stdout_file' => runtime_path() . '/logs/stdout.log',
'log_file' => runtime_path() . '/logs/workerman.log',
'stop_timeout' => 4,
'max_package_size' => 2 * 1024 * 1024,
'max_package_size' => 66 * 1024 * 1024,
];
+1 -1
View File
@@ -1,3 +1,3 @@
<?php
return ['enable' => true, 'middleware' => []];
return ['enable' => true, 'middleware' => [App\Middleware\PublicAssets::class]];
+193
View File
@@ -53,3 +53,196 @@
.password-form { max-width: 37rem; }
.admin-form button:disabled, .admin-bar button:disabled { cursor: progress; opacity: .65; }
.admin-form .ajax-feedback { margin: 0; }
.studio-frame-window { position: relative; height: min(67vh, 39rem); overflow: hidden; margin-bottom: .8rem; border: 1px solid var(--line); border-radius: .55rem; background: var(--paper); }
.studio-frame-window iframe { display: block; width: 100%; height: 100%; border: 0; background: white; }
.studio-frame-window.has-scaled-preview iframe { position: absolute; top: 0; transform-origin: 0 0; }
.studio-canvas-toolbar { margin-bottom: .55rem; }
.studio-canvas-toolbar button:disabled { opacity: .5; cursor: default; }
.preview-selector { display: flex; gap: .35rem; flex-wrap: wrap; }
.preview-selector [aria-pressed="true"] { background: var(--accent-light); color: var(--accent-deep); }
.studio-inspector details label { margin-top: .7rem; }
.studio-blocks form, .studio-block-actions { display: flex; align-items: center; flex-wrap: wrap; gap: .32rem; }
.studio-blocks .button { padding-inline: .65rem; }
.studio-block-add { margin-top: 1.25rem; }
.studio-rich { min-height: 15rem; max-width: 100%; overflow-x: auto; padding: 1rem; background: #fff; border: 1px solid var(--line); border-radius: .55rem; }
.studio-rich:focus { outline: 2px solid var(--accent); outline-offset: 2px; }
.studio-rich details { margin-bottom: .5rem; }
.studio-rich img, .studio-rich video { max-width: 100%; height: auto; }
.asset-field { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: end; gap: .55rem; }
.settings-form { max-width: 54rem; }
.media-grid, .picker-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr)); gap: .8rem; }
.media-card, .picker-item { min-width: 0; border: 1px solid var(--line); border-radius: .65rem; background: white; padding: .75rem; overflow-wrap: anywhere; }
.media-card > img, .picker-item img, .media-file-type { height: 6rem; width: 100%; object-fit: contain; background: var(--paper); border-radius: .45rem; margin-bottom: .7rem; }
.media-card .media-file-type { display: grid; place-items: center; font-size: 1.1rem; text-transform: uppercase; }
.media-card h3 { font-size: 1rem; margin-bottom: 0; }
.media-card small { color: var(--muted); }
.media-card .actions { margin: .45rem 0; }
.media-card .button { padding-inline: .55rem; }
.media-card .media-archive { display: flex; align-items: center; }
.media-card .media-archive input { width: auto; min-height: 0; }
.media-picker { max-width: min(92vw, 52rem); max-height: 86vh; width: 100%; padding: 1.25rem; border: 1px solid var(--line); border-radius: var(--radius); color: var(--ink); }
.media-picker.canvas-properties { max-width: min(92vw, 32rem); }
.media-picker::backdrop { background: #101c3488; }
.media-picker label { display: grid; gap: .35rem; }
.media-picker input { padding: .55rem .75rem; border: 1px solid var(--line); border-radius: .4rem; }
.picker-grid { max-height: 50vh; overflow: auto; padding: .25rem; }
.picker-item { text-align: left; min-height: 44px; }
.picker-item:hover { border-color: var(--accent); }
@media (max-width: 65rem) {
}
.admin-wrap.admin-wide { width: calc(100% - clamp(1rem, 3vw, 3rem)); }
.studio-layout {
display: grid;
align-items: start;
grid-template-columns: minmax(12rem, 15rem) minmax(0, 1fr);
grid-template-areas: "library workspace" "library settings";
gap: .9rem;
}
.studio-library { grid-area: library; position: sticky; z-index: 3; top: .75rem; max-height: calc(100vh - 1.5rem); overflow: auto; }
.studio-library h2 { font-size: 1.05rem; margin-bottom: .7rem; }
.studio-workspace { grid-area: workspace; min-width: 0; }
.studio-inspector { grid-area: settings; }
.studio-workspace .studio-preview { padding: clamp(.55rem, 1.25vw, 1rem); }
.studio-workspace .studio-frame-window { height: max(34rem, calc(100dvh - 16rem)); }
.studio-workspace .studio-preview h2 { font-size: 1.2rem; }
.studio-presets { display: grid; gap: .4rem; }
.studio-library .studio-layers button:not(.button), .studio-pending button {
width: 100%;
min-height: 2.75rem;
padding: .55rem .75rem;
margin: 0;
border: 1px solid var(--line);
border-radius: .45rem;
background: var(--white);
color: var(--ink);
text-align: left;
}
.studio-library button:not(.button):hover { border-color: var(--accent); color: var(--accent); }
.studio-insert-mode { margin-block: .45rem .15rem; font-size: .875rem; }
.studio-pending { padding: 0; margin: 0; list-style: none; }
.studio-pending li + li { margin-top: .3rem; }
.studio-presets [role="status"]:empty { margin: 0; }
.studio-layers { border-top: 1px solid var(--line); margin-top: .85rem; padding-top: .55rem; }
.studio-layers summary { cursor: pointer; font-weight: 620; }
.studio-layers[open] > summary { margin-bottom: .55rem; }
.studio-library .studio-layers > button + button { margin-top: .3rem; }
.studio-layers .studio-blocks li { display: grid; gap: .4rem; }
.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-element-tools {
position: absolute; z-index: 3; display: flex; align-items: center; gap: .15rem; padding: .2rem;
border: 1px solid #3f62e0; border-radius: .65rem; background: #244bc8;
box-shadow: 0 .22rem .7rem #13297538;
}
.studio-element-tools button {
min-height: 2rem; padding: .22rem .6rem; border: 0; border-radius: .42rem;
background: transparent; color: white; font-size: .84rem; white-space: nowrap; cursor: pointer;
}
.studio-element-tools button:hover, .studio-element-tools button:focus-visible { background: #ffffff32; }
.studio-element-tools button:focus-visible { outline: 1px solid white; outline-offset: -2px; }
.studio-media-handle {
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;
background: var(--accent); box-shadow: 0 0 0 1px var(--accent); color: white; cursor: ew-resize;
touch-action: none; user-select: none;
}
.studio-media-handle::after { content: ''; width: .38rem; height: .9rem; border-inline: 1px solid currentColor; }
.studio-media-sizing output { font-size: .85rem; font-variant-numeric: tabular-nums; }
.studio-media-sizing .button { min-height: 2.2rem; padding: .25rem .7rem; }
@media (max-width: 54rem) {
.studio-layout { grid-template-columns: minmax(0, 1fr); grid-template-areas: "library" "workspace" "settings"; }
.studio-library { position: static; max-height: none; }
.studio-workspace .studio-frame-window { height: max(25rem, 64dvh); }
}
.studio-template-search { display: grid; gap: .3rem; font-size: .9rem; font-weight: 600; }
.studio-template-search input {
width: 100%;
min-height: 42px;
padding: .45rem .6rem;
color: var(--ink);
background: var(--white);
border: 1px solid var(--line);
border-radius: .5rem;
}
.studio-template-filters { display: flex; gap: .3rem; flex-wrap: wrap; margin-block: .25rem; }
.studio-template-filters button {
min-height: 36px;
padding: .2rem .5rem;
color: var(--muted);
font-size: .825rem;
border: 1px solid var(--line);
border-radius: .35rem;
background: var(--white);
}
.studio-template-filters button[aria-pressed="true"] { border-color: #9bb5fa; color: var(--accent-deep); background: var(--accent-light); }
.studio-template-group + .studio-template-group { margin-top: .9rem; }
.studio-template-group h3 { margin: 0 0 .4rem; font-size: .9rem; font-weight: 650; }
.studio-template-cards { display: grid; gap: .48rem; }
.studio-template-card { min-width: 0; border: 1px solid var(--line); border-radius: .55rem; background: var(--white); }
.studio-template-card:focus-within { border-color: var(--accent); }
.studio-template-image {
display: block;
width: 100%;
padding: 0;
overflow: hidden;
border: 0;
border-radius: .5rem .5rem 0 0;
background: var(--paper);
}
.studio-template-image img { display: block; width: 100%; height: auto; aspect-ratio: 8 / 5; transition: transform .16s ease; }
.studio-template-image:hover img, .studio-template-image:focus-visible img { transform: scale(1.07); }
.studio-template-meta { display: flex; align-items: center; justify-content: space-between; gap: .3rem; padding: .3rem .38rem .3rem .55rem; font-size: .875rem; }
.studio-template-meta .button { min-height: 33px; font-size: .8rem; flex: 0 0 auto; padding: .2rem .45rem; }
.studio-template-peek {
position: fixed;
z-index: 2;
overflow: hidden;
pointer-events: none;
background: var(--white);
border: 1px solid #adbfdf;
border-radius: .65rem;
box-shadow: 0 14px 35px #142e5626;
}
.studio-template-peek img, .studio-template-dialog img { width: 100%; height: auto; aspect-ratio: 8 / 5; display: block; }
.studio-template-peek p { padding: .5rem .8rem; margin: 0; font-size: .9rem; color: var(--ink); }
.studio-template-dialog { width: min(90vw, 49rem); }
.studio-template-dialog > img { border: 1px solid var(--line); border-radius: .55rem; }
.studio-template-dialog > .actions { justify-content: flex-end; margin-top: .75rem; }
@media (max-width: 54rem) {
.studio-template-groups { max-height: 44dvh; overflow-y: auto; padding: .2rem; }
.studio-template-cards { grid-template-columns: repeat(auto-fill, minmax(8.5rem, 1fr)); }
.studio-template-meta { flex-wrap: wrap; }
.studio-template-peek { display: none; }
}
@media (prefers-reduced-motion: reduce) {
.studio-template-image img { transition: none; }
}
.category-checks { min-width: 0; padding: .75rem 1rem; border: 1px solid var(--line); border-radius: .5rem; }
.category-checks > div { display: flex; flex-wrap: wrap; gap: .45rem 1.25rem; }
.admin-form .category-checks label { display: inline-flex; align-items: center; gap: .35rem; }
.admin-form .category-checks input { min-height: 0; width: auto; }
.admin-options { padding: .7rem 1rem; border: 1px solid var(--line); border-radius: .5rem; }
.admin-options > summary { font-weight: 650; cursor: pointer; }
.admin-options[open] > summary { margin-bottom: .85rem; }
.admin-options .form-grid + .category-checks { margin-top: .8rem; }
.article-editor { min-width: 0; }
.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; }
+37 -5
View File
@@ -16,6 +16,18 @@ jQuery(function ($) {
}
};
function clearSavedStatus() {
$('[data-save-confirmation]').prop('hidden', true);
}
if (document.querySelector('[data-save-confirmation]')) {
const url = new URL(window.location.href);
if (url.searchParams.get('saved') === '1') {
url.searchParams.delete('saved');
window.history.replaceState(window.history.state, '', url.href);
}
}
function refreshToken(response) {
if (response?.csrf) {
$('input[name="csrf"]').val(response.csrf);
@@ -37,34 +49,53 @@ jQuery(function ($) {
$feedback.prop('hidden', false).trigger('focus');
}
document.addEventListener('invalid', (event) => {
if (event.target.form?.method.toLowerCase() === 'post') clearSavedStatus();
}, true);
$('form[method="post"]').on('submit', function (event) {
event.preventDefault();
const $form = $(this);
if ($form.attr('aria-busy') === 'true') return;
const submitter = event.originalEvent?.submitter;
if (submitter?.dataset.confirm && !window.confirm(submitter.dataset.confirm)) return;
clearSavedStatus();
const action = $form.attr('action');
const isLogin = action === '/admin/login';
const $submit = $form.find(':submit');
const $submit = $form.find(':submit:enabled');
const multipart = $form.attr('enctype') === 'multipart/form-data';
$form.attr('aria-busy', 'true').children('.ajax-feedback').prop('hidden', true);
$submit.prop('disabled', true);
$form.triggerHandler('studio:busy', [true]);
function finish() {
$form.removeAttr('aria-busy');
$submit.prop('disabled', false);
$form.triggerHandler('studio:busy', [false]);
}
function submit(canRetryLogin) {
$form.triggerHandler('studio:sync');
const fields = multipart ? new FormData($form.get(0)) : $form.serializeArray();
if (submitter?.name) {
if (multipart) fields.append(submitter.name, submitter.value);
else fields.push({name: submitter.name, value: submitter.value});
}
$.ajax({
url: action,
method: 'POST',
data: $form.serialize(),
data: fields,
processData: !multipart,
contentType: multipart ? false : 'application/x-www-form-urlencoded; charset=UTF-8',
dataType: 'json'
}).done(function (response) {
if (response.redirect) {
$form.triggerHandler('studio:saved');
window.location.assign(response.redirect);
return;
}
formError($form, '未收到保存结果,请刷新页面确认。');
finish();
formError($form, '未收到保存结果,请刷新页面确认。');
}).fail(function (request) {
const response = request.responseJSON;
refreshToken(response);
@@ -72,8 +103,8 @@ jQuery(function ($) {
submit(false);
return;
}
formError($form, response?.message || '请求未完成,请稍后重试。', request.status);
finish();
formError($form, response?.message || '请求未完成,请稍后重试。', request.status);
});
}
@@ -82,6 +113,7 @@ jQuery(function ($) {
$('[data-editor]').each(function () {
const $editor = $(this);
if ($editor.find('[data-rich-canvas]').length) return;
const area = $editor.find('textarea').get(0);
const format = $editor.data('format');
const $preview = $editor.find('.editor-preview');
@@ -116,7 +148,7 @@ jQuery(function ($) {
if (status === 'abort') return;
let feedback = request.responseJSON;
if (!feedback && request.getResponseHeader('Content-Type')?.startsWith('application/json')) {
feedback = JSON.parse(request.responseText);
try { feedback = JSON.parse(request.responseText); } catch { /* Use the fallback feedback. */ }
}
refreshToken(feedback);
$preview.text(feedback?.message || '预览无法加载,请重试。');
+56
View File
@@ -0,0 +1,56 @@
'use strict';
jQuery(function ($) {
$('[data-article-editor]').each(function () {
const Editor = window.toastui?.Editor;
if (!Editor) return;
const $field = $(this);
const $source = $field.find('textarea');
const $format = $field.find('input[name="body_format"]');
const $host = $field.find('[data-editor-host]');
const $status = $field.find('[data-article-editor-status]');
const originalFormat = $format.val();
const original = $source.val();
$host.prop('hidden', false);
let editor;
try {
editor = new Editor({
el: $host.get(0),
height: '34rem',
initialEditType: originalFormat === 'html' ? 'wysiwyg' : 'markdown',
initialValue: originalFormat === 'markdown' ? original : '',
previewStyle: 'vertical',
language: 'zh-CN',
usageStatistics: false,
autofocus: false,
hooks: {
addImageBlobHook() {
$status.text('请先上传图片到媒体库,再从媒体库插入。');
}
}
});
if (originalFormat === 'html') editor.setHTML(original);
} catch (error) {
$host.prop('hidden', true);
return;
}
const snapshot = originalFormat === 'html' ? editor.getHTML() : editor.getMarkdown();
$source.prop('hidden', true);
$field.find('[data-article-editor-label]').removeAttr('for');
$field.find('[data-insert-article-image]').prop('hidden', false).on('click', () => {
$('#media-picker').triggerHandler('studio:pick', ['image/', (file) => {
const alt = window.prompt('图片替代文本(装饰图可留空)', file.label);
if (alt === null) return;
$status.empty();
editor.focus();
editor.exec('addImage', {imageUrl: file.url, altText: alt});
}]);
});
$field.closest('form').on('studio:sync', function () {
const format = editor.isMarkdownMode() ? 'markdown' : 'html';
const content = format === 'html' ? editor.getHTML() : editor.getMarkdown();
$format.val(format);
$source.val(format === originalFormat && content === snapshot ? original : content);
});
});
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 72" width="72" height="72">
<rect width="72" height="72" rx="19" fill="#e6f5f1"/>
<rect x="16.5" y="20.5" width="39" height="31" rx="5" fill="#bfe4da" stroke="#0c775f" stroke-width="2.5"/>
<path d="m30 31-6 5 6 5m12-10 6 5-6 5m-4-12-4 14" fill="none" stroke="#0c775f" stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5"/>
</svg>

After

Width:  |  Height:  |  Size: 405 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 72" width="72" height="72">
<rect width="72" height="72" rx="19" fill="#e8efff"/>
<path d="M18 26a4 4 0 0 1 4-4h12l5 5h12a4 4 0 0 1 4 4v16a5 5 0 0 1-5 5H23a5 5 0 0 1-5-5Z" fill="#c5d7ff" stroke="#214ed7" stroke-width="2.5" stroke-linejoin="round"/>
<path d="m29 39 5 5 10-10" fill="none" stroke="#214ed7" stroke-linecap="round" stroke-linejoin="round" stroke-width="3"/>
</svg>

After

Width:  |  Height:  |  Size: 440 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 72" width="72" height="72">
<rect width="72" height="72" rx="19" fill="#fff1e0"/>
<path d="M36 18c5 5 12 7 17 8v10c0 9-8 15-17 19-9-4-17-10-17-19V26c5-1 12-3 17-8Z" fill="#ffdab0" stroke="#a85410" stroke-linejoin="round" stroke-width="2.5"/>
<path d="m29 36 5 5 9-10" fill="none" stroke="#a85410" stroke-linecap="round" stroke-linejoin="round" stroke-width="3"/>
</svg>

After

Width:  |  Height:  |  Size: 432 B

+344 -8
View File
@@ -301,18 +301,22 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
.pagination { display: flex; align-items: center; gap: 1rem; margin-top: 1.5rem; }
.empty-state { background: var(--paper); padding: 1rem; border-radius: .6rem; }
.site-footer { padding: clamp(2.5rem, 5.8vw, 5.5rem) 0 2rem; background: #edf2fa; border-top: 1px solid var(--line); }
.footer-grid { display: grid; grid-template-columns: minmax(0, 1.4fr) repeat(2, minmax(0, .75fr)); gap: 1.5rem 3rem; }
.footer-grid > div { display: flex; flex-direction: column; align-items: flex-start; }
.site-footer { padding: clamp(2.5rem, 5.8vw, 5.5rem) 0 2rem; background: #e4ecfc; border-top: 1px solid var(--line); }
.footer-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 1.6rem clamp(2rem, 7vw, 7rem); }
.footer-company { display: flex; flex-direction: column; align-items: flex-start; }
.footer-logo img { width: clamp(8.125rem, 13vw, 10rem); height: auto; }
.footer-links { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); align-items: start; gap: 1rem; }
.footer-links ul { padding: 0; margin: 0; list-style: none; }
.footer-grid a, .footer-meta a { color: var(--muted); text-decoration: none; overflow-wrap: anywhere; }
.footer-grid a:hover, .footer-meta a:hover { color: var(--accent); text-decoration: underline; }
.footer-grid a { min-height: 44px; display: inline-flex; align-items: center; }
.footer-grid a { min-height: 40px; display: inline-flex; align-items: center; }
.footer-company p, .footer-label { color: var(--ink); font-weight: 640; margin: .2rem 0 .35rem; }
.footer-label { font-size: 1.05rem; line-height: 1.35; }
.footer-company p { margin-top: .6rem; }
.footer-company .footer-payment-label { margin: .25rem 0 0; color: var(--muted); font-size: .87rem; font-weight: 500; }
.footer-company address { color: var(--muted); max-width: 26rem; font-size: .95rem; }
.footer-meta { display: flex; flex-wrap: wrap; gap: .6rem 1.8rem; padding-top: 1.2rem; margin-top: 1.25rem; border-top: 1px solid var(--line); font-size: .875rem; }
.footer-meta { display: grid; gap: .35rem; padding-top: 1.2rem; margin-top: 1.6rem; border-top: 1px solid var(--line); font-size: .875rem; }
.footer-meta p { margin: 0; }
.footer-terms { flex-basis: 100%; }
@media (max-width: 62rem) {
.masthead-inner { gap: .85rem; }
@@ -358,8 +362,9 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
.article-category { grid-column: 1; grid-row: 1; }
.article-row-title { grid-column: 1 / -1; grid-row: 2; }
.article-row time { grid-column: 2; grid-row: 1; }
.footer-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); column-gap: 1rem; }
.footer-company { grid-column: 1 / -1; }
.footer-grid { grid-template-columns: 1fr; }
.footer-company { align-items: center; text-align: center; }
.footer-links, .footer-meta { text-align: center; }
}
@media (max-width: 23rem) {
.hero-actions .button { width: 100%; }
@@ -371,3 +376,334 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
.payment-methods { display: flex; gap: .65rem; align-items: center; margin-block: .5rem; }
.payment-methods img { width: 1.625rem; height: 1.625rem; object-fit: contain; }
.hero-inner.hero-text-only { grid-template-columns: minmax(0, 1fr); min-height: 28rem; }
.hero-directory > .directory-label { border-inline-start: 0; }
.catalog-hero { background: var(--paper); padding-block: clamp(3rem, 6vw, 6rem); }
.catalog-hero h1 { margin-bottom: .85rem; }
.catalog-hero p { margin: 0; font-size: 1.15rem; }
.catalog-listing { padding-block: clamp(3rem, 6vw, 6rem); }
.catalog-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: clamp(1rem, 3vw, 2rem); }
.catalog-card { min-width: 0; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; display: flex; flex-direction: column; }
.catalog-image { aspect-ratio: 16 / 8; padding: clamp(.8rem, 3vw, 1.8rem); background: var(--paper); display: grid; place-items: center; }
.catalog-image img { max-height: 100%; width: 100%; height: 100%; object-fit: contain; }
.catalog-content { padding: clamp(1.25rem, 3vw, 2rem); flex: 1; display: flex; flex-direction: column; }
.catalog-content h2 { font-size: clamp(1.45rem, 3vw, 2.6rem); margin-bottom: .7rem; }
.catalog-content .overline { margin-bottom: .4rem; }
.catalog-content .actions { margin-top: auto; padding-top: 1rem; }
.hero-shnu-sc ~ #benefits { background: #f7f9fe; padding-block: clamp(3.25rem, 6vw, 6rem); }
.hero-shnu-sc ~ #benefits .section-heading { margin-bottom: 1.25rem; }
.hero-shnu-sc ~ #benefits h2 { font-size: clamp(1.85rem, 3.35vw, 3rem); }
.hero-shnu-sc ~ #benefits .rich > p { margin-bottom: .85rem; }
.hero-shnu-sc ~ #benefits .rich > ul { padding-left: 1.35rem; }
.hero-shnu-sc ~ #benefits .rich > ul li + li { margin-top: .35rem; }
.hero-shnu-sc ~ #benefits .rich > ul li::marker { color: var(--accent); }
.hero-shnu-sc ~ #benefits .rich > img {
width: var(--studio-media-width, 100%);
max-width: 100%;
border-radius: var(--radius);
box-shadow: 0 .75rem 2.25rem #101c341a;
}
@media (min-width: 52rem) {
.hero-shnu-sc ~ #benefits > .wrap:has(> .rich > p:first-child + ul + img:last-child) {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1.2fr);
gap: .8rem clamp(2rem, 5vw, 5.5rem);
align-content: center;
}
.hero-shnu-sc ~ #benefits > .wrap:has(> .rich > p:first-child + ul + img:last-child) > .rich { display: contents; }
.hero-shnu-sc ~ #benefits > .wrap:has(> .rich > p:first-child + ul + img:last-child) :is(.section-heading, .rich > p, .rich > ul) {
grid-column: 1;
margin-bottom: 0;
}
.hero-shnu-sc ~ #benefits > .wrap:has(> .rich > p:first-child + ul + img:last-child) .rich > img {
grid-column: 2;
grid-row: 1 / span 3;
align-self: center;
}
}
.copyright-service #materials .feature-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.copyright-service #why .choice-card { background: #e9f0ff; border-color: #7599ec; box-shadow: inset 0 3px var(--accent); }
.copyright-service #why .choice-card h3 { color: var(--accent-deep); }
.copyright-service #options .feature-card { display: flex; flex-direction: column; align-items: flex-start; }
.copyright-service #options .feature-card > img { width: 3.6rem; height: 3.6rem; margin-bottom: .95rem; }
.copyright-service #options .feature-card > a { margin-top: auto; }
.copyright-service #faq .faq { max-width: none; }
.copyright-service #faq summary { font-size: clamp(1.05rem, 1.35vw, 1.2rem); min-height: 3.75rem; }
.copyright-service #faq details > div { max-width: 75ch; }
.copyright-service #go { padding-block: clamp(2rem, 5vw, 4rem); background: var(--white); }
.copyright-service #go > .wrap {
position: relative;
padding: clamp(1.5rem, 5vw, 4.5rem);
padding-right: clamp(11rem, 29vw, 23rem);
border-radius: var(--radius);
background: radial-gradient(ellipse at 88% 110%, #264b9a 0, transparent 59%), #132443;
color: var(--white);
min-height: 16rem;
display: flex;
flex-direction: column;
justify-content: center;
}
.copyright-service #go .section-heading { margin-bottom: .8rem; }
.copyright-service #go h2 { font-size: clamp(1.8rem, 4vw, 3.5rem); }
.copyright-service #go .contact-panel { display: block; }
.copyright-service #go .contact-panel p { color: #d9e8ff; max-width: 40ch; }
.copyright-service #go .contact-panel img {
position: absolute;
top: 50%;
right: clamp(1.5rem, 6vw, 6rem);
transform: translateY(-50%);
width: clamp(8rem, 13vw, 12rem);
padding: .5rem;
border: 0;
border-radius: .85rem;
background: white;
}
.copyright-service #go .button { color: #142956; background: #eef4ff; border-color: #eef4ff; }
.copyright-service #terms { padding-block: 1.4rem 2.5rem; border-top: 0; }
.copyright-service #terms .section-heading { margin-bottom: .35rem; }
.copyright-service #terms h2 { font-size: .95rem; letter-spacing: 0; }
.copyright-service #terms .rich { font-size: .875rem; color: var(--muted); }
@media (max-width: 62rem) {
.copyright-service #materials .feature-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (max-width: 44rem) {
.catalog-grid, .copyright-service #materials .feature-grid { grid-template-columns: 1fr; }
.hero-directory > .directory-label { grid-column: 1 / -1; border-top: 0; }
.copyright-service #go > .wrap { padding: 1.55rem; min-height: 0; }
.copyright-service #go .contact-panel { display: flex; gap: 1rem; }
.copyright-service #go .contact-panel img { position: static; transform: none; width: 7rem; }
}
.hero h1 .hero-heading-primary { color: inherit; }
.studio-accent { display: block; }
[data-studio-editing] [contenteditable], [data-studio-editing] [data-studio-action],
[data-studio-editing] [data-studio-navigation] a, [data-studio-editing] [data-studio-hero-image] {
outline: 1px dashed #7896d5;
outline-offset: 3px;
}
[data-studio-editing] [contenteditable]:focus { outline: 2px solid #4477f9; }
[data-studio-editing] :is([data-studio-action], [data-studio-navigation] a, [data-studio-hero-image], .rich :is(img, video, audio)) { cursor: pointer; }
[data-studio-editing] [data-studio-placeholder]:empty::before {
content: attr(data-studio-placeholder);
color: var(--muted);
font: 400 1rem / 1.5 var(--sans);
}
.home-cursor {
display: inline-block;
width: .52em;
margin-inline-start: .08em;
font-family: var(--mono);
font-size: .7em;
animation: home-cursor-blink 1.1s steps(1, end) 5;
}
@keyframes home-cursor-blink { 50% { opacity: 0; } }
.home-pipe-flow {
position: absolute;
inset: clamp(.45rem, 1.8vw, 1.7rem);
width: calc(100% - 2 * clamp(.45rem, 1.8vw, 1.7rem));
height: calc(100% - 2 * clamp(.45rem, 1.8vw, 1.7rem));
pointer-events: none;
}
.home-pipe-route { opacity: 0; animation: pipe-visibility 7s linear 2 both; }
.home-pipe-route use {
fill: none;
stroke: #2985fa;
stroke-width: 3;
stroke-linecap: round;
stroke-dasharray: 17 110;
stroke-dashoffset: 19;
opacity: .48;
animation: pipe-travel 7s linear 2 both;
}
.home-pipe-route use + use { stroke: #ecffff; stroke-width: 1.3; stroke-dasharray: 11 116; opacity: .95; }
.home-pipe-route:nth-of-type(2) { --pipe-delay: .85s; }
.home-pipe-route:nth-of-type(3) { --pipe-delay: 2.35s; }
.home-pipe-route:nth-of-type(4) { --pipe-delay: 3.2s; }
.home-pipe-route, .home-pipe-route use { animation-delay: var(--pipe-delay, 0s); }
@keyframes pipe-travel { 0%, 6% { stroke-dashoffset: 19; } 45%, 100% { stroke-dashoffset: -104; } }
@keyframes pipe-visibility { 0%, 6%, 45%, 100% { opacity: 0; } 13%, 37% { opacity: 1; } }
@media (prefers-reduced-motion: reduce) {
.home-cursor { animation: none; }
.home-pipe-flow { display: none; }
}
.studio-split { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1.5rem; align-items: center; }
.studio-split > img { width: 100%; }
.studio-banner { padding: clamp(1.25rem, 4vw, 3.25rem); border-radius: var(--radius); background: var(--accent-light); }
@media (max-width: 44rem) { .studio-split { grid-template-columns: 1fr; } }
:where(img, video, audio, .hero-visual)[class*="studio-media-"] { max-width: 100%; }
:is(.rich, .hero-inner, .editor-preview) [class*="studio-media-"] { width: var(--studio-media-width, auto); }
.studio-media-10 { --studio-media-width: 10%; }
.studio-media-11 { --studio-media-width: 11%; }
.studio-media-12 { --studio-media-width: 12%; }
.studio-media-13 { --studio-media-width: 13%; }
.studio-media-14 { --studio-media-width: 14%; }
.studio-media-15 { --studio-media-width: 15%; }
.studio-media-16 { --studio-media-width: 16%; }
.studio-media-17 { --studio-media-width: 17%; }
.studio-media-18 { --studio-media-width: 18%; }
.studio-media-19 { --studio-media-width: 19%; }
.studio-media-20 { --studio-media-width: 20%; }
.studio-media-21 { --studio-media-width: 21%; }
.studio-media-22 { --studio-media-width: 22%; }
.studio-media-23 { --studio-media-width: 23%; }
.studio-media-24 { --studio-media-width: 24%; }
.studio-media-25 { --studio-media-width: 25%; }
.studio-media-26 { --studio-media-width: 26%; }
.studio-media-27 { --studio-media-width: 27%; }
.studio-media-28 { --studio-media-width: 28%; }
.studio-media-29 { --studio-media-width: 29%; }
.studio-media-30 { --studio-media-width: 30%; }
.studio-media-31 { --studio-media-width: 31%; }
.studio-media-32 { --studio-media-width: 32%; }
.studio-media-33 { --studio-media-width: 33%; }
.studio-media-34 { --studio-media-width: 34%; }
.studio-media-35 { --studio-media-width: 35%; }
.studio-media-36 { --studio-media-width: 36%; }
.studio-media-37 { --studio-media-width: 37%; }
.studio-media-38 { --studio-media-width: 38%; }
.studio-media-39 { --studio-media-width: 39%; }
.studio-media-40 { --studio-media-width: 40%; }
.studio-media-41 { --studio-media-width: 41%; }
.studio-media-42 { --studio-media-width: 42%; }
.studio-media-43 { --studio-media-width: 43%; }
.studio-media-44 { --studio-media-width: 44%; }
.studio-media-45 { --studio-media-width: 45%; }
.studio-media-46 { --studio-media-width: 46%; }
.studio-media-47 { --studio-media-width: 47%; }
.studio-media-48 { --studio-media-width: 48%; }
.studio-media-49 { --studio-media-width: 49%; }
.studio-media-50 { --studio-media-width: 50%; }
.studio-media-51 { --studio-media-width: 51%; }
.studio-media-52 { --studio-media-width: 52%; }
.studio-media-53 { --studio-media-width: 53%; }
.studio-media-54 { --studio-media-width: 54%; }
.studio-media-55 { --studio-media-width: 55%; }
.studio-media-56 { --studio-media-width: 56%; }
.studio-media-57 { --studio-media-width: 57%; }
.studio-media-58 { --studio-media-width: 58%; }
.studio-media-59 { --studio-media-width: 59%; }
.studio-media-60 { --studio-media-width: 60%; }
.studio-media-61 { --studio-media-width: 61%; }
.studio-media-62 { --studio-media-width: 62%; }
.studio-media-63 { --studio-media-width: 63%; }
.studio-media-64 { --studio-media-width: 64%; }
.studio-media-65 { --studio-media-width: 65%; }
.studio-media-66 { --studio-media-width: 66%; }
.studio-media-67 { --studio-media-width: 67%; }
.studio-media-68 { --studio-media-width: 68%; }
.studio-media-69 { --studio-media-width: 69%; }
.studio-media-70 { --studio-media-width: 70%; }
.studio-media-71 { --studio-media-width: 71%; }
.studio-media-72 { --studio-media-width: 72%; }
.studio-media-73 { --studio-media-width: 73%; }
.studio-media-74 { --studio-media-width: 74%; }
.studio-media-75 { --studio-media-width: 75%; }
.studio-media-76 { --studio-media-width: 76%; }
.studio-media-77 { --studio-media-width: 77%; }
.studio-media-78 { --studio-media-width: 78%; }
.studio-media-79 { --studio-media-width: 79%; }
.studio-media-80 { --studio-media-width: 80%; }
.studio-media-81 { --studio-media-width: 81%; }
.studio-media-82 { --studio-media-width: 82%; }
.studio-media-83 { --studio-media-width: 83%; }
.studio-media-84 { --studio-media-width: 84%; }
.studio-media-85 { --studio-media-width: 85%; }
.studio-media-86 { --studio-media-width: 86%; }
.studio-media-87 { --studio-media-width: 87%; }
.studio-media-88 { --studio-media-width: 88%; }
.studio-media-89 { --studio-media-width: 89%; }
.studio-media-90 { --studio-media-width: 90%; }
.studio-media-91 { --studio-media-width: 91%; }
.studio-media-92 { --studio-media-width: 92%; }
.studio-media-93 { --studio-media-width: 93%; }
.studio-media-94 { --studio-media-width: 94%; }
.studio-media-95 { --studio-media-width: 95%; }
.studio-media-96 { --studio-media-width: 96%; }
.studio-media-97 { --studio-media-width: 97%; }
.studio-media-98 { --studio-media-width: 98%; }
.studio-media-99 { --studio-media-width: 99%; }
.studio-media-100 { --studio-media-width: 100%; }
.rich :is(img, video)[class*="studio-media-"] { height: auto; max-width: 100%; }
.hero-visual[class*="studio-media-"] { justify-self: center; }
[data-studio-editing] [data-studio-selected] { outline: 1px dashed #315ef0; outline-offset: 3px; }
.rich .studio-intro { max-width: 47rem; }
.rich .studio-intro h3, .rich .studio-cover h3 { font-size: clamp(1.75rem, 4vw, 2.8rem); }
.rich .studio-cover { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.05fr); align-items: center; gap: clamp(1rem, 4vw, 3rem); background: var(--paper); padding: clamp(.8rem, 3vw, 2rem); border-radius: var(--radius); }
.rich .studio-cover img { width: 100%; }
.rich .studio-cover p { margin-bottom: .85rem; }
.rich .studio-two-column { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; }
.rich .studio-quick-nav { display: flex; flex-wrap: wrap; gap: .55rem 1rem; list-style: none; padding: .75rem; border: 1px solid var(--line); border-radius: .6rem; }
.rich .studio-quick-nav a { display: inline-flex; align-items: center; min-height: 44px; padding-inline: .4rem; font-weight: 600; }
@media (max-width: 44rem) {
.rich .studio-cover, .rich .studio-two-column { grid-template-columns: minmax(0, 1fr); }
}
.article-feed-note { margin-top: 1.15rem; }
.article-cover { display: block; max-height: 28rem; width: auto; margin-bottom: 1.75rem; object-fit: contain; }
.article-tabs { margin-bottom: .85rem; }
.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); }
+31
View File
@@ -22,6 +22,37 @@ jQuery(function ($) {
});
}
$('[data-article-tabs]').each(function () {
const $feed = $(this);
const $list = $feed.children('[data-tab-list]');
const $panels = $feed.children('[data-tab-panel]');
const $tabs = $list.children('[role="tab"]');
function selectTab(index, focus = false) {
$tabs.each(function (number) {
$(this).attr({'aria-selected': String(index === number), tabindex: index === number ? '0' : '-1'});
});
$panels.prop('hidden', true).eq(index).prop('hidden', false);
if (focus) $tabs.eq(index).trigger('focus');
}
$panels.each(function (index) {
$(this).attr({role: 'tabpanel', 'aria-labelledby': $tabs.eq(index).attr('id'), tabindex: '0'});
}).children('[data-tab-heading]').prop('hidden', true);
$list.prop('hidden', false);
selectTab(0);
$tabs.on('click', function () {
selectTab($tabs.index(this));
}).on('keydown', function (event) {
const index = $tabs.index(this);
const last = $tabs.length - 1;
const destinations = {ArrowLeft: index === 0 ? last : index - 1, ArrowRight: index === last ? 0 : index + 1, Home: 0, End: last};
if (!Object.hasOwn(destinations, event.key)) return;
event.preventDefault();
selectTab(destinations[event.key], true);
});
});
if ('IntersectionObserver' in window && !matchMedia('(prefers-reduced-motion: reduce)').matches) {
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 NHN Cloud Corp.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+162
View File
@@ -0,0 +1,162 @@
/*!
* TOAST UI Editor : i18n
* @version 3.2.2
* @author NHN Cloud FE Development Lab <dl_javascript@nhn.com>
* @license MIT
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("@toast-ui/editor"));
else if(typeof define === 'function' && define.amd)
define(["@toast-ui/editor"], factory);
else {
var a = typeof exports === 'object' ? factory(require("@toast-ui/editor")) : factory(root["toastui"]["Editor"]);
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(self, function(__WEBPACK_EXTERNAL_MODULE__213__) {
return /******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ 213:
/***/ (function(module) {
module.exports = __WEBPACK_EXTERNAL_MODULE__213__;
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ !function() {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function() { return module['default']; } :
/******/ function() { return module; };
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ !function() {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = function(exports, definition) {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ !function() {
/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/ }();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ !function() {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
!function() {
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _editorCore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(213);
/* harmony import */ var _editorCore__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_editorCore__WEBPACK_IMPORTED_MODULE_0__);
/**
* @fileoverview I18N for Chinese
* @author NHN Cloud FE Development Lab <dl_javascript@nhn.com>
*/
_editorCore__WEBPACK_IMPORTED_MODULE_0___default().setLanguage('zh-CN', {
Markdown: 'Markdown',
WYSIWYG: '所见即所得',
Write: '编辑',
Preview: '预览',
Headings: '标题',
Paragraph: '文本',
Bold: '加粗',
Italic: '斜体字',
Strike: '删除线',
Code: '内嵌代码',
Line: '水平线',
Blockquote: '引用块',
'Unordered list': '无序列表',
'Ordered list': '有序列表',
Task: '任务',
Indent: '缩进',
Outdent: '减少缩进',
'Insert link': '插入链接',
'Insert CodeBlock': '插入代码块',
'Insert table': '插入表格',
'Insert image': '插入图片',
Heading: '标题',
'Image URL': '图片网址',
'Select image file': '选择图片文件',
'Choose a file': '选择一个文件',
'No file': '没有文件',
Description: '说明',
OK: '确认',
More: '更多',
Cancel: '取消',
File: '文件',
URL: 'URL',
'Link text': '链接文本',
'Add row to up': '向上添加行',
'Add row to down': '在下方添加行',
'Add column to left': '在左侧添加列',
'Add column to right': '在右侧添加列',
'Remove row': '删除行',
'Remove column': '删除列',
'Align column to left': '左对齐',
'Align column to center': '居中对齐',
'Align column to right': '右对齐',
'Remove table': '删除表格',
'Would you like to paste as table?': '需要粘贴为表格吗?',
'Text color': '文字颜色',
'Auto scroll enabled': '自动滚动已启用',
'Auto scroll disabled': '自动滚动已禁用',
'Choose language': '选择语言',
});
}();
/******/ return __webpack_exports__;
/******/ })()
;
});
+24 -4
View File
@@ -12,9 +12,11 @@ CREATE TABLE IF NOT EXISTS pages (
lead TEXT NOT NULL,
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,
partners TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('draft', 'published')),
updated_at TEXT,
version INTEGER NOT NULL DEFAULT 0
);
@@ -24,6 +26,8 @@ CREATE TABLE IF NOT EXISTS sections (
title TEXT NOT NULL,
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,
@@ -33,9 +37,10 @@ CREATE TABLE IF NOT EXISTS articles (
id INTEGER PRIMARY KEY,
slug TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
category TEXT NOT NULL CHECK (category IN ('announcement','news','product')),
summary TEXT NOT NULL,
body TEXT NOT NULL,
body_format TEXT NOT NULL DEFAULT 'markdown' CHECK (body_format IN ('markdown', 'html')),
card TEXT NOT NULL DEFAULT '{}',
tags TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('draft','published')),
published_at TEXT,
@@ -44,6 +49,16 @@ CREATE TABLE IF NOT EXISTS articles (
version INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS articles_public ON articles (status, published_at DESC, id DESC);
CREATE TABLE IF NOT EXISTS article_categories (
slug TEXT PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS article_category_links (
article_id INTEGER NOT NULL REFERENCES articles(id) ON DELETE CASCADE,
category_slug TEXT NOT NULL REFERENCES article_categories(slug),
PRIMARY KEY (article_id, category_slug)
);
CREATE INDEX IF NOT EXISTS article_categories_lookup ON article_category_links (category_slug, article_id);
CREATE TABLE IF NOT EXISTS article_redirects (
slug TEXT PRIMARY KEY,
article_id INTEGER NOT NULL REFERENCES articles(id) ON DELETE CASCADE
@@ -58,6 +73,11 @@ CREATE TABLE IF NOT EXISTS login_attempts (
attempts INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS schema_migrations (
name TEXT PRIMARY KEY
CREATE TABLE IF NOT EXISTS media (
name TEXT PRIMARY KEY,
label TEXT NOT NULL,
mime TEXT NOT NULL,
size INTEGER NOT NULL,
created_at TEXT NOT NULL,
archived INTEGER NOT NULL DEFAULT 0
);
+228 -56
View File
@@ -34,7 +34,7 @@
"key": "product",
"title": "产品与服务",
"lead": "",
"body": "<div class=\"project-stack\"><article class=\"project\"><div><img src=\"/assets/original/pagepan-editor-optimized.webp\" alt=\"PAGEPAN 可视化网页编辑器\" loading=\"lazy\"></div><div><span class=\"overline\">可视化建站</span><h3>PAGEPAN 小飞页</h3><p>自托管拖拽建站工具。由 UI 中国签约的飞屋设计团队打造,可在自己的服务器上运行。</p><p>无需代码,五分钟 DIY 网站,每一处细节都可定制。提供永久免费版本,VIP 版本最低 ¥79/年。</p><div class=\"actions\"><a class=\"button button-primary\" href=\"/pagepan\">探索 PAGEPAN</a><a href=\"/pagepan#download\">免费体验</a></div></div></article><article class=\"project\"><div><img src=\"/assets/original/highspeaker-ui-optimized.webp\" alt=\"HighSpeaker DNS 管理界面\" loading=\"lazy\"></div><div><span class=\"overline\">开源基础软件</span><h3>HighSpeaker DNS</h3><p>新一代智能 DNS 系统。企业和云服务商可以私有化或内网部署,也可二次开发,提供多租户、可分销的 SaaS 服务。</p><p>100% 开源免费。</p><a class=\"button button-primary\" href=\"/highspeaker\">探索 HighSpeaker</a></div></article><article class=\"project\"><div><img src=\"/assets/original/copyright.webp\" alt=\"软件著作权服务插图\" loading=\"lazy\"></div><div><span class=\"overline\">软件著作权</span><h3>来笙软著代理</h3><p>提供申请代理、材料审核与优化、合作开发合同模板。</p><div class=\"actions\"><a class=\"button button-primary\" href=\"/sc\">查看软著服务</a><a href=\"/shnu-sc\">查看 SHNU 学生方案</a></div></div></article></div>",
"body": "<div class=\"project-stack\"><article class=\"project\"><div><img src=\"/assets/original/pagepan-editor-optimized.webp\" alt=\"PAGEPAN 可视化网页编辑器\" loading=\"lazy\"></div><div><span class=\"overline\">可视化建站</span><h3>PAGEPAN 小飞页</h3><p>自托管拖拽建站工具。由 UI 中国签约的飞屋设计团队打造,可在自己的服务器上运行。</p><p>无需代码,五分钟 DIY 网站,每一处细节都可定制。提供永久免费版本,VIP 版本最低 ¥79/年。</p><div class=\"actions\"><a class=\"button button-primary\" href=\"/pagepan\">探索 PAGEPAN</a><a href=\"/pagepan#download\">免费体验</a></div></div></article><article class=\"project\"><div><img src=\"/assets/original/highspeaker-ui-optimized.webp\" alt=\"HighSpeaker DNS 管理界面\" loading=\"lazy\"></div><div><span class=\"overline\">开源基础软件</span><h3>HighSpeaker DNS</h3><p>新一代智能 DNS 系统。企业和云服务商可以私有化或内网部署,也可二次开发,提供多租户、可分销的 SaaS 服务。</p><p>100% 开源免费。</p><a class=\"button button-primary\" href=\"/highspeaker\">探索 HighSpeaker</a></div></article></div>",
"style": "projects"
},
{
@@ -43,56 +43,22 @@
"lead": "",
"body": "<p>来笙是由上海师范大学、华东理工大学、沈阳建筑大学、华南师范大学等多所高校学生发起的合作跨校的自主创业项目。致力于提供独特、优质的企行业软件和面向开发者的个人工具软件。</p><p>来笙致力于通过研发互联网基础软件和产品,解决互联网基础产品痛点痒点,为构建更好互联网持续做出努力。</p>",
"style": "about"
}
],
"partners": [
{
"name": "HighSpeaker DNS",
"image": "/assets/original/highspeaker-logo-optimized.webp",
"url": "/highspeaker",
"group": "来笙支持项目"
},
{
"name": "FW Network",
"image": "/assets/original/fw-banner.svg",
"url": "https://fw.ac.cn/",
"group": "来笙合作伙伴"
},
{
"name": "IdealShark",
"image": "/assets/original/IdealShark_B.png",
"url": "",
"group": "来笙支持项目"
},
{
"name": "MimirLib",
"image": "/assets/original/mimirlib.png",
"url": "",
"group": "来笙支持项目"
},
{
"name": "NoNat",
"image": "/assets/original/nonat-optimized.webp",
"url": "https://nonat.eu.org/",
"group": "来笙支持项目"
},
{
"name": "PAGEPAN",
"image": "/assets/original/papepan-logo.svg",
"url": "https://pagepan.com/",
"group": "来笙合作伙伴"
},
{
"name": "LayFi",
"image": "",
"url": "https://www.layfi.de",
"group": "来笙支持项目"
},
{
"name": "OneProvider",
"image": "/assets/original/oneprovider_invert.svg",
"url": "https://oneprovider.com/",
"group": "来笙合作伙伴"
"key": "blog",
"title": "来笙动态",
"lead": "",
"style": "plain",
"body": "",
"feed": {
"categories": [
"announcement",
"news",
"product"
],
"mode": "merged",
"limit": 3
}
}
]
},
@@ -146,7 +112,7 @@
"key": "features",
"title": "建站工具与功能",
"lead": "",
"body": "<img src=\"/assets/original/pagepan-example.webp\" alt=\"用 PAGEPAN 搭建的响应式网站在电脑和手机上的效果\" loading=\"lazy\" width=\"1366\" height=\"768\"><div class=\"card-grid feature-grid\"><article class=\"content-card feature-card\"><h3>字体管理器</h3>\n<p>几千种开源字体随意添加选用。附带字体压缩功能和缓存器功能,再也不用为加载字体付出高额流量费!</p></article><article class=\"content-card feature-card\"><h3>文件管理器</h3>\n<p>什么年代了还需要FTP?不存在的。图片、文档、视频、压缩包,全都由可视化的文件管理器来管理,随时取用~</p></article><article class=\"content-card feature-card\"><h3>代码编辑器</h3>\n<p>PAGEPAN已经不能满足你了?没关系。每一个组件,包括公共页头页脚你都可以打开Html编辑器修改其代码,依旧所见即所得。你甚至可以编写PHP脚本。</p></article><article class=\"content-card feature-card\"><h3>COS、CDN</h3>\n<p>可以将所有静态内容传入腾讯云COS,或接入任意CDN。让你的网站快如闪电!</p></article><article class=\"content-card feature-card\"><h3>Sitemap一键生成</h3>\n<p>自动挖掘Sitemap,一键即可生成!</p></article><article class=\"content-card feature-card\"><h3>All for SEO</h3>\n<p>SEO优化友好,加快网站收录速度。</p></article><article class=\"content-card feature-card\"><h3>动态组件(CMS)</h3>\n<p>无论是新闻、列表、博客、文章、产品,都可以通过动态内容来实现类似于CMS的体验。支持Html和Markdown双编辑器自由切换。不是CMS,但是超越CMS!</p></article><article class=\"content-card feature-card\"><h3>渐变色调色器</h3>\n<p>自带渐变调色器。任何组件任何文字都可以设置为魅力十足的渐变色。</p></article><article class=\"content-card feature-card\"><h3>多语言支持</h3>\n<p>一个站点,多种语言,任意切换,实现面向全球!</p></article></div><p><a href=\"https://pagepan.com/home\">访问 PAGEPAN 官网</a></p>",
"body": "<img src=\"/assets/original/pagepan-example.webp\" alt=\"用 PAGEPAN 搭建的响应式网站在电脑和手机上的效果\" loading=\"lazy\" width=\"1366\" height=\"768\"><div class=\"card-grid feature-grid\"><article class=\"content-card feature-card\"><img src=\"/assets/original/pagepan/fonts.svg\" alt=\"\" width=\"50\" height=\"50\" loading=\"lazy\"><h3>字体管理器</h3>\n<p>几千种开源字体随意添加选用。附带字体压缩功能和缓存器功能,再也不用为加载字体付出高额流量费!</p></article><article class=\"content-card feature-card\"><img src=\"/assets/original/pagepan/files.svg\" alt=\"\" width=\"50\" height=\"50\" loading=\"lazy\"><h3>文件管理器</h3>\n<p>什么年代了还需要FTP?不存在的。图片、文档、视频、压缩包,全都由可视化的文件管理器来管理,随时取用~</p></article><article class=\"content-card feature-card\"><img src=\"/assets/original/pagepan/code.svg\" alt=\"\" width=\"50\" height=\"50\" loading=\"lazy\"><h3>代码编辑器</h3>\n<p>PAGEPAN已经不能满足你了?没关系。每一个组件,包括公共页头页脚你都可以打开Html编辑器修改其代码,依旧所见即所得。你甚至可以编写PHP脚本。</p></article><article class=\"content-card feature-card\"><img src=\"/assets/original/pagepan/cdn.svg\" alt=\"\" width=\"50\" height=\"50\" loading=\"lazy\"><h3>COS、CDN</h3>\n<p>可以将所有静态内容传入腾讯云COS,或接入任意CDN。让你的网站快如闪电!</p></article><article class=\"content-card feature-card\"><img src=\"/assets/original/pagepan/sitemap.svg\" alt=\"\" width=\"50\" height=\"50\" loading=\"lazy\"><h3>Sitemap一键生成</h3>\n<p>自动挖掘Sitemap,一键即可生成!</p></article><article class=\"content-card feature-card\"><img src=\"/assets/original/pagepan/seo.svg\" alt=\"\" width=\"50\" height=\"50\" loading=\"lazy\"><h3>All for SEO</h3>\n<p>SEO优化友好,加快网站收录速度。</p></article><article class=\"content-card feature-card\"><img src=\"/assets/original/pagepan/cms.svg\" alt=\"\" width=\"50\" height=\"50\" loading=\"lazy\"><h3>动态组件(CMS)</h3>\n<p>无论是新闻、列表、博客、文章、产品,都可以通过动态内容来实现类似于CMS的体验。支持Html和Markdown双编辑器自由切换。不是CMS,但是超越CMS!</p></article><article class=\"content-card feature-card\"><img src=\"/assets/original/pagepan/gradient.svg\" alt=\"\" width=\"50\" height=\"50\" loading=\"lazy\"><h3>渐变色调色器</h3>\n<p>自带渐变调色器。任何组件任何文字都可以设置为魅力十足的渐变色。</p></article><article class=\"content-card feature-card\"><img src=\"/assets/original/pagepan/languages.svg\" alt=\"\" width=\"50\" height=\"50\" loading=\"lazy\"><h3>多语言支持</h3>\n<p>一个站点,多种语言,任意切换,实现面向全球!</p></article></div><p><a href=\"https://pagepan.com/home\">访问 PAGEPAN 官网</a></p>",
"style": "plain"
},
{
@@ -305,14 +271,14 @@
"key": "why",
"title": "为什么选择来笙",
"lead": "",
"body": "<div class=\"card-grid feature-grid\"><article class=\"content-card feature-card\"><h3>手工DIY</h3>\n<p>申请需要繁琐的材料。<br/>一旦有所错漏哪怕格式不对、甚至点错了按钮,都会造成补正。<br/>一次补正就要重新排队,至少延迟两周时间。</p></article><article class=\"content-card feature-card\"><h3>其他著作权代理商</h3>\n<p>经常收取高额费用,声称提供所谓“加急”服务<br/>实则经常盗用各种开源软件、AI代码。<br/>一旦被版权中心查实,面临终生黑名单,得不偿失!部分黑心商家还收合作申请费!</p></article><article class=\"content-card feature-card\"><h3>选择来笙</h3>\n<p>最低仅需¥120元起,替您处理和审查、优化材料。不收取任何加急费,所有申请均最快60日内下证。<br/>不收取合作申请费,可多人一起申请。</p></article></div>",
"body": "<div class=\"card-grid feature-grid\"><article class=\"content-card feature-card\"><h3>手工DIY</h3>\n<p>申请需要繁琐的材料。<br>一旦有所错漏哪怕格式不对、甚至点错了按钮,都会造成补正。<br>一次补正就要重新排队,至少延迟两周时间。</p></article><article class=\"content-card feature-card\"><h3>其他著作权代理商</h3>\n<p>经常收取高额费用,声称提供所谓“加急”服务<br>实则经常盗用各种开源软件、AI代码。<br>一旦被版权中心查实,面临终生黑名单,得不偿失!部分黑心商家还收合作申请费!</p></article><article class=\"content-card feature-card choice-card\"><h3>选择来笙</h3>\n<p>最低仅需¥120元起,替您处理和审查、优化材料。不收取任何加急费,所有申请均最快60日内下证。<br>不收取合作申请费,可多人一起申请。</p></article></div>",
"style": "tinted"
},
{
"key": "options",
"title": "按准备进度选择服务",
"lead": "",
"body": "<div class=\"card-grid feature-grid\"><article class=\"content-card feature-card\"><li>\n\n<img alt=\"\" loading=\"lazy\" src=\"/assets/original/10-1.png\"/>\n<h3>我已经有项目了!</h3>\n<p>仅需一本书的价格,来笙直接帮您搞定软著!为您全程提供申请代理+材料指导+审核优化,最快60天拿证书!</p>\n<a href=\"#price1\"><span>代理申请服务</span></a>\n\n</li></article><article class=\"content-card feature-card\"><li>\n\n<img alt=\"\" loading=\"lazy\" src=\"/assets/original/10-2.png\"/>\n<h3>我会写代码!</h3>\n<p>无需头疼各种麻烦的材料和手续,来笙为您一次性做齐所有材料,包您下证!</p>\n<a href=\"#price2\"><span>无忧申请</span></a>\n\n</li></article><article class=\"content-card feature-card\"><li>\n\n<img alt=\"\" loading=\"lazy\" src=\"/assets/original/10-3.png\"/>\n<h3>啥也不会也没事!</h3>\n<p>从代码到材料,来笙替您一站式解决。即使不会写代码也能拿到软著!</p>\n<a href=\"#price3\"><span>一价全包</span></a>\n\n</li></article></div>",
"body": "<div class=\"card-grid feature-grid\"><article class=\"content-card feature-card\">\n\n<img alt=\"\" loading=\"lazy\" src=\"/assets/service/project.svg\">\n<h3>我已经有项目了!</h3>\n<p>仅需一本书的价格,来笙直接帮您搞定软著!为您全程提供申请代理+材料指导+审核优化,最快60天拿证书!</p>\n<a href=\"#price1\"><span>代理申请服务</span></a>\n\n</article><article class=\"content-card feature-card\">\n\n<img alt=\"\" loading=\"lazy\" src=\"/assets/service/code.svg\">\n<h3>我会写代码!</h3>\n<p>无需头疼各种麻烦的材料和手续,来笙为您一次性做齐所有材料,包您下证!</p>\n<a href=\"#price2\"><span>无忧申请</span></a>\n\n</article><article class=\"content-card feature-card\">\n\n<img alt=\"\" loading=\"lazy\" src=\"/assets/service/support.svg\">\n<h3>啥也不会也没事!</h3>\n<p>从代码到材料,来笙替您一站式解决。即使不会写代码也能拿到软著!</p>\n<a href=\"#price3\"><span>一价全包</span></a>\n\n</article></div>",
"style": "plain"
},
{
@@ -409,14 +375,14 @@
"key": "why",
"title": "为什么选择来笙",
"lead": "",
"body": "<div class=\"card-grid feature-grid\"><article class=\"content-card feature-card\"><h3>手工DIY</h3>\n<p>申请需要繁琐的材料。<br/>一旦有所错漏哪怕格式不对、甚至点错了按钮,都会造成补正。<br/>一次补正就要重新排队,至少延迟两周时间。</p></article><article class=\"content-card feature-card\"><h3>其他著作权代理商</h3>\n<p>经常收取高额费用,声称提供所谓“加急”服务<br/>实则经常盗用各种开源软件、AI代码。<br/>一旦被版权中心查实,面临终生黑名单,得不偿失!部分黑心商家还收合作申请费!</p></article><article class=\"content-card feature-card\"><h3>选择来笙</h3>\n<p>最低仅需¥66元起,替您处理和审查、优化材料。不收取任何加急费,所有申请均最快60日内下证。<br/>不收取合作申请费,可多人一起申请。</p></article></div>",
"body": "<div class=\"card-grid feature-grid\"><article class=\"content-card feature-card\"><h3>手工DIY</h3>\n<p>申请需要繁琐的材料。<br>一旦有所错漏哪怕格式不对、甚至点错了按钮,都会造成补正。<br>一次补正就要重新排队,至少延迟两周时间。</p></article><article class=\"content-card feature-card\"><h3>其他著作权代理商</h3>\n<p>经常收取高额费用,声称提供所谓“加急”服务<br>实则经常盗用各种开源软件、AI代码。<br>一旦被版权中心查实,面临终生黑名单,得不偿失!部分黑心商家还收合作申请费!</p></article><article class=\"content-card feature-card choice-card\"><h3>选择来笙</h3>\n<p>最低仅需¥66元起,替您处理和审查、优化材料。不收取任何加急费,所有申请均最快60日内下证。<br>不收取合作申请费,可多人一起申请。</p></article></div>",
"style": "tinted"
},
{
"key": "options",
"title": "按准备进度选择服务",
"lead": "",
"body": "<div class=\"card-grid feature-grid\"><article class=\"content-card feature-card\"><li>\n\n<img alt=\"\" loading=\"lazy\" src=\"/assets/original/10-1.png\"/>\n<h3>我已经有项目了!</h3>\n<p>仅需一本书的价格,来笙直接帮您搞定软著!为您全程提供申请代理+材料指导+审核优化,最快60天拿证书!</p>\n<a href=\"/shnu-sc#price1\"><span>代理申请服务</span></a>\n\n</li></article><article class=\"content-card feature-card\"><li>\n\n<img alt=\"\" loading=\"lazy\" src=\"/assets/original/10-2.png\"/>\n<h3>我会写代码!</h3>\n<p>无需头疼各种麻烦的材料和手续,来笙为您一次性做齐所有材料,包您下证!</p>\n<a href=\"/shnu-sc#price2\"><span>无忧申请</span></a>\n\n</li></article><article class=\"content-card feature-card\"><li>\n\n<img alt=\"\" loading=\"lazy\" src=\"/assets/original/10-3.png\"/>\n<h3>啥也不会也没事!</h3>\n<p>从代码到材料,来笙替您一站式解决。即使不会写代码也能拿到软著!</p>\n<a href=\"/shnu-sc#price3\"><span>一价全包</span></a>\n\n</li></article></div>",
"body": "<div class=\"card-grid feature-grid\"><article class=\"content-card feature-card\">\n\n<img alt=\"\" loading=\"lazy\" src=\"/assets/service/project.svg\">\n<h3>我已经有项目了!</h3>\n<p>仅需一本书的价格,来笙直接帮您搞定软著!为您全程提供申请代理+材料指导+审核优化,最快60天拿证书!</p>\n<a href=\"/shnu-sc#price1\"><span>代理申请服务</span></a>\n\n</article><article class=\"content-card feature-card\">\n\n<img alt=\"\" loading=\"lazy\" src=\"/assets/service/code.svg\">\n<h3>我会写代码!</h3>\n<p>无需头疼各种麻烦的材料和手续,来笙为您一次性做齐所有材料,包您下证!</p>\n<a href=\"/shnu-sc#price2\"><span>无忧申请</span></a>\n\n</article><article class=\"content-card feature-card\">\n\n<img alt=\"\" loading=\"lazy\" src=\"/assets/service/support.svg\">\n<h3>啥也不会也没事!</h3>\n<p>从代码到材料,来笙替您一站式解决。即使不会写代码也能拿到软著!</p>\n<a href=\"/shnu-sc#price3\"><span>一价全包</span></a>\n\n</article></div>",
"style": "plain"
},
{
@@ -468,7 +434,6 @@
{
"slug": "global-server-deployment",
"title": "来笙关于即将减少全球服务器部署的公告",
"category": "announcement",
"summary": "",
"body": "",
"tags": [
@@ -477,7 +442,214 @@
],
"date": "2024-11-10 14:39:31",
"status": "published",
"legacy": "/news/id/4.html"
"legacy": "/news/id/4.html",
"categories": [
"announcement"
]
},
{
"slug": "service-1",
"title": "PAGEPAN 小飞页",
"body": "<p>自托管拖拽建站工具。由 UI 中国签约的飞屋设计团队打造,可在自己的服务器上运行。</p><p>无需代码,五分钟 DIY 网站,每一处细节都可定制。提供永久免费版本,VIP 版本最低 ¥79/年。</p>",
"card": {
"image": "/assets/original/pagepan-editor-optimized.webp",
"alt": "PAGEPAN 可视化网页编辑器",
"url": "/pagepan",
"label": "探索 PAGEPAN",
"extra_url": "/pagepan#download",
"extra_label": "免费体验",
"position": 0,
"category_label": "可视化建站"
},
"body_format": "html",
"categories": [
"services"
]
},
{
"slug": "service-2",
"title": "HighSpeaker DNS",
"body": "<p>新一代智能 DNS 系统。企业和云服务商可以私有化或内网部署,也可二次开发,提供多租户、可分销的 SaaS 服务。</p><p>100% 开源免费。</p>",
"card": {
"image": "/assets/original/highspeaker-ui-optimized.webp",
"alt": "HighSpeaker DNS 管理界面",
"url": "/highspeaker",
"label": "探索 HighSpeaker",
"extra_url": "",
"extra_label": "",
"position": 10,
"category_label": "开源基础软件"
},
"body_format": "html",
"categories": [
"services"
]
},
{
"slug": "service-3",
"title": "来笙软著代理",
"body": "<p>提供申请代理、材料审核与优化、合作开发合同模板。</p>",
"card": {
"image": "/assets/original/copyright.webp",
"alt": "软件著作权服务插图",
"url": "/sc",
"label": "查看软著服务",
"extra_url": "/shnu-sc",
"extra_label": "查看 SHNU 学生方案",
"position": 20,
"category_label": "软件著作权"
},
"body_format": "html",
"categories": [
"services"
]
},
{
"slug": "service-4",
"title": "SHNU 学生软著服务",
"body": "<p>面向 SHNU 学生的软件著作权申请服务。</p>",
"card": {
"image": "/assets/original/shnu-hero.webp",
"alt": "",
"url": "/shnu-sc",
"label": "查看学生方案",
"extra_url": "",
"extra_label": "",
"position": 30,
"category_label": "校园服务"
},
"body_format": "html",
"categories": [
"services"
]
},
{
"slug": "network-1",
"title": "HighSpeaker DNS",
"body": "",
"card": {
"image": "/assets/original/highspeaker-logo-optimized.webp",
"alt": "",
"url": "/highspeaker",
"label": "访问网站",
"position": 0
},
"body_format": "html",
"categories": [
"supported-projects"
]
},
{
"slug": "network-2",
"title": "FW Network",
"body": "",
"card": {
"image": "/assets/original/fw-banner.svg",
"alt": "",
"url": "https://fw.ac.cn/",
"label": "访问网站",
"position": 1
},
"body_format": "html",
"categories": [
"partners"
]
},
{
"slug": "network-3",
"title": "IdealShark",
"body": "",
"card": {
"image": "/assets/original/IdealShark_B.png",
"alt": "",
"url": "",
"label": "访问网站",
"position": 2
},
"body_format": "html",
"categories": [
"supported-projects"
]
},
{
"slug": "network-4",
"title": "MimirLib",
"body": "",
"card": {
"image": "/assets/original/mimirlib.png",
"alt": "",
"url": "",
"label": "访问网站",
"position": 3
},
"body_format": "html",
"categories": [
"supported-projects"
]
},
{
"slug": "network-5",
"title": "NoNat",
"body": "",
"card": {
"image": "/assets/original/nonat-optimized.webp",
"alt": "",
"url": "https://nonat.eu.org/",
"label": "访问网站",
"position": 4
},
"body_format": "html",
"categories": [
"supported-projects"
]
},
{
"slug": "network-6",
"title": "PAGEPAN",
"body": "",
"card": {
"image": "/assets/original/papepan-logo.svg",
"alt": "",
"url": "https://pagepan.com/",
"label": "访问网站",
"position": 5
},
"body_format": "html",
"categories": [
"partners"
]
},
{
"slug": "network-7",
"title": "LayFi",
"body": "",
"card": {
"image": "",
"alt": "",
"url": "https://www.layfi.de",
"label": "访问网站",
"position": 6
},
"body_format": "html",
"categories": [
"supported-projects"
]
},
{
"slug": "network-8",
"title": "OneProvider",
"body": "",
"card": {
"image": "/assets/original/oneprovider_invert.svg",
"alt": "",
"url": "https://oneprovider.com/",
"label": "访问网站",
"position": 7
},
"body_format": "html",
"categories": [
"partners"
]
}
]
}
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use App\Content\Database;
// 输出目录类文章:slug<TAB>卡片网址<TAB>是否已发布
$pdo = Database::connect();
$query = $pdo->query("SELECT a.slug, a.card, a.status FROM articles a
WHERE EXISTS (SELECT 1 FROM article_category_links l WHERE l.article_id = a.id
AND l.category_slug IN ('services', 'supported-projects', 'partners'))
ORDER BY a.id");
foreach ($query as $row) {
$card = json_decode($row['card'], true) ?: [];
echo $row['slug'], '|', $card['url'] ?? '', '|', $row['status'], "\n";
}
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env bash
# 目录页(/services、/network)的卡片链接必须指向卡片配置的网址,而不是 /articles/<slug>
set -u
cd "$(dirname "$0")/.." || exit 1
BASE=http://127.0.0.1:8787
PASS=0; FAIL=0
ok(){ PASS=$((PASS+1)); printf ' ok %s\n' "$1"; }
no(){ FAIL=$((FAIL+1)); printf ' FAIL %s -> %s\n' "$1" "${2:-}"; }
SERVICES=$(curl -s "$BASE/services")
NETWORK=$(curl -s "$BASE/network")
ROWS=$(php tests/dircheck.php)
echo "== /services 卡片链接 =="
while IFS='|' read -r slug url status; do
[ -z "$slug" ] && continue
[ -z "$url" ] && continue
if echo "$SERVICES" | grep -q "href=\"$url\""; then ok "$slug 标题/按钮指向 $url"; else no "$slug 未指向 $url"; fi
if echo "$SERVICES" | grep -q "href=\"/articles/$slug\""; then no "$slug 仍出现 /articles/$slug"; else ok "$slug 不再指向文章页"; fi
done <<< "$(echo "$ROWS" | grep -E '^service-')"
echo "== /network 卡片链接 =="
while IFS='|' read -r slug url status; do
[ -z "$slug" ] && continue
[ -z "$url" ] && continue
if echo "$NETWORK" | grep -q "href=\"$url\""; then ok "$slug 指向 $url"; else no "$slug 未指向 $url"; fi
if echo "$NETWORK" | grep -q "href=\"/articles/$slug\""; then no "$slug 仍出现 /articles/$slug"; else ok "$slug 不再指向文章页"; fi
done <<< "$(echo "$ROWS" | grep -E '^network-')"
echo "== 标题链接与按钮链接一致性 =="
python3 - "$BASE" <<'PY'
import re, sys, html, urllib.request
base = sys.argv[1]
def get(path):
return urllib.request.urlopen(base + path, timeout=10).read().decode()
page = get('/services')
cards = re.findall(r'<article class="catalog-card">.*?</article>', page, re.S)
bad = 0
for card in cards:
links = re.findall(r'<a[^>]*href="([^"]+)"', card)
title = re.search(r'<h2><a href="([^"]+)"', card)
if not title:
print(' FAIL 卡片缺标题链接'); bad += 1; continue
primary = [l for l in links if not l.startswith('/articles/')]
if primary and title.group(1) != primary[0]:
print(' FAIL 标题 href=%s 与主按钮 href=%s 不一致' % (title.group(1), primary[0])); bad += 1
print(' ok %d 张卡片标题与主按钮一致' % (len(cards) - bad) if bad == 0 else ' 共 %d 张卡片,%d 张不一致' % (len(cards), bad))
sys.exit(0 if bad == 0 else 1)
PY
[ $? -eq 0 ] && ok "标题与按钮目标一致" || no "标题与主按钮目标不一致"
echo "== 参考信息:目录条目在文章流中的可见性(不判定) =="
PUB=$(echo "$ROWS" | awk -F'|' '$3 == "published" {print $1}')
N=0
for slug in $PUB; do
if curl -s "$BASE/articles" | grep -q "href=\"/articles/$slug\""; then N=$((N+1)); fi
done
echo " /articles 列表中出现的目录条目: $N / $(echo "$PUB" | wc -l)"
M=0
for slug in $PUB; do
if curl -s "$BASE/sitemap.xml" | grep -q "/articles/$slug"; then M=$((M+1)); fi
done
echo " sitemap 中的目录条目: $M / $(echo "$PUB" | wc -l)"
echo ""
echo "== 结果: $PASS 通过, $FAIL 失败 =="
[ $FAIL -eq 0 ] || exit 1
+382
View File
@@ -0,0 +1,382 @@
'use strict';
const assert = require('node:assert/strict');
const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const baseURL = process.env.LAYSENSE_TEST_URL || 'http://127.0.0.1:8787';
const email = process.env.LAYSENSE_TEST_EMAIL;
const password = process.env.LAYSENSE_TEST_PASSWORD;
if (!email || !password) {
throw new Error('Set LAYSENSE_TEST_EMAIL and LAYSENSE_TEST_PASSWORD for a disposable test database.');
}
async function run(browser) {
const context = await browser.newContext({baseURL, viewport: {width: 1480, height: 960}, reducedMotion: 'reduce'});
const page = await context.newPage();
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
await page.goto('/admin/login');
await page.locator('[name=email]').fill(email);
await page.locator('[name=password]').fill(password);
await page.locator('form button[type=submit]').click();
await page.waitForURL('**/admin');
const csrf = await page.locator('[name=csrf]').first().inputValue();
const slug = 'studio-browser-' + Date.now().toString(36);
async function post(path, values) {
const response = await context.request.post(path, {
form: {csrf, ...values},
headers: {'X-Requested-With': 'XMLHttpRequest'},
});
assert.equal(response.status(), 200, await response.text());
return response.json();
}
await post('/admin/new-page', {slug, name: '画布测试页'});
await post('/admin/page-blocks/' + slug, {operation: 'create', key: 'fixtures', preset: 'text'});
await post('/admin/pages/' + slug + '/fixtures', {
version: '0', title: '媒体和链接', lead: '', style: 'plain',
body: '<p><img src="/assets/favicon.png" alt="示例图片" width="96"></p>'
+ '<p><a href="/services">示例链接</a></p>'
+ '<p id="copy-fixture">待复制段落</p><p>待删除段落</p>'
+ '<video controls width="260" preload="none"><source src="/assets/original/drag-in-components.mp4"></video>'
+ '<audio controls src="/assets/original/drag-in-components.mp4" preload="none"></audio>',
});
const editorPath = '/admin/pages/' + slug;
await page.goto(editorPath);
const version = await page.locator('#studio-page-settings [name=version]').inputValue();
await post(editorPath, {
version, name: '画布测试页', status: 'draft', title: '画布测试页',
description: '', heading: '画布测试页', accent: '', lead: '待删除的首屏简介',
image: '/assets/original/home-hero.webp', alt: '首屏示例', image_scale: '0',
});
await page.reload();
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');
await image.click();
await sizing.waitFor({state: 'visible'});
assert.equal(await image.getAttribute('data-studio-selected'), '');
const handle = page.getByRole('slider', {name: '媒体宽度'});
const initial = await image.boundingBox();
const grip = await handle.boundingBox();
await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
await page.mouse.down();
await page.mouse.move(grip.x + grip.width / 2 + 145, grip.y + grip.height / 2, {steps: 8});
assert((await image.boundingBox()).width > initial.width + 100);
await page.mouse.up();
const imageSize = await image.getAttribute('class');
assert.match(imageSize, /studio-media-\d+/);
assert.notEqual(imageSize, 'studio-media-100');
await image.dblclick();
await properties.waitFor({state: 'visible'});
assert.equal(await properties.locator('h2').textContent(), '正文图片');
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));
await hero.click();
await sizing.waitFor({state: 'visible'});
assert.equal(await hero.getAttribute('data-studio-selected'), '');
await handle.press('ArrowLeft');
assert.equal(await page.locator('[name=image_scale]').inputValue(), '99');
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');
await frame.locator('#fixtures a').click();
await tools.getByRole('button', {name: '属性'}).click();
await properties.waitFor({state: 'visible'});
assert.equal(await properties.locator('h2').textContent(), '正文链接');
await properties.locator('[name=url]').fill('/articles');
await properties.locator('button[type=submit]').click();
assert.equal(await frame.locator('#fixtures a').getAttribute('href'), '/articles');
for (const [tag, label] of [['video', '视频'], ['audio', '音频']]) {
const media = frame.locator('#fixtures ' + tag);
await media.dispatchEvent('dblclick');
await properties.waitFor({state: 'visible'});
assert.equal(await properties.locator('h2').textContent(), label);
await closeProperties();
}
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);
const oldParagraph = frame.getByText('待删除段落', {exact: true});
await oldParagraph.click();
await tools.getByRole('button', {name: '删除'}).click();
assert.equal(await oldParagraph.count(), 0);
await frame.getByText('待删除的首屏简介', {exact: true}).click();
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]');
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()));
return images.filter((image) => image.naturalWidth !== 768).length;
});
assert.equal(brokenPreviews, 0);
await gallery.locator('[data-template-filter=cover]').click();
assert.equal(await gallery.locator('[data-template-card]:visible').count(), 2);
const cover = gallery.locator('[data-template-preview=cover]');
await cover.hover();
const peek = gallery.locator('[data-template-peek]');
await peek.waitFor({state: 'visible'});
assert((await peek.boundingBox()).width > (await cover.boundingBox()).width);
await cover.focus();
await page.keyboard.press('Enter');
const dialog = gallery.locator('[data-template-dialog]');
await dialog.waitFor({state: 'visible'});
assert.equal(await dialog.locator('h2').textContent(), '图文封面');
await dialog.locator('[data-template-use]').click();
await frame.locator('section[id^=block-] h2').filter({hasText: '图文封面'}).waitFor();
await gallery.locator('[data-template-filter=""]').click();
const search = gallery.locator('[data-template-search]');
await search.fill('does-not-exist');
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();
await Promise.all([
page.waitForResponse((response) => response.url().endsWith(editorPath) && response.request().method() === 'POST' && response.ok()),
page.getByRole('button', {name: '保存页面', exact: true}).first().click(),
]);
await page.locator('[data-save-confirmation]').waitFor({state: 'visible'});
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.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);
assert.equal(await oldParagraph.count(), 0);
assert.equal(await page.locator('[name=lead]').inputValue(), '');
const feedSection = frame.locator('section[id^=block-]').filter({hasText: '分类文章'});
const feedId = await feedSection.getAttribute('id');
await feedSection.locator('.article-list').waitFor();
const phone = await browser.newContext({
baseURL, viewport: {width: 390, height: 844}, isMobile: true, hasTouch: true,
storageState: await context.storageState(),
});
const phonePage = await phone.newPage();
phonePage.on('pageerror', (error) => errors.push(error.message));
await phonePage.goto(editorPath);
const phoneGallery = phonePage.locator('[data-canvas-presets]');
await phoneGallery.locator('[data-template-filter=cover]').tap();
await phoneGallery.locator('[data-template-preview=banner]').tap();
await phoneGallery.locator('[data-template-dialog]').waitFor({state: 'visible'});
assert.equal(await phoneGallery.locator('[data-template-dialog] h2').textContent(), '横幅');
await phone.close();
await verifyArticleLibrary(browser, context, page, post, slug, feedId);
assert.deepEqual(errors, []);
await context.close();
}
async function verifyArticleLibrary(browser, context, page, post, slug, feedId) {
const category = String(Date.now());
await post('/admin/article-categories', {slug: category, name: '自定义测试分类'});
const articleSlug = slug + '-article';
await page.goto('/admin/articles/new');
const editor = page.locator('[data-editor-host]');
const markdown = editor.locator('.toastui-editor-md-container .ProseMirror');
const preview = editor.locator('.toastui-editor-md-preview');
await markdown.waitFor();
await preview.waitFor();
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();
await page.getByRole('button', {name: '保存文章'}).click();
await page.waitForURL(/\/admin\/articles\/\d+/);
const articleAdmin = new URL(page.url()).pathname;
const publishedPath = '/articles/' + articleSlug;
const sourcePage = await context.newPage();
await sourcePage.goto(publishedPath);
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();
const rich = editor.locator('.toastui-editor-ww-container .ProseMirror');
await rich.waitFor();
await rich.press('End');
await page.keyboard.insertText(' 富文本');
await page.getByRole('button', {name: '从媒体库插入图片'}).click();
await page.locator('[data-media-query]').fill('favicon.png');
page.once('dialog', (dialog) => dialog.accept('媒体库图片'));
await page.locator('.picker-item', {hasText: 'favicon.png'}).click();
await rich.locator('img[alt="媒体库图片"]').waitFor();
await page.getByRole('button', {name: '保存文章'}).click();
await page.locator('[data-save-confirmation]').waitFor({state: 'visible'});
await page.reload();
await rich.waitFor();
assert.equal(await page.locator('[name=body_format]').inputValue(), 'html');
await sourcePage.reload();
assert.match(await sourcePage.locator('[itemprop=articleBody]').textContent(), /Markdown 分屏 富文本/);
await sourcePage.locator('[itemprop=articleBody] img[alt="媒体库图片"]').waitFor();
const sectionPath = '/admin/pages/' + slug + '/' + feedId;
await page.goto(sectionPath);
await page.locator('[name=feed_mode]').selectOption('merged');
await page.locator('[name="feed_categories[]"][value=announcement]').uncheck();
await page.locator('[name="feed_categories[]"][value=product]').uncheck();
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';
await sourcePage.goto(canvasPath);
const feed = sourcePage.locator('#' + feedId + ' .article-feed');
assert.equal(await feed.locator('a[href="' + publishedPath + '"]').count(), 1);
assert.equal(await feed.getByRole('tab').count(), 0);
await page.locator('[name=feed_mode]').selectOption('tabs');
await page.getByRole('button', {name: '保存区块'}).click();
await page.locator('[data-save-confirmation]').waitFor({state: 'visible'});
contentVersion = await page.locator('[name=version]').inputValue();
assert.equal(contentVersion, '2');
await sourcePage.reload();
const customTab = feed.getByRole('tab', {name: '自定义测试分类'});
await customTab.waitFor();
await feed.getByRole('tab', {name: '新闻'}).press('ArrowRight');
assert.equal(await customTab.getAttribute('aria-selected'), 'true');
assert.equal(await feed.getByRole('tabpanel').count(), 1);
assert.equal(await feed.locator('a[href="' + publishedPath + '"]:visible').count(), 1);
const noJS = await browser.newContext({baseURL, javaScriptEnabled: false, storageState: await context.storageState()});
const noJSPage = await noJS.newPage();
await noJSPage.goto(canvasPath);
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');
assert.equal(await sourcePage.locator('.network-group').count(), 2);
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 alignment, editor elements and modules, persistence, and scoped article archives.');
} finally {
await browser.close();
}
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});