Author SHA1 Message Date
ChatGPT 4db9af6404 Reflow home shortcuts and support article deletion 2026-11-22 02:00:29 +08:00
ChatGPT 02e8685bc2 Make catalog and article landing pages editable 2026-11-22 01:37:33 +08:00
ChatGPT 92354d7e4a Manage dynamic blocks and expand the editor library 2026-11-22 00:59:59 +08:00
hy 828dfc09f9 Merge pull request '恢复原站页脚和独立资源链接' (#11) from ChatGPT/laysense.cn:restore-original-footer into main 2026-11-22 00:21:15 +08:00
hy 904812fd95 Merge pull request '分类优先的组件与元素库,优化网站后台' (#10) from ChatGPT/laysense.cn:categorized-admin-library into main 2026-11-22 00:21:12 +08:00
hy d6fee652db Merge pull request '复核 #7、#8:修正目录详情判定和失效的回归测试' (#9) from ChatGPT/laysense.cn:audit-directory-links into main 2026-11-22 00:20:58 +08:00
ChatGPT abccb8c004 Restore the original Laysense footer 2026-11-21 23:49:21 +08:00
ChatGPT 2cf63b61ba Add category-first template library and improve admin dashboard 2026-11-21 23:44:26 +08:00
ChatGPT 2b01537cf3 Audit merged directory links and test rendered fallbacks 2026-11-21 23:36:20 +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
92 changed files with 2062 additions and 466 deletions
+7 -5
View File
@@ -27,13 +27,15 @@ php bin/admin.php reset admin@example.com
## 后台编辑 ## 后台编辑
- **页面设计**支持新建草稿、发布和撤回。首屏标题与简介可在桌面或手机画布中直接编辑。区块支持新增、排序、删除、可视化编辑、媒体插入和 HTML 源码。单击画布元素可用浮动工具条复制或删除。选中媒体后,可拖动边缘手柄调整宽度。编辑器左侧可按分类和名称查找模板。悬停或键盘聚焦缩略图可放大,点击可打开预览。 - **网站后台**可按名称、地址或发布状态查找页面,从列表打开画布、公开页或草稿预览。
- **页面设计**支持新建草稿、发布和撤回。首屏标题与简介可在桌面或手机画布中直接编辑。区块支持新增、排序、删除、可视化编辑、媒体插入和 HTML 源码。单击画布元素可用浮动工具条复制或删除。选中媒体后,可拖动边缘手柄调整宽度。浮动工具条可将正文元素、区块标题和首屏元素对齐到左侧、中央或右侧。编辑器左侧分为「组件」「元素」「图层」。先进入分类,再查找并插入模板或基础元素。可在功能分类中复用产品图文、特性组、服务报价等内置模板,徽标、按钮组、面包屑、进度、通知和折叠等元素参考 [Preline UI 免费组件文档](https://preline.co/docs/index.html),用本站样式实现。悬停或键盘聚焦缩略图可放大,点击可打开预览。
- **媒体库**集中列出项目静态文件及上传文件,支持查找、选取、复制路径、改名和归档。归档资源的已有 URL 保持可访问。上传文件放在 `LAYSENSE_MEDIA_DIR`,由 `/assets/uploads/` 提供。 - **媒体库**集中列出项目静态文件及上传文件,支持查找、选取、复制路径、改名和归档。归档资源的已有 URL 保持可访问。上传文件放在 `LAYSENSE_MEDIA_DIR`,由 `/assets/uploads/` 提供。
- **文章**使用自托管的 TOAST UI Editor 3.2.2(MIT)。Markdown 左侧源码、右侧实时预览,富文本使用所见即所得模式。文章可以加入多个分类,可在「管理分类」创建新分类。 - **文章**使用自托管的 TOAST UI Editor 3.2.2(MIT)。Markdown 左侧源码、右侧实时预览,富文本使用所见即所得模式。文章可以加入多个分类,可在「管理分类」创建新分类。
- **分类文章**支持在任意页面添加,保存区块后在「图层」中编辑分类、展示数量和合并或标签页模式。 - **普通页面**包括 `/services`、`/articles` 和 `/contact`。产品目录和分类文章模块的设置可在画布编辑。动态页默认显示公告、新闻和产品动态。
- **分类文章**支持在任意页面添加,选中动态模块后可用浮动工具条打开设置、复制或删除,随页面一起保存。文章列表、产品目录和项目与伙伴卡片共用分类设置。「查看全部」和翻页只列出该区块所选的分类。
- **产品与服务**(`/services`)和**支持项目与合作伙伴**(`/network`)由文章分类生成。通过文章的目录卡片设置图片、链接和排序,使用草稿状态可从目录撤下。 - **产品与服务**(`/services`)和**支持项目与合作伙伴**(`/network`)由文章分类生成。通过文章的目录卡片设置图片、链接和排序,使用草稿状态可从目录撤下。
- **网站设置**分别编辑页头标志、导航及按钮,和页脚的公司信息、链接与备注。CDN 设置接受 HTTPS 源站地址。浏览器看到的公开 `/assets/…` 路径使用该源站。 - **网站设置**分别编辑页头标志、导航及按钮,和页脚的公司信息、产品、公司及资源链接和备注。页脚设置可恢复原站内容。CDN 设置接受 HTTPS 源站地址。浏览器看到的公开 `/assets/…` 路径使用该源站。
- 文章支持摘要和标签。状态选「草稿」可撤回公开文章。已发布文章改网址标识后,旧标识会自动跳转。 - 文章支持摘要和标签。状态选「草稿」可撤回公开文章。编辑页底部可永久删除文章,重复安装也会保留删除结果。已发布文章改网址标识后,旧标识会自动跳转。
- 首页动态、分类列表和站点地图随发布状态更新。源代码和 SQLite 数据分开管理。安装命令可重复执行,已编辑的内容会保留。 - 首页动态、分类列表和站点地图随发布状态更新。源代码和 SQLite 数据分开管理。安装命令可重复执行,已编辑的内容会保留。
## 生产运行 ## 生产运行
@@ -70,7 +72,7 @@ location = /admin/media {
| `LAYSENSE_SECURE_COOKIES` | 默认关闭 · 本地 HTTP 使用默认值。生产 HTTPS 设置为 `1`。 | | `LAYSENSE_SECURE_COOKIES` | 默认关闭 · 本地 HTTP 使用默认值。生产 HTTPS 设置为 `1`。 |
| `LAYSENSE_TRUSTED_PROXIES` | 默认 `127.0.0.1,::1` · 逗号分隔的受信反代 IP,设为空字符串可关闭信任 | | `LAYSENSE_TRUSTED_PROXIES` | 默认 `127.0.0.1,::1` · 逗号分隔的受信反代 IP,设为空字符串可关闭信任 |
SQLite 已启用 WAL。本版需要新的 SQLite 文件。将 `LAYSENSE_DB` 指向新文件,执行 `php bin/install.php`,再按上面的步骤创建管理员并重启 Webman。安装会预载网站自带页面、文章、产品和伙伴目录。服务用户需要对 SQLite 目录、媒体目录和 `runtime/` 有写权限。备份可用 `sqlite3 storage/laysense.sqlite ".backup 'laysense-backup.sqlite'"`,媒体目录单独保存。 SQLite 已启用 WAL。使用上一版多分类文章结构的站点,可用当前 `LAYSENSE_DB` 运行 `php bin/install.php` 增量安装,之后重启 Webman。安装会补齐 `/services`、`/articles` 和 `/contact` 的页面记录,并一次性导入首页五联导航和伙伴动态模块。全新安装时,将 `LAYSENSE_DB` 指向新文件并按上面的步骤初始化和创建管理员。安装会预载网站自带页面、文章、产品和伙伴目录。服务用户需要对 SQLite 目录、媒体目录和 `runtime/` 有写权限。备份可用 `sqlite3 storage/laysense.sqlite ".backup 'laysense-backup.sqlite'"`,媒体目录单独保存。
### CDN ### CDN
+117 -3
View File
@@ -8,38 +8,152 @@ final class BlockTemplates
{ {
public const ARTICLE_FEED = '{"categories":["announcement","news","product"],"mode":"merged","limit":6}'; public const ARTICLE_FEED = '{"categories":["announcement","news","product"],"mode":"merged","limit":6}';
public const NETWORK_FEED = '{"categories":["supported-projects","partners"],"mode":"network","limit":30}';
public const CATALOG_FEED = '{"categories":["services"],"mode":"catalog","limit":30}';
public const PRODUCT_LINKS = '<div class="hero-directory"><a class="overline directory-label" href="/services">产品与服务</a><a href="/pagepan"><span>PAGEPAN</span><small>可视化建站</small></a><a href="/highspeaker"><span>HighSpeaker DNS</span><small>开源智能解析</small></a><a href="/sc"><span>软著代理</span><small>登记申请与材料服务</small></a><a href="/shnu-sc"><span>SHNU 学生</span><small>软著申请方案</small></a></div>';
public const ELEMENT_GROUPS = [
'text-elements' => ['文字与列表', [
'paragraph' => ['段落', '<p>填写正文。</p>'],
'subheading' => ['小标题', '<h3>填写小标题</h3>'],
'lead' => ['导语', '<p class="studio-lead">填写本节的导语。</p>'],
'blockquote' => ['引用', '<blockquote><p>填写需要引用的内容。</p></blockquote>'],
'bullet-list' => ['项目列表', '<ul><li>填写列表项</li><li>填写列表项</li></ul>'],
'ordered-list' => ['编号列表', '<ol><li>填写第一项</li><li>填写第二项</li></ol>'],
'heading-kicker' => ['标题眉标', '<p class="overline">填写分类名称</p>'],
'tag' => ['徽标', '<p><span class="studio-badge">填写标签</span></p>'],
'large-number' => ['重点数字', '<p class="price-value">填写数字</p>'],
'definition-list' => ['术语说明', '<dl class="studio-definitions"><dt>填写术语</dt><dd>填写术语说明。</dd></dl>'],
]],
'link-elements' => ['链接与按钮', [
'button' => ['主按钮', '<p><a class="button button-primary" href="#contact">联系来笙</a></p>'],
'outline-button' => ['描边按钮', '<p><a class="button button-outline" href="/services">查看服务</a></p>'],
'text-link' => ['文字链接', '<p><a href="/articles">阅读文章</a></p>'],
'button-group' => ['按钮组', '<div class="actions studio-button-group"><a class="button button-primary" href="/services">查看服务</a><a class="button button-outline" href="#contact">联系团队</a></div>'],
'breadcrumbs' => ['面包屑', '<p class="breadcrumbs"><a href="/">首页</a><span> / </span><span>当前页面</span></p>'],
'download-link' => ['下载入口', '<p><a class="button button-outline" href="/pagepan#download">查看下载</a></p>'],
'email-link' => ['邮件链接', '<p><a href="mailto:hello@example.com">发送邮件</a></p>'],
]],
'media-elements' => ['图片与影音', [
'image' => ['图片', '', 'image/'],
'video' => ['视频', '', 'video/'],
'audio' => ['音频', '', 'audio/'],
'qr-image' => ['二维码', '', 'image/'],
'image-link' => ['图片链接', '<p><a href="/pagepan"><img src="/assets/original/pagepan-example.webp" alt="PAGEPAN 产品预览" loading="lazy"></a></p>'],
]],
'structure-elements' => ['版式与数据', [
'separator' => ['分割线', '<hr class="studio-divider">'],
'spacer' => ['留白', '<div class="studio-spacer"></div>'],
'code' => ['代码块', '<pre class="studio-code"><code>填写代码</code></pre>'],
'basic-table' => ['数据表格', '<table><thead><tr><th scope="col">名称</th><th scope="col">数据</th></tr></thead><tbody><tr><td>填写名称</td><td>填写数据</td></tr></tbody></table>'],
'progress' => ['进度条', '<div class="studio-progress"><p>完成进度</p><progress max="100" value="65">65%</progress></div>'],
'alert' => ['提示卡', '<div class="studio-notice"><p><strong>请注意</strong></p><p>填写一条提示信息。</p></div>'],
'simple-card' => ['内容卡片', '<article class="content-card"><h3>填写卡片标题</h3><p>填写卡片内容。</p></article>'],
'link-card' => ['链接卡片', '<article class="content-card"><h3>查看资料</h3><p>填写链接指向的资料说明。</p><a href="/articles">打开资料</a></article>'],
'list-group' => ['列表组', '<ul class="studio-resources"><li><a href="/services">产品与服务</a><span>目录</span></li><li><a href="/articles">来笙动态</a><span>文章</span></li></ul>'],
'empty-card' => ['空状态', '<div class="studio-empty"><h3>暂无内容</h3><p>填写访客可以执行的下一步。</p><a href="/articles">查看站点动态</a></div>'],
'status-note' => ['状态提示', '<div class="studio-notice studio-success-note"><p><strong>已完成</strong></p><p>填写操作结果或服务状态。</p></div>'],
'disclosure' => ['折叠内容', '<div class="faq"><details><summary>填写折叠标题</summary><div><p>填写展开后的内容。</p></div></details></div>'],
]],
];
public const GROUPS = [ public const GROUPS = [
'content' => ['标题与正文', [ 'content' => ['标题与正文', [
'headline' => ['标题与简介', '<div class="studio-intro"><h3>填写区块标题</h3><p>用一句话补充背景或说明。</p></div>'], 'headline' => ['标题与简介', '<div class="studio-intro"><h3>填写区块标题</h3><p>用一句话补充背景或说明。</p></div>'],
'text' => ['正文', '<p>在这里输入区块内容。</p>'], 'text' => ['正文', '<p>在这里输入区块内容。</p>'],
'articles' => ['分类文章', ''], 'articles' => ['分类文章', '', '', self::ARTICLE_FEED],
'network' => ['支持项目与合作伙伴', '', '', self::NETWORK_FEED],
'list' => ['步骤列表', '<ol><li>填写第一步</li><li>填写第二步</li><li>填写第三步</li></ol>'], 'list' => ['步骤列表', '<ol><li>填写第一步</li><li>填写第二步</li><li>填写第三步</li></ol>'],
'notice' => ['重点提示', '<div class="studio-notice"><h3>填写重要提示</h3><p>说明访客需要知悉的事项、条件或时间。</p></div>'],
]], ]],
'cover' => ['封面与横幅', [ '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>'], '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>'], 'banner' => ['横幅', '<div class="studio-banner"><h3>用一句话介绍你的项目</h3><p>简要说明项目能为访客做什么。</p><a class="button button-primary" href="/services">了解更多</a></div>'],
'two-actions' => ['双按钮横幅', '<div class="studio-banner studio-banner-two"><div><h3>选择下一步</h3><p>介绍访客可以立即做什么。</p></div><div class="actions"><a class="button button-primary" href="/services">查看服务</a><a class="button button-outline" href="/#contact">联系我们</a></div></div>'],
]], ]],
'layout' => ['图文与布局', [ 'layout' => ['图文与布局', [
'image' => ['图文', '<div class="studio-split"><img src="/assets/original/home-hero.webp" alt="" loading="lazy"><div><h3>介绍主题</h3><p>在这里说明图片或产品。</p></div></div>'], '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>'], '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' => ['特性与口碑', [
'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>'], '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>'], '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' => ['表格与问答', [ '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>'], '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>'], '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>'],
'changelog' => ['更新记录', '<div class="studio-releases"><article><h3>版本 2.0</h3><p>填写主要功能或改进。</p></article><article><h3>版本 1.0</h3><p>填写上一版本的更新内容。</p></article></div>'],
'pricing' => ['双方案报价', '<div class="card-grid price-grid studio-pricing"><article class="content-card price-card"><h3>基础方案</h3><p class="price-value">填写价格</p><p>填写方案包含的服务。</p><a class="button button-outline" href="/#contact">咨询基础方案</a></article><article class="content-card price-card"><h3>进阶方案</h3><p class="price-value">填写价格</p><p>填写扩展服务或权益。</p><a class="button button-primary" href="/#contact">咨询进阶方案</a></article></div>'],
]], ]],
'actions' => ['导航与引导', [ 'actions' => ['导航与引导', [
'service-catalog' => ['产品与服务目录', '', '', self::CATALOG_FEED],
'product-links' => ['产品与服务五联导航', self::PRODUCT_LINKS],
'navigation' => ['快速导航', '<ul class="studio-quick-nav"><li><a href="/services">产品与服务</a></li><li><a href="/articles">动态与文章</a></li><li><a href="/#contact">联系来笙</a></li></ul>'], 'navigation' => ['快速导航', '<ul class="studio-quick-nav"><li><a href="/services">产品与服务</a></li><li><a href="/articles">动态与文章</a></li><li><a href="/#contact">联系来笙</a></li></ul>'],
'cta' => ['行动按钮', '<p>说明下一步。</p><p><a class="button button-primary" href="#contact">联系来笙</a></p>'], 'cta' => ['行动按钮', '<p>说明下一步。</p><p><a class="button button-primary" href="#contact">联系来笙</a></p>'],
'resources' => ['资料与链接', '<ul class="studio-resources"><li><a href="/pagepan#download">获取 PAGEPAN</a><span>应用下载</span></li><li><a href="/articles">浏览动态与文档</a><span>网站资源</span></li></ul>'],
'contact-card' => ['联系方式', '<div class="studio-contact"><div><h3>联系团队</h3><p>填写咨询范围与回复时间。</p></div><dl class="studio-definitions"><dt>电子邮件</dt><dd><a href="mailto:hello@example.com">hello@example.com</a></dd><dt>服务时间</dt><dd>填写工作时间</dd></dl></div>'],
]], ]],
]; ];
public static function groups(): array
{
static $groups;
if ($groups !== null) {
return $groups;
}
$groups = self::GROUPS;
$seed = json_decode(file_get_contents(dirname(__DIR__, 2) . '/resources/seed.json'), true, flags: JSON_THROW_ON_ERROR);
$sectionGroups = [
'product' => 'layout', 'about' => 'content', 'blog' => 'content',
'features' => 'features', 'support' => 'features', 'why' => 'features', 'stories' => 'features',
'pricing' => 'details', 'comparison' => 'details', 'materials' => 'details', 'fees' => 'details',
'faq' => 'details', 'terms' => 'details',
'get' => 'actions', 'options' => 'actions', 'go' => 'actions', 'benefits' => 'layout',
];
foreach ($seed['pages'] as $page) {
if (!in_array($page['slug'], ['home', 'highspeaker', 'sc', 'shnu-sc'], true)) {
continue;
}
$links = '';
foreach ($page['actions'] as [$url, $label]) {
$links .= '<a class="button button-outline" href="' . View::escape($url) . '">' . View::escape($label) . '</a>';
}
$hero = '<div class="studio-cover"><img src="' . View::escape($page['image']) . '" alt="' . View::escape($page['alt']) . '" loading="lazy">'
. '<div><h3>' . View::escape(trim($page['heading'] . ' ' . $page['accent'])) . '</h3><p>' . View::escape($page['lead'])
. '</p><div class="actions">' . $links . '</div></div></div>';
$prefix = 'existing-' . $page['slug'] . '-';
$groups['cover'][1][$prefix . 'hero'] = ['产品图文 · ' . $page['name'], $hero];
foreach ($page['sections'] as $section) {
$group = $sectionGroups[$section['key']] ?? null;
if ($group === null) {
continue;
}
$groups[$group][1][$prefix . $section['key']] = [
$section['key'] === 'features' ? '特性组' : $section['title'],
Html::sanitize($section['body']), $section['lead'],
isset($section['feed']) ? Database::json($section['feed']) : null,
$section['style'],
];
}
}
return $groups;
}
public static function find(string $key): ?array public static function find(string $key): ?array
{ {
foreach (self::GROUPS as [, $templates]) { foreach (self::groups() as [, $templates]) {
if (isset($templates[$key])) { if (isset($templates[$key])) {
return $templates[$key]; return $templates[$key];
} }
+29 -3
View File
@@ -10,6 +10,10 @@ use Throwable;
final class Database final class Database
{ {
// Avoid reusing a deleted ID that may still be open in an editing form.
public const NEXT_ARTICLE_ID = 'MAX(COALESCE((SELECT MAX(id) FROM articles), 0),
COALESCE((SELECT MAX(article_id) FROM article_deletions), 0)) + 1';
private static ?PDO $connection = null; private static ?PDO $connection = null;
public static function connect(): PDO public static function connect(): PDO
@@ -44,6 +48,12 @@ final class Database
throw new RuntimeException('请将 LAYSENSE_DB 指向一个新的 SQLite 文件,再运行安装命令。'); throw new RuntimeException('请将 LAYSENSE_DB 指向一个新的 SQLite 文件,再运行安装命令。');
} }
$pdo->exec(file_get_contents($root . '/resources/schema.sql')); $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 = $pdo->prepare('INSERT OR IGNORE INTO site_settings (id, payload) VALUES (1, ?)');
$site->execute([self::json($seed['site'])]); $site->execute([self::json($seed['site'])]);
@@ -69,13 +79,29 @@ final class Database
} }
} }
if ((int) $pdo->query('PRAGMA user_version')->fetchColumn() === 0) {
$heroDirectory = $pdo->prepare("INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, position)
VALUES ('home', 'hero-directory', '产品与服务导航', '', 'hero-links', ?, -1)");
$heroDirectory->execute([BlockTemplates::PRODUCT_LINKS]);
$network = $pdo->prepare("INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, position)
SELECT 'home', 'network', '支持项目与合作伙伴', '', 'plain', '', ?, COALESCE(MAX(position), -1) + 1
FROM sections WHERE page_slug = 'home'");
$network->execute([BlockTemplates::NETWORK_FEED]);
if ($heroDirectory->rowCount() + $network->rowCount() > 0) {
$pdo->exec("UPDATE pages SET version = version + 1 WHERE slug = 'home'");
}
$pdo->exec('PRAGMA user_version = 1');
}
$category = $pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)'); $category = $pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
foreach (Repository::CATEGORIES as $slug => $name) { foreach (Repository::CATEGORIES as $slug => $name) {
$category->execute([$slug, $name]); $category->execute([$slug, $name]);
} }
$article = $pdo->prepare("INSERT OR IGNORE INTO articles $article = $pdo->prepare("INSERT OR IGNORE INTO articles
(slug, title, summary, body, body_format, card, tags, status, published_at, updated_at, legacy_path) (id, 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 = ?)"); SELECT " . self::NEXT_ARTICLE_ID . ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
WHERE NOT EXISTS (SELECT 1 FROM article_redirects WHERE slug = ?)
AND NOT EXISTS (SELECT 1 FROM article_deletions WHERE slug = ?)");
$link = $pdo->prepare('INSERT INTO article_category_links (article_id, category_slug) VALUES (?, ?)'); $link = $pdo->prepare('INSERT INTO article_category_links (article_id, category_slug) VALUES (?, ?)');
foreach ($seed['articles'] as $item) { foreach ($seed['articles'] as $item) {
$format = $item['body_format'] ?? 'markdown'; $format = $item['body_format'] ?? 'markdown';
@@ -84,7 +110,7 @@ final class Database
$item['slug'], $item['title'], $item['summary'] ?? '', $item['slug'], $item['title'], $item['summary'] ?? '',
$format === 'html' ? Html::sanitize($item['body']) : $item['body'], $format, $format === 'html' ? Html::sanitize($item['body']) : $item['body'], $format,
self::json($item['card'] ?? []), self::json($item['tags'] ?? []), self::json($item['card'] ?? []), self::json($item['tags'] ?? []),
$item['status'] ?? 'published', $date, $date ?? gmdate(DATE_ATOM), $item['legacy'] ?? null, $item['slug'], $item['status'] ?? 'published', $date, $date ?? gmdate(DATE_ATOM), $item['legacy'] ?? null, $item['slug'], $item['slug'],
]); ]);
if ($article->rowCount() === 1) { if ($article->rowCount() === 1) {
$id = $pdo->lastInsertId(); $id = $pdo->lastInsertId();
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMXPath;
final class DirectoryCard
{
public static function links(array $article, string $body): array
{
$detail = self::hasText($article['summary']) || self::hasBody($body) ? '/articles/' . $article['slug'] : '';
$primary = ($article['card']['url'] ?? '') ?: $detail;
return ['primary' => $primary, 'detail' => $primary === $detail ? '' : $detail];
}
private static function hasText(string $text): bool
{
return preg_match('/[^\s\p{Z}\p{Cf}]/u', $text) === 1;
}
private static function hasBody(string $html): bool
{
if (self::hasText(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8'))) {
return true;
}
if (!str_contains($html, 'src=')) {
return false;
}
$document = new DOMDocument();
$document->loadHTML('<meta charset="utf-8">' . $html, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
$xpath = new DOMXPath($document);
return (bool) $xpath->evaluate('boolean(//img[@src] | //audio[@src] | //video[@src] | //audio/source[@src] | //video/source[@src])');
}
}
+19 -1
View File
@@ -12,6 +12,8 @@ use RuntimeException;
final class Html final class Html
{ {
public const ALIGNMENTS = ['left', 'center', 'right'];
private const TAGS = [ private const TAGS = [
'a' => ['href'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [], 'a' => ['href'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [],
'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'], 'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
@@ -86,7 +88,7 @@ final class Html
return $result; return $result;
} }
public static function sanitize(string $html): string public static function sanitize(string $html, ?string $anchorPrefix = null): string
{ {
$document = new DOMDocument('1.0', 'UTF-8'); $document = new DOMDocument('1.0', 'UTF-8');
$document->loadHTML('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' . $html . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET); $document->loadHTML('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' . $html . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
@@ -95,6 +97,22 @@ final class Html
return ''; return '';
} }
self::sanitizeChildren($body); self::sanitizeChildren($body);
if ($anchorPrefix !== null) {
$ids = [];
foreach ($body->getElementsByTagName('*') as $element) {
$id = $element->getAttribute('id');
if ($id !== '') {
$ids[$id] = $anchorPrefix . '-' . $id;
$element->setAttribute('id', $ids[$id]);
}
}
foreach ($body->getElementsByTagName('a') as $link) {
$href = $link->getAttribute('href');
if (str_starts_with($href, '#') && isset($ids[substr($href, 1)])) {
$link->setAttribute('href', '#' . $ids[substr($href, 1)]);
}
}
}
$output = ''; $output = '';
foreach ($body->childNodes as $child) { foreach ($body->childNodes as $child) {
$output .= $document->saveHTML($child); $output .= $document->saveHTML($child);
+48 -18
View File
@@ -52,7 +52,7 @@ final class Repository
if (!$page) { if (!$page) {
return null; return null;
} }
foreach (['actions', 'quicklinks'] as $key) { foreach (['actions', 'quicklinks', 'alignments'] as $key) {
$page[$key] = json_decode($page[$key], true, flags: JSON_THROW_ON_ERROR); $page[$key] = json_decode($page[$key], true, flags: JSON_THROW_ON_ERROR);
} }
$query = $this->pdo->prepare('SELECT * FROM sections WHERE page_slug = ? ORDER BY position, key'); $query = $this->pdo->prepare('SELECT * FROM sections WHERE page_slug = ? ORDER BY position, key');
@@ -67,19 +67,28 @@ final class Repository
return $this->one('SELECT * FROM sections WHERE page_slug = ? AND key = ?', [$page, $key]); return $this->one('SELECT * FROM sections WHERE page_slug = ? AND key = ?', [$page, $key]);
} }
public function publishedFeed(string $page, string $key): ?array
{
return $this->one("SELECT sections.title, sections.feed FROM sections
JOIN pages ON pages.slug = sections.page_slug
WHERE pages.slug = ? AND pages.status = 'published' AND sections.key = ? AND sections.feed IS NOT NULL", [$page, $key]);
}
public function savePage(string $slug, array $data, int $version, array $sections = []): void public function savePage(string $slug, array $data, int $version, array $sections = []): void
{ {
Database::write(function (PDO $pdo) use ($slug, $data, $version, $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 = ?, $query = $pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?,
image = ?, alt = ?, image_scale = ?, actions = ?, quicklinks = ?, status = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?'); image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, status = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?');
$query->execute([ $query->execute([
$data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'], $data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'],
$data['image'], $data['alt'], $data['image_scale'], Database::json($data['actions']), Database::json($data['quicklinks']), $data['image'], $data['alt'], $data['image_scale'], Database::json($data['alignments']), Database::json($data['actions']), Database::json($data['quicklinks']),
$data['status'], self::now(), $slug, $version, $data['status'], self::now(), $slug, $version,
]); ]);
self::checkVersion($query->rowCount()); self::checkVersion($query->rowCount());
foreach ($sections as $section) { foreach ($sections as $section) {
if ($section['version'] === null) { if (!empty($section['delete'])) {
self::deleteSection($pdo, $slug, $section['key'], $section['version']);
} elseif ($section['version'] === null) {
self::insertSection($pdo, $slug, $section['key'], $section); self::insertSection($pdo, $slug, $section['key'], $section);
} else { } else {
self::updateSection($pdo, $slug, $section['key'], $section, $section['version']); self::updateSection($pdo, $slug, $section['key'], $section, $section['version']);
@@ -98,30 +107,37 @@ final class Repository
private static function updateSection(PDO $pdo, string $page, string $key, array $data, int $version): void private static function updateSection(PDO $pdo, string $page, string $key, array $data, int $version): void
{ {
$query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, feed = ?, version = version + 1 $query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, feed = ?, alignments = COALESCE(?, alignments), version = version + 1
WHERE page_slug = ? AND key = ? AND version = ?'); WHERE page_slug = ? AND key = ? AND version = ?');
$query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $data['feed'] ?? null, $page, $key, $version]); $query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $data['feed'] ?? null, $data['alignments'] ?? null, $page, $key, $version]);
self::checkVersion($query->rowCount()); self::checkVersion($query->rowCount());
} }
public function createSection(string $page, string $key, string $title, string $style, string $body, ?string $feed = null): void public function createSection(string $page, string $key, string $title, string $style, string $body, ?string $feed = null, string $lead = ''): void
{ {
Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body, $feed): void { Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body, $feed, $lead): void {
self::insertSection($pdo, $page, $key, compact('title', 'style', 'body', 'feed') + ['lead' => '']); self::insertSection($pdo, $page, $key, compact('title', 'style', 'body', 'feed', 'lead'));
self::touchPage($pdo, $page, structureChanged: true); self::touchPage($pdo, $page, structureChanged: true);
}); });
} }
private static function insertSection(PDO $pdo, string $page, string $key, array $data): void private static function insertSection(PDO $pdo, string $page, string $key, array $data): void
{ {
$query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, position) $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 = ?'); SELECT ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?');
$query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $page]); $query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $data['alignments'] ?? '{}', $page]);
if ($query->rowCount() !== 1) { if ($query->rowCount() !== 1) {
throw new RuntimeException('此区块锚点已被使用。'); throw new RuntimeException('此区块锚点已被使用。');
} }
} }
private static function deleteSection(PDO $pdo, string $page, string $key, int $version): void
{
$query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?');
$query->execute([$page, $key, $version]);
self::checkVersion($query->rowCount());
}
public function arrangeSection(string $page, string $key, string $operation, int $version, int $pageVersion): void public function arrangeSection(string $page, string $key, string $operation, int $version, int $pageVersion): void
{ {
Database::write(function (PDO $pdo) use ($page, $key, $operation, $version, $pageVersion): void { Database::write(function (PDO $pdo) use ($page, $key, $operation, $version, $pageVersion): void {
@@ -130,14 +146,12 @@ final class Repository
$revision = $current->fetchColumn(); $revision = $current->fetchColumn();
self::checkVersion($revision !== false && (int) $revision === $pageVersion ? 1 : 0); self::checkVersion($revision !== false && (int) $revision === $pageVersion ? 1 : 0);
if ($operation === 'delete') { if ($operation === 'delete') {
$query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?'); self::deleteSection($pdo, $page, $key, $version);
$query->execute([$page, $key, $version]);
self::checkVersion($query->rowCount());
self::touchPage($pdo, $page, structureChanged: true); self::touchPage($pdo, $page, structureChanged: true);
return; return;
} }
$query = $pdo->prepare('SELECT key, version FROM sections WHERE page_slug = ? ORDER BY position, key'); $query = $pdo->prepare("SELECT key, version FROM sections WHERE page_slug = ? AND style <> 'hero-links' ORDER BY position, key");
$query->execute([$page]); $query->execute([$page]);
$revisions = $query->fetchAll(PDO::FETCH_KEY_PAIR); $revisions = $query->fetchAll(PDO::FETCH_KEY_PAIR);
if (!array_key_exists($key, $revisions)) { if (!array_key_exists($key, $revisions)) {
@@ -250,8 +264,8 @@ final class Repository
]; ];
if ($id === null) { if ($id === null) {
$query = $pdo->prepare('INSERT INTO articles $query = $pdo->prepare('INSERT INTO articles
(slug, title, summary, body, body_format, card, tags, status, published_at, updated_at) (id, slug, title, summary, body, body_format, card, tags, status, published_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); VALUES (' . Database::NEXT_ARTICLE_ID . ', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$query->execute($values); $query->execute($values);
$id = (int) $pdo->lastInsertId(); $id = (int) $pdo->lastInsertId();
} else { } else {
@@ -275,6 +289,22 @@ final class Repository
}); });
} }
public function deleteArticle(int $id, int $version): void
{
Database::write(function (PDO $pdo) use ($id, $version): void {
// Keep the original seed slug even if the article has been renamed.
$deletions = $pdo->prepare('INSERT INTO article_deletions (slug, article_id)
SELECT slug, id FROM articles WHERE id = :id
UNION ALL SELECT slug, article_id FROM article_redirects WHERE article_id = :id
ON CONFLICT (slug) DO UPDATE SET article_id = excluded.article_id');
$deletions->execute(['id' => $id]);
$delete = $pdo->prepare('DELETE FROM articles WHERE id = ? AND version = ?');
$delete->execute([$id, $version]);
self::checkVersion($delete->rowCount());
});
}
public function sitemapArticles(): iterable public function sitemapArticles(): iterable
{ {
$query = $this->pdo->query("SELECT slug, updated_at FROM articles WHERE status = 'published' $query = $this->pdo->query("SELECT slug, updated_at FROM articles WHERE status = 'published'
+30 -4
View File
@@ -12,18 +12,44 @@ final class SiteDesign
public const DEFAULT_HEADER = [ public const DEFAULT_HEADER = [
'logo' => '/assets/wordmark.webp', 'alt' => 'Laysense 来笙', 'logo' => '/assets/wordmark.webp', 'alt' => 'Laysense 来笙',
'links' => [['/', '首页'], ['/services', '产品与服务'], ['/articles', '动态'], ['/#about', '关于来笙']], 'links' => [['/', '首页'], ['/services', '产品与服务'], ['/articles', '动态'], ['/#about', '关于来笙']],
'button' => ['#contact', '联系来笙'], 'button' => ['/contact', '联系来笙'],
]; ];
public const DEFAULT_FOOTER = [ public const DEFAULT_FOOTER = [
'logo' => '/assets/wordmark.webp', 'alt' => '来笙 Laysense', 'logo' => '/assets/original/footer-wordmark.webp', 'alt' => '来笙 Laysense',
'name' => '上海来笙信息科技有限公司',
'address' => '中国(上海)自由贸易试验区世博村路231号2单元3层328室',
'email' => 'public@laysense.cn',
'products_title' => '产品与服务', 'products_title' => '产品与服务',
'products' => [['/pagepan', 'PAGEPAN 小飞页'], ['/highspeaker', 'HighSpeaker DNS'], ['/sc', '软著代理服务'], ['/shnu-sc', 'SHNU 学生软著服务']], 'products' => [['/highspeaker', 'HighSpeaker DNS'], ['/pagepan', 'PAGEPAN'], ['/sc', '软著代理服务']],
'company_title' => '公司', 'company_title' => '公司',
'company' => [['/#about', '关于来笙'], ['/articles', '来笙动态'], ['https://git.laysense.com', 'Laysense Git'], ['https://www.layso.de', 'LaySo']], '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']], '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 public static function parseLinks(string $value): array
{ {
$links = []; $links = [];
+14
View File
@@ -65,6 +65,20 @@ final class View
return $value ? date($format, strtotime($value)) : ''; 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 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'], ''); return new Response($status, ['Location' => $path, 'Cache-Control' => $status === 301 ? 'public, max-age=300' : 'no-store'], '');
+84 -14
View File
@@ -135,6 +135,7 @@ class AdminController
return $this->render($request, 'admin-articles', [ return $this->render($request, 'admin-articles', [
'title' => '文章与动态', 'articles' => array_slice($articles, 0, 30), 'pageNumber' => $page, 'title' => '文章与动态', 'articles' => array_slice($articles, 0, 30), 'pageNumber' => $page,
'hasNext' => count($articles) > 30, 'categories' => $categories, 'category' => $category, 'hasNext' => count($articles) > 30, 'categories' => $categories, 'category' => $category,
'deleted' => $request->get('deleted') === '1',
]); ]);
} }
@@ -221,6 +222,21 @@ class AdminController
], $error !== '' ? 422 : 200); ], $error !== '' ? 422 : 200);
} }
public function deleteArticle(Request $request, string $id): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
try {
(new Repository())->deleteArticle((int) $id, $this->version($request));
} catch (RuntimeException $exception) {
return $this->error($request, $this->validationMessage($exception), $exception instanceof \PDOException ? 500 : 409);
}
return $this->success($request, '/admin/articles?deleted=1');
}
public function page(Request $request, string $slug): Response public function page(Request $request, string $slug): Response
{ {
if ($failure = $this->guard($request)) { if ($failure = $this->guard($request)) {
@@ -255,6 +271,9 @@ class AdminController
} }
$page = array_replace($page, $data, ['version' => $this->version($request)]); $page = array_replace($page, $data, ['version' => $this->version($request)]);
try { try {
$data['alignments'] = $request->post('alignments') === null ? $page['alignments']
: $this->alignmentMap(json_decode($this->input($request, 'alignments'), true), ['heading', 'lead', 'actions', 'image']);
$page['alignments'] = $data['alignments'];
$data['quicklinks'] = $request->post('quicklinks') === null ? $page['quicklinks'] : SiteDesign::parseLinks($this->input($request, 'quicklinks')); $data['quicklinks'] = $request->post('quicklinks') === null ? $page['quicklinks'] : SiteDesign::parseLinks($this->input($request, 'quicklinks'));
if ($data['name'] === '' || mb_strlen($data['name']) > 100 || !in_array($data['status'], ['draft', 'published'], true) if ($data['name'] === '' || mb_strlen($data['name']) > 100 || !in_array($data['status'], ['draft', 'published'], true)
|| $data['title'] === '' || mb_strlen($data['title']) > 160 || || $data['title'] === '' || mb_strlen($data['title']) > 160 ||
@@ -265,7 +284,7 @@ class AdminController
strlen($data['image']) > 1000 || ($data['image'] !== '' && !Html::url($data['image'], true)) || !$validButtons) { strlen($data['image']) > 1000 || ($data['image'] !== '' && !Html::url($data['image'], true)) || !$validButtons) {
throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。'); throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。');
} }
$sections = $this->canvasSections($request->post('canvas_sections', ''), $page['sections']); $sections = $this->canvasSections($request->post('canvas_sections', ''), $page['sections'], $repo->categories());
$repo->savePage($slug, $data, $this->version($request), $sections); $repo->savePage($slug, $data, $this->version($request), $sections);
return $this->success($request, '/admin/pages/' . $slug . '?saved=1'); return $this->success($request, '/admin/pages/' . $slug . '?saved=1');
@@ -275,7 +294,7 @@ class AdminController
} }
return $this->render($request, 'admin-page', [ return $this->render($request, 'admin-page', [
'title' => '编辑 ' . $page['name'], 'page' => $page, 'wideAdmin' => true, 'error' => $error, 'saved' => $request->get('saved') === '1', 'title' => '编辑 ' . $page['name'], 'page' => $page, 'categories' => $repo->categories(), 'wideAdmin' => true, 'error' => $error, 'saved' => $request->get('saved') === '1',
], $error !== '' ? 422 : 200); ], $error !== '' ? 422 : 200);
} }
@@ -296,12 +315,12 @@ class AdminController
$data = [ $data = [
'title' => $this->input($request, 'title'), 'lead' => $this->input($request, 'lead'), 'title' => $this->input($request, 'title'), 'lead' => $this->input($request, 'lead'),
'body' => $this->input($request, 'body'), 'body' => $this->input($request, 'body'),
'style' => $request->post('style') === null ? $section['style'] : $this->input($request, 'style'), 'style' => $savedStyle === 'hero-links' || $request->post('style') === null ? $savedStyle : $this->input($request, 'style'),
'feed' => $section['feed'], 'feed' => $section['feed'],
]; ];
$section = array_replace($section, $data, ['version' => $this->version($request)]); $section = array_replace($section, $data, ['version' => $this->version($request)]);
try { try {
if ($request->post('feed_mode') !== null) { if ($savedStyle !== 'hero-links' && $request->post('feed_mode') !== null) {
$data['feed'] = $section['feed'] = $this->feedInput($request, $categories); $data['feed'] = $section['feed'] = $this->feedInput($request, $categories);
} }
$this->checkSection($data, $savedStyle); $this->checkSection($data, $savedStyle);
@@ -319,7 +338,7 @@ class AdminController
], $error !== '' ? 422 : 200); ], $error !== '' ? 422 : 200);
} }
private function canvasSections(mixed $payload, array $sections): array private function canvasSections(mixed $payload, array $sections, array $categories): array
{ {
if ($payload === '') { if ($payload === '') {
return []; return [];
@@ -333,14 +352,46 @@ class AdminController
foreach ($changes as $change) { foreach ($changes as $change) {
$key = $change['key'] ?? null; $key = $change['key'] ?? null;
$version = $change['version'] ?? null; $version = $change['version'] ?? null;
$fields = $change['fields'] ?? null; $fields = $change['fields'] ?? [];
$alignments = $change['alignments'] ?? null;
$feed = $change['feed'] ?? null;
$delete = ($change['delete'] ?? false) === true;
$isNew = is_array($change) && array_key_exists('version', $change) && $version === null; $isNew = is_array($change) && array_key_exists('version', $change) && $version === null;
if (!is_string($key) || isset($updates[$key]) || !is_array($fields) || $fields === [] if (!is_string($key) || isset($updates[$key]) || !is_array($fields) || (!$delete && $fields === [] && $alignments === null && $feed === null)
|| ($isNew ? (isset($available[$key]) || !preg_match('/^block-[a-f0-9]{32}$/D', $key)) || ($isNew ? (isset($available[$key]) || !preg_match('/^block-[a-f0-9]{32}$/D', $key))
: (!isset($available[$key]) || !is_int($version) || $version !== (int) $available[$key]['version']))) { : (!isset($available[$key]) || !is_int($version) || $version !== (int) $available[$key]['version']))) {
throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。'); throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。');
} }
if ($delete) {
if ($isNew || empty($available[$key]['feed'])) {
throw new RuntimeException('此区块不能通过模块工具删除。');
}
$updates[$key] = compact('key', 'version', 'delete');
continue;
}
$section = $available[$key] ?? ['key' => $key, 'title' => '', 'lead' => '', 'body' => '', 'style' => 'plain']; $section = $available[$key] ?? ['key' => $key, 'title' => '', 'lead' => '', 'body' => '', 'style' => 'plain'];
if ($isNew && isset($change['template'])) {
$preset = is_string($change['template']) ? BlockTemplates::find($change['template']) : null;
if ($preset === null) {
throw new RuntimeException('区块模板已失效。');
}
$section['feed'] = $preset[3] ?? null;
$section['style'] = $preset[4] ?? 'plain';
}
if ($isNew && isset($change['copyOf'])) {
$source = $change['copyOf']['key'] ?? null;
$sourceVersion = $change['copyOf']['version'] ?? null;
if (!is_string($source) || empty($available[$source]['feed']) || $sourceVersion !== (int) $available[$source]['version']) {
throw new RuntimeException('原模块已变更,请刷新画布后再复制。');
}
$section = array_replace($available[$source], ['key' => $key]);
}
if ($feed !== null) {
if (!is_array($feed) || empty($section['feed'])) {
throw new RuntimeException('模块设置不正确。');
}
$section['feed'] = $this->encodeFeed($feed['mode'] ?? null, $feed['categories'] ?? null, $feed['limit'] ?? null, $categories);
}
foreach ($fields as $field => $value) { foreach ($fields as $field => $value) {
if (!in_array($field, ['title', 'lead', 'body'], true)) { if (!in_array($field, ['title', 'lead', 'body'], true)) {
throw new RuntimeException('画布内容无效。'); throw new RuntimeException('画布内容无效。');
@@ -353,13 +404,13 @@ class AdminController
} }
$section[$field] = trim($value); $section[$field] = trim($value);
} }
if ($alignments !== null) {
$section['alignments'] = Database::json($this->alignmentMap($alignments, ['title', 'lead']));
}
$this->checkSection($section, $section['style']); $this->checkSection($section, $section['style']);
if (isset($fields['body'])) { if (isset($fields['body'])) {
$section['body'] = Html::sanitize($section['body']); $section['body'] = Html::sanitize($section['body']);
} }
if ($isNew && ($change['template'] ?? null) === 'articles') {
$section['feed'] = BlockTemplates::ARTICLE_FEED;
}
$section['version'] = $version; $section['version'] = $version;
$updates[$key] = $section; $updates[$key] = $section;
} }
@@ -367,6 +418,20 @@ class AdminController
return $updates; 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 private function checkSection(array $section, string $savedStyle): void
{ {
if ($section['title'] === '' || mb_strlen($section['title']) > 100 || mb_strlen($section['lead']) > 500 if ($section['title'] === '' || mb_strlen($section['title']) > 100 || mb_strlen($section['lead']) > 500
@@ -525,9 +590,14 @@ class AdminController
if ($mode === 'off') { if ($mode === 'off') {
return null; return null;
} }
$categories = $this->selectedCategories($request->post('feed_categories')); return $this->encodeFeed($mode, $request->post('feed_categories'), $this->input($request, 'feed_limit'), $available);
$limit = filter_var($this->input($request, 'feed_limit'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 30]]); }
if (!in_array($mode, ['merged', 'tabs'], true) || !$categories || array_diff($categories, array_keys($available)) || $limit === false) {
private function encodeFeed(mixed $mode, mixed $selected, mixed $value, array $available): string
{
$categories = $this->selectedCategories($selected);
$limit = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 30]]);
if (!in_array($mode, ['merged', 'tabs', 'network', 'catalog'], true) || !$categories || array_diff($categories, array_keys($available)) || $limit === false) {
throw new RuntimeException('请选择文章分类,并将展示数量设为 1 至 30。'); throw new RuntimeException('请选择文章分类,并将展示数量设为 1 至 30。');
} }
@@ -570,7 +640,7 @@ class AdminController
], $status); ], $status);
} }
return View::render($view, $data + ['token' => $token, 'user' => $this->user], $status, true); return View::render($view, $data + ['token' => $token, 'user' => $this->user, 'adminPath' => $request->path()], $status, true);
} }
protected function error(Request $request, string $message, int $status): Response protected function error(Request $request, string $message, int $status): Response
+87 -29
View File
@@ -24,6 +24,16 @@ final class SiteController
if (!$page || $page['status'] !== 'published' || $slug === 'home' && $request->path() !== '/') { if (!$page || $page['status'] !== 'published' || $slug === 'home' && $request->path() !== '/') {
return $this->missing($request); return $this->missing($request);
} }
if ($slug === 'articles' && $request->get('page') !== null) {
foreach ($page['sections'] as $section) {
$feed = json_decode($section['feed'] ?? '{}', true, flags: JSON_THROW_ON_ERROR);
if (in_array($feed['mode'] ?? null, ['merged', 'tabs'], true)) {
return $this->feedArchive($request, $slug, $section['key']);
}
}
return $this->missing($request);
}
return $this->renderPage($repo, $page); return $this->renderPage($repo, $page);
} }
@@ -37,12 +47,23 @@ final class SiteController
continue; continue;
} }
$feed = json_decode($section['feed'], true, flags: JSON_THROW_ON_ERROR); $feed = json_decode($section['feed'], true, flags: JSON_THROW_ON_ERROR);
$tabs = $feed['mode'] === 'tabs' && count($feed['categories']) > 1; $network = $feed['mode'] === 'network';
$catalog = $feed['mode'] === 'catalog';
$grouped = $network || ($feed['mode'] === 'tabs' && count($feed['categories']) > 1);
$archivePath = '/articles/feed/' . $slug . '/' . $section['key'];
if ($network && count($feed['categories']) === 2 && !array_diff($feed['categories'], ['supported-projects', 'partners'])) {
$archivePath = '/network';
}
$section['archivePath'] = $page['status'] === 'published' ? $archivePath : null;
$section['articleFeed'] = []; $section['articleFeed'] = [];
foreach ($tabs ? $feed['categories'] : [''] as $category) { $section['networkFeed'] = $network;
$section['catalogFeed'] = $catalog;
$section['feedLimit'] = $feed['limit'];
foreach ($grouped ? $feed['categories'] : [''] as $category) {
$selected = $category === '' ? $feed['categories'] : [$category];
$section['articleFeed'][] = [ $section['articleFeed'][] = [
'label' => $categories[$category] ?? '', 'categories' => $selected, 'label' => $categories[$category] ?? '',
'articles' => $repo->articles($category === '' ? $feed['categories'] : $category, limit: $feed['limit']), 'articles' => $repo->articles($selected, limit: $feed['limit'], directoryOrder: $network || $catalog),
]; ];
} }
} }
@@ -56,23 +77,10 @@ final class SiteController
'description' => $page['description'], 'description' => $page['description'],
'socialImage' => $page['image'], 'socialImage' => $page['image'],
'socialAlt' => $page['alt'], 'socialAlt' => $page['alt'],
'network' => $isHome ? $this->networkGroups($repo) : [],
'previewMode' => $preview, 'canvas' => $preview && $canvas, 'noindex' => $preview, 'previewMode' => $preview, 'canvas' => $preview && $canvas, 'noindex' => $preview,
]); ]);
} }
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 public function network(Request $request): Response
{ {
$repo = new Repository(); $repo = new Repository();
@@ -102,22 +110,76 @@ final class SiteController
} }
$title = $category ? $categories[$category] : ($tag ?: '来笙动态'); $title = $category ? $categories[$category] : ($tag ?: '来笙动态');
$path = '/articles' . ($category ? '/category/' . $category : ($tag ? '/tag/' . rawurlencode($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],
'catalog' => $feed['mode'] === 'catalog',
'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'); $number = $request->get('page', '1');
if (!is_scalar($number) || !preg_match('/^[1-9][0-9]{0,4}$/D', (string) $number)) { if (!is_scalar($number) || !preg_match('/^[1-9][0-9]{0,4}$/D', (string) $number)) {
return $this->missing($request); return $this->missing($request);
} }
$page = (int) $number; $page = (int) $number;
$articles = $repo->articles($category, $tag, limit: 21, offset: ($page - 1) * 20); $articles = $repo->articles($category, $tag, limit: 21, offset: ($page - 1) * 20, directoryOrder: $view['catalog'] ?? false);
if ($page > 1 && $articles === []) { if ($page > 1 && $articles === []) {
return $this->missing($request); return $this->missing($request);
} }
$path = $view['archivePath'];
return View::render('archive', [ return View::render('archive', $view + [
'site' => $repo->site(), 'title' => $title . ' · 来笙', 'headline' => $title, 'site' => $repo->site(), 'title' => $view['headline'] . ' · 来笙',
'description' => '查看来笙的公告、新闻和产品动态。', 'path' => $page > 1 ? View::archivePage($path, $page) : $path,
'path' => $path . ($page > 1 ? '?page=' . $page : ''), 'archivePath' => $path, 'pageNumber' => $page, 'hasNext' => count($articles) > 20, 'articles' => array_slice($articles, 0, 20),
'categories' => $categories, 'category' => $category, 'tag' => $tag, 'pageNumber' => $page,
'hasNext' => count($articles) > 20, 'articles' => array_slice($articles, 0, 20),
'noindex' => $articles === [], 'noindex' => $articles === [],
]); ]);
} }
@@ -180,11 +242,7 @@ final class SiteController
$repo = new Repository(); $repo = new Repository();
$xml = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">']; $xml = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'];
$pages = $repo->pages(publishedOnly: true); $pages = $repo->pages(publishedOnly: true);
$pages[] = ['slug' => 'services', 'updated_at' => null];
$pages[] = ['slug' => 'network', 'updated_at' => null]; $pages[] = ['slug' => 'network', 'updated_at' => null];
if ($repo->articles(limit: 1)) {
$pages[] = ['slug' => 'articles', 'updated_at' => null];
}
foreach ($pages as $page) { foreach ($pages as $page) {
$xml[] = $this->sitemapUrl($page['slug'] === 'home' ? '/' : '/' . $page['slug'], $page['updated_at']); $xml[] = $this->sitemapUrl($page['slug'] === 'home' ? '/' : '/' . $page['slug'], $page['updated_at']);
} }
@@ -209,7 +267,7 @@ final class SiteController
$normal = rtrim($path, '/'); $normal = rtrim($path, '/');
$single = preg_match('~^/[a-z0-9-]+$~D', $normal); $single = preg_match('~^/[a-z0-9-]+$~D', $normal);
$known = $single && ((new Repository())->page(substr($normal, 1))['status'] ?? null) === 'published' && $normal !== '/home'; $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)) { if ($known || $normal === '/network' || preg_match('~^/articles(?:/[a-z0-9-]+){1,2}$~D', $normal)) {
$query = $request->queryString(); $query = $request->queryString();
return View::redirect($normal . ($query !== '' ? '?' . $query : ''), 301); return View::redirect($normal . ($query !== '' ? '?' . $query : ''), 301);
+12 -6
View File
@@ -27,7 +27,7 @@ final class StudioController extends AdminController
$data['name'] = $this->input($request, 'name'); $data['name'] = $this->input($request, 'name');
$data['slug'] = $this->input($request, 'slug'); $data['slug'] = $this->input($request, 'slug');
try { try {
if (!$this->slug($data['slug']) || in_array($data['slug'], ['admin', 'assets', 'articles', 'home', 'services', 'network', 'news', 'main', 'favicon'], true) if (!$this->slug($data['slug']) || in_array($data['slug'], ['admin', 'assets', 'home', 'network', 'news', 'main', 'favicon'], true)
|| $data['name'] === '' || mb_strlen($data['name']) > 100) { || $data['name'] === '' || mb_strlen($data['name']) > 100) {
throw new RuntimeException('请填写页面名称及可用的网址标识。'); throw new RuntimeException('请填写页面名称及可用的网址标识。');
} }
@@ -74,7 +74,7 @@ final class StudioController extends AdminController
if ($preset === null) { if ($preset === null) {
throw new RuntimeException('请选择区块类型。'); throw new RuntimeException('请选择区块类型。');
} }
$repo->createSection($slug, $key, $preset[0], 'plain', $preset[1], $type === 'articles' ? BlockTemplates::ARTICLE_FEED : null); $repo->createSection($slug, $key, $preset[0], $preset[4] ?? 'plain', Html::sanitize($preset[1], $key), $preset[3] ?? null, $preset[2] ?? '');
return $this->success($request, "/admin/pages/$slug/$key"); return $this->success($request, "/admin/pages/$slug/$key");
} }
@@ -98,15 +98,16 @@ final class StudioController extends AdminController
$site = (new Repository())->site(); $site = (new Repository())->site();
$defaults = match ($part) { $defaults = match ($part) {
'header' => SiteDesign::DEFAULT_HEADER, 'header' => SiteDesign::DEFAULT_HEADER,
'footer' => SiteDesign::DEFAULT_FOOTER + array_intersect_key($site, array_flip(['name', 'address', 'email', 'copyright', 'registration', 'terms'])), 'footer' => SiteDesign::DEFAULT_FOOTER,
'cdn' => ['origin' => ''], 'cdn' => ['origin' => ''],
}; };
$config = ($site[$part] ?? []) + $defaults; $config = $part === 'footer' ? SiteDesign::footer($site) : ($site[$part] ?? []) + $defaults;
$version = $site['revisions'][$part] ?? 0; $version = $site['revisions'][$part] ?? 0;
$error = ''; $error = '';
if ($request->method() === 'POST') { if ($request->method() === 'POST') {
try { try {
$config = $this->settingsInput($request, $part, $defaults); $config = $part === 'footer' && $request->post('operation') === 'restore-footer'
? $defaults : $this->settingsInput($request, $part, $defaults, $config);
SiteDesign::saveSettings($part, $config, $this->version($request)); SiteDesign::saveSettings($part, $config, $this->version($request));
return $this->success($request, '/admin/settings/' . $part . '?saved=1'); return $this->success($request, '/admin/settings/' . $part . '?saved=1');
@@ -177,13 +178,18 @@ final class StudioController extends AdminController
return $this->success($request, '/admin/media'); return $this->success($request, '/admin/media');
} }
private function settingsInput(Request $request, string $part, array $defaults): array private function settingsInput(Request $request, string $part, array $defaults, array $current): array
{ {
if ($part === 'cdn') { if ($part === 'cdn') {
return ['origin' => Assets::cdn($this->input($request, 'origin'))]; return ['origin' => Assets::cdn($this->input($request, 'origin'))];
} }
$result = []; $result = [];
$hasResources = $request->post('resources') !== null;
foreach ($defaults as $key => $default) { 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); $input = $this->input($request, $key);
if (is_array($default)) { if (is_array($default)) {
$result[$key] = SiteDesign::parseLinks($input); $result[$key] = SiteDesign::parseLinks($input);
+11
View File
@@ -51,3 +51,14 @@ $e = View::escape(...);
<button class="button button-primary" type="submit">保存文章</button> <button class="button button-primary" type="submit">保存文章</button>
</div> </div>
</form> </form>
<?php if ($articleId !== null): ?>
<details class="admin-panel admin-options">
<summary>删除文章</summary>
<form method="post" action="/admin/articles/<?= $e($articleId) ?>/delete">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($article['version']) ?>">
<p class="field-note">删除后,文章及其目录卡片会从网站移除,且无法恢复。</p>
<button class="button button-danger" type="submit">永久删除</button>
</form>
</details>
<?php endif ?>
+2 -1
View File
@@ -12,10 +12,11 @@ $filters = $category ? 'category=' . rawurlencode($category) . '&' : '';
<a class="button button-primary" href="/admin/articles/new<?= $category ? '?category=' . $e($category) : '' ?>">新建文章</a> <a class="button button-primary" href="/admin/articles/new<?= $category ? '?category=' . $e($category) : '' ?>">新建文章</a>
</div> </div>
</header> </header>
<?php if ($deleted): ?><p class="feedback success" role="status">文章已删除。</p><?php endif ?>
<nav class="filter-nav" aria-label="筛选文章"> <nav class="filter-nav" aria-label="筛选文章">
<a href="/admin/articles" <?= $category === null ? 'aria-current="page"' : '' ?>>全部</a> <a href="/admin/articles" <?= $category === null ? 'aria-current="page"' : '' ?>>全部</a>
<?php foreach ($categories as $key => $name): ?> <?php foreach ($categories as $key => $name): ?>
<a href="/admin/articles?category=<?= $e($key) ?>" <?= $category === $key ? 'aria-current="page"' : '' ?>><?= $e($name) ?></a> <a href="/admin/articles?category=<?= $e($key) ?>" <?= $category === (string) $key ? 'aria-current="page"' : '' ?>><?= $e($name) ?></a>
<?php endforeach ?> <?php endforeach ?>
</nav> </nav>
<div class="admin-panel"> <div class="admin-panel">
+2 -1
View File
@@ -2,12 +2,13 @@
use App\Content\View; use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
$checked = array_fill_keys($selected, true);
?> ?>
<fieldset class="category-checks"> <fieldset class="category-checks">
<legend><?= $e($legend) ?></legend> <legend><?= $e($legend) ?></legend>
<div> <div>
<?php foreach ($categories as $key => $label): ?> <?php foreach ($categories as $key => $label): ?>
<label><input type="checkbox" name="<?= $e($name) ?>[]" value="<?= $e($key) ?>" <?= in_array($key, $selected, true) ? 'checked' : '' ?>> <?= $e($label) ?></label> <label><input type="checkbox" name="<?= $e($name) ?>[]" value="<?= $e($key) ?>" <?= isset($checked[$key]) ? 'checked' : '' ?>> <?= $e($label) ?></label>
<?php endforeach ?> <?php endforeach ?>
</div> </div>
</fieldset> </fieldset>
+46 -12
View File
@@ -2,24 +2,58 @@
use App\Content\View; use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
$live = count(array_filter($pages, static fn (array $page): bool => $page['status'] === 'published'));
?> ?>
<header class="admin-heading"> <header class="admin-heading dashboard-heading">
<div><h1>内容管理</h1><p>管理网站页面、文章、公告和产品动态。</p></div> <h1>网站后台</h1>
<div class="actions"><a class="button button-primary" href="/admin/new-page">新建页面</a> <div class="actions">
<a class="button button-outline" href="/admin/articles/new">新建文章</a></div> <a class="button button-primary" href="/admin/new-page">新建页面</a>
<a class="button button-outline" href="/admin/articles/new">写文章</a>
</div>
</header> </header>
<section class="admin-panel" aria-labelledby="pages-title"> <div class="dashboard-grid">
<section class="admin-panel dashboard-pages" aria-labelledby="pages-title" data-page-list>
<div class="admin-heading compact">
<h2 id="pages-title">网站页面</h2> <h2 id="pages-title">网站页面</h2>
<ul class="admin-list"> <p class="field-note"><?= $live ?> 个已发布 · <?= count($pages) - $live ?> 个草稿</p>
</div>
<div class="dashboard-filters" data-page-filters hidden>
<label>查找页面<input type="search" data-page-search placeholder="页面名称或地址"></label>
<label>发布状态<select data-page-status>
<option value="">全部状态</option>
<option value="published">已发布</option>
<option value="draft">草稿</option>
</select></label>
</div>
<p class="empty-state" data-page-empty role="status"<?= $pages ? ' hidden' : '' ?>><?= $pages ? '没有匹配的页面。' : '暂无页面。' ?></p>
<ul class="admin-list dashboard-page-list">
<?php foreach ($pages as $page): ?> <?php foreach ($pages as $page): ?>
<li> <?php $path = $page['slug'] === 'home' ? '/' : '/' . $page['slug']; $published = $page['status'] === 'published'; ?>
<div><strong><?= $e($page['name']) ?></strong><small><?= $e($page['slug'] === 'home' ? '/' : '/' . $page['slug']) ?> · <?= $page['status'] === 'draft' ? '草稿' : '已发布' ?></small></div> <li data-page-item="<?= $e($page['status']) ?>" data-page-label="<?= $e($page['name'] . ' ' . $page['title'] . ' ' . $path) ?>">
<div class="dashboard-page-label"><strong><?= $e($page['name']) ?></strong><small><?= $e($path) ?></small></div>
<span class="dashboard-page-state" data-published="<?= $published ? 'true' : 'false' ?>"><?= $published ? '已发布' : '草稿' ?></span>
<div class="dashboard-page-actions">
<a class="button button-outline" href="/admin/pages/<?= $e($page['slug']) ?>">编辑页面</a> <a class="button button-outline" href="/admin/pages/<?= $e($page['slug']) ?>">编辑页面</a>
<a href="<?= $e($published ? $path : '/admin/pages/' . $page['slug'] . '/preview') ?>" target="_blank" rel="noopener"><?= $published ? '查看' : '预览' ?></a>
</div>
</li> </li>
<?php endforeach ?> <?php endforeach ?>
</ul> </ul>
</section> </section>
<section class="admin-panel" aria-labelledby="recent-title"> <div class="dashboard-secondary">
<div class="admin-heading compact"><h2 id="recent-title">最近编辑的文章</h2><a href="/admin/articles">管理全部文章</a></div> <section class="admin-panel" aria-labelledby="recent-title">
<div class="admin-heading compact"><h2 id="recent-title">最近编辑的文章</h2></div>
<?= View::fragment('admin-article-list', ['articles' => $articles]) ?> <?= View::fragment('admin-article-list', ['articles' => $articles]) ?>
</section> <a class="back-link" href="/admin/articles">管理全部文章</a>
</section>
<section class="admin-panel dashboard-settings" aria-labelledby="quick-title">
<h2 id="quick-title">站点编辑</h2>
<ul class="dashboard-setting-buttons">
<li><a class="button button-outline" href="/admin/settings/header">编辑页头</a></li>
<li><a class="button button-outline" href="/admin/settings/footer">编辑页脚</a></li>
<li><a class="button button-outline" href="/admin/settings/cdn">静态资源 CDN</a></li>
<li><a class="button button-outline" href="/admin/media">打开媒体库</a></li>
</ul>
</section>
</div>
</div>
+22 -8
View File
@@ -2,6 +2,13 @@
use App\Content\View; use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
$active = match (true) {
str_starts_with($adminPath, '/admin/article') => 'articles',
str_starts_with($adminPath, '/admin/media') => 'media',
str_starts_with($adminPath, '/admin/settings') => 'settings',
$adminPath === '/admin/password' => '',
default => 'pages',
};
?> ?>
<!doctype html> <!doctype html>
<html lang="zh-CN"> <html lang="zh-CN">
@@ -29,18 +36,25 @@ $e = View::escape(...);
<div class="admin-wrap admin-bar-inner"> <div class="admin-wrap admin-bar-inner">
<a class="wordmark" href="/admin" aria-label="来笙内容管理首页"><img src="/assets/wordmark.webp" alt="来笙 Laysense" width="130" height="33"></a> <a class="wordmark" href="/admin" aria-label="来笙内容管理首页"><img src="/assets/wordmark.webp" alt="来笙 Laysense" width="130" height="33"></a>
<?php if ($user): ?> <?php if ($user): ?>
<nav aria-label="后台导航"> <nav class="admin-primary" aria-label="后台导航">
<a href="/admin">页面</a> <a href="/admin"<?= $active === 'pages' ? ' aria-current="page"' : '' ?>>页面</a>
<a href="/admin/articles">文章</a> <a href="/admin/articles"<?= $active === 'articles' ? ' aria-current="page"' : '' ?>>文章</a>
<a href="/admin/media">媒体库</a> <a href="/admin/media"<?= $active === 'media' ? ' aria-current="page"' : '' ?>>媒体库</a>
<a href="/admin/settings/header">网站设置</a> <a href="/admin/settings/header"<?= $active === 'settings' ? ' aria-current="page"' : '' ?>>网站设置</a>
<a href="/admin/password">修改密码</a> </nav>
<div class="admin-utility">
<a href="/">访问网站</a> <a href="/">访问网站</a>
<details class="admin-account">
<summary>账户</summary>
<div class="admin-account-menu">
<a href="/admin/password">修改密码</a>
<form method="post" action="/admin/logout"> <form method="post" action="/admin/logout">
<input type="hidden" name="csrf" value="<?= $e($token) ?>"> <input type="hidden" name="csrf" value="<?= $e($token) ?>">
<button class="button button-outline" type="submit">退出</button> <button type="submit">退出登录</button>
</form> </form>
</nav> </div>
</details>
</div>
<?php else: ?> <?php else: ?>
<a class="back-link" href="/">返回网站</a> <a class="back-link" href="/">返回网站</a>
<?php endif ?> <?php endif ?>
+44 -56
View File
@@ -1,7 +1,7 @@
<?php <?php
use App\Content\Database;
use App\Content\SiteDesign; use App\Content\SiteDesign;
use App\Content\View; use App\Content\View;
use App\Content\BlockTemplates;
$e = View::escape(...); $e = View::escape(...);
$slug = $page['slug']; $slug = $page['slug'];
@@ -10,8 +10,10 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
?> ?>
<a class="back-link" href="/admin">返回页面</a> <a class="back-link" href="/admin">返回页面</a>
<header class="admin-heading"> <header class="admin-heading">
<div><h1><?= $e($title) ?></h1><p><?= $e($path) ?> · <?= $page['status'] === 'draft' ? '草稿' : '已发布' ?></p></div> <div><h1><?= $e($title) ?></h1><p class="studio-page-meta"><code><?= $e($path) ?></code>
<span class="dashboard-page-state" data-published="<?= $page['status'] === 'published' ? 'true' : 'false' ?>"><?= $page['status'] === 'draft' ? '草稿' : '已发布' ?></span></p></div>
<div class="actions"> <div class="actions">
<a class="button button-outline" href="#studio-page-settings">页面设置</a>
<?php if ($page['status'] === 'published'): ?><a class="button button-outline" href="<?= $e($path) ?>">公开页面</a><?php endif ?> <?php if ($page['status'] === 'published'): ?><a class="button button-outline" href="<?= $e($path) ?>">公开页面</a><?php endif ?>
<a class="button button-outline" href="<?= $e($previewUrl) ?>" target="_blank" rel="noopener">打开预览</a> <a class="button button-outline" href="<?= $e($previewUrl) ?>" target="_blank" rel="noopener">打开预览</a>
</div> </div>
@@ -19,56 +21,11 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?> <?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<div class="studio-layout"> <div class="studio-layout">
<aside class="admin-panel studio-library" aria-labelledby="studio-library-title"> <aside class="admin-panel studio-library" aria-labelledby="studio-library-title">
<h2 id="studio-library-title">区块模板</h2> <h2 id="studio-library-title">页面编辑</h2>
<?= View::fragment('studio-templates') ?> <?= View::fragment('studio-templates', [
<details class="studio-layers"> 'layers' => View::fragment('studio-layers', compact('page', 'slug', 'token')),
<summary>首屏与目录</summary> 'anchorForm' => View::fragment('studio-anchor-form', compact('slug', 'token')),
<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> </aside>
<div class="studio-workspace"> <div class="studio-workspace">
<section class="admin-panel studio-preview" data-preview-studio aria-labelledby="studio-preview-title"> <section class="admin-panel studio-preview" data-preview-studio aria-labelledby="studio-preview-title">
@@ -92,9 +49,14 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
<div class="studio-frame-window"> <div class="studio-frame-window">
<iframe title="可编辑页面画布" src="<?= $e($previewUrl) ?>?canvas=1" sandbox="allow-same-origin"></iframe> <iframe title="可编辑页面画布" src="<?= $e($previewUrl) ?>?canvas=1" sandbox="allow-same-origin"></iframe>
<div class="studio-element-tools" data-element-tools role="group" aria-label="所选元素" hidden> <div class="studio-element-tools" data-element-tools role="group" aria-label="所选元素" hidden>
<button type="button" data-element-properties>属性</button> <div class="studio-element-align" data-element-align role="group" aria-label="对齐">
<button type="button" data-element-copy>复制</button> <?php foreach (['left' => '居左', 'center' => '居中', 'right' => '居右'] as $value => $label): ?>
<button type="button" data-element-delete>删除</button> <button type="button" data-align="<?= $value ?>" aria-pressed="false" aria-label="<?= $label ?>" title="<?= $label ?>"><?= View::fragment('studio-icon', ['icon' => $value]) ?></button>
<?php endforeach ?>
</div>
<?php foreach (['module-settings' => ['settings', '模块设置'], 'properties' => ['edit', '属性'], 'copy' => ['copy', '复制'], 'delete' => ['delete', '删除']] as $action => [$icon, $label]): ?>
<button type="button" data-element-<?= $action ?> aria-label="<?= $label ?>" title="<?= $label ?>"><?= View::fragment('studio-icon', compact('icon')) ?></button>
<?php endforeach ?>
</div> </div>
<button class="studio-media-handle" type="button" role="slider" aria-label="媒体宽度" aria-valuemin="10" aria-valuemax="100" aria-valuenow="100" data-media-handle hidden></button> <button class="studio-media-handle" type="button" role="slider" aria-label="媒体宽度" aria-valuemin="10" aria-valuemax="100" aria-valuenow="100" data-media-handle hidden></button>
<div class="studio-media-sizing" data-media-sizing hidden> <div class="studio-media-sizing" data-media-sizing hidden>
@@ -103,14 +65,17 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
<button class="button button-outline" type="button" data-replace-media>替换媒体</button> <button class="button button-outline" type="button" data-replace-media>替换媒体</button>
</div> </div>
</div> </div>
<p class="field-note">单击画布中的元素可打开浮动工具条。选中媒体后可拖动边缘手柄调整宽度。</p> <p class="field-note studio-canvas-status" data-canvas-status role="status"></p>
<dialog class="media-picker canvas-properties" data-canvas-properties aria-labelledby="canvas-properties-heading"> <dialog class="media-picker canvas-properties" data-canvas-properties aria-labelledby="canvas-properties-heading">
<div class="admin-heading compact"><h2 id="canvas-properties-heading" data-property-heading>编辑属性</h2></div> <div class="admin-heading compact"><h2 id="canvas-properties-heading" data-property-heading>编辑属性</h2></div>
<form class="admin-form" method="dialog"> <form class="admin-form" method="dialog">
<label data-property-row="label">文案<input name="label"></label> <label data-property-row="label">文案<input name="label"></label>
<label data-property-row="note">副标题<input name="note" maxlength="200"></label>
<label data-property-row="url">地址<input name="url" maxlength="1000"></label> <label data-property-row="url">地址<input name="url" maxlength="1000"></label>
<label data-property-row="alt">图片替代文本<input name="alt" maxlength="200"></label> <label data-property-row="alt">图片替代文本<input name="alt" maxlength="200"></label>
<label data-property-row="quicklinks">目录链接<textarea name="quicklinks" rows="5" placeholder="概览 | #overview"></textarea><small>每行填写「文案 | 链接」。</small></label> <label data-property-row="quicklinks">目录链接<textarea name="quicklinks" rows="5" placeholder="概览 | #overview"></textarea><small>每行填写「文案 | 链接」。</small></label>
<label data-property-row="value">当前值<input name="value" inputmode="numeric"></label>
<label data-property-row="max">最大值<input name="max" inputmode="numeric"></label>
<label data-property-row="poster">视频封面<input name="poster" maxlength="1000"></label> <label data-property-row="poster">视频封面<input name="poster" maxlength="1000"></label>
<p class="feedback error" role="alert" data-property-error hidden></p> <p class="feedback error" role="alert" data-property-error hidden></p>
<div class="actions"> <div class="actions">
@@ -123,6 +88,19 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
</div> </div>
</form> </form>
</dialog> </dialog>
<dialog class="media-picker canvas-module-settings" data-module-dialog aria-labelledby="module-settings-title">
<div class="admin-heading compact"><h2 id="module-settings-title">模块设置</h2></div>
<form class="admin-form" method="dialog">
<label>模块标题<input name="module_title" maxlength="100" required></label>
<label>模块简介<textarea name="module_lead" rows="2" maxlength="500"></textarea></label>
<?= View::fragment('studio-feed-fields', ['categories' => $categories, 'feed' => [], 'allowOff' => false]) ?>
<p class="feedback error" role="alert" data-module-error hidden></p>
<div class="actions">
<button class="button button-primary" type="submit">应用</button>
<button class="button button-outline" data-module-close type="button">取消</button>
</div>
</form>
</dialog>
</section> </section>
</div> </div>
<form id="studio-page-settings" class="admin-form admin-panel studio-inspector" method="post" action="/admin/pages/<?= $e($slug) ?>"> <form id="studio-page-settings" class="admin-form admin-panel studio-inspector" method="post" action="/admin/pages/<?= $e($slug) ?>">
@@ -130,6 +108,16 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
<input type="hidden" name="csrf" value="<?= $e($token) ?>"> <input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($page['version']) ?>"> <input type="hidden" name="version" value="<?= $e($page['version']) ?>">
<input type="hidden" name="canvas_sections" value=""> <input type="hidden" name="canvas_sections" value="">
<input type="hidden" name="alignments" value="<?= $e(Database::json($page['alignments'])) ?>">
<details class="studio-hero-settings">
<summary>首屏与目录</summary>
<div class="studio-hero-controls">
<button class="button button-outline" type="button" disabled data-hero-control="image">首屏图片</button>
<button class="button button-outline" type="button" disabled data-hero-control="1">首屏按钮 1</button>
<button class="button button-outline" type="button" disabled data-hero-control="2">首屏按钮 2</button>
<button class="button button-outline" type="button" disabled data-hero-control="navigation">本页目录</button>
</div>
</details>
<label>页面名称<input name="name" value="<?= $e($page['name']) ?>" required maxlength="100"></label> <label>页面名称<input name="name" value="<?= $e($page['name']) ?>" required maxlength="100"></label>
<label>SEO 标题<input name="title" value="<?= $e($page['title']) ?>" required maxlength="160"></label> <label>SEO 标题<input name="title" value="<?= $e($page['title']) ?>" required maxlength="160"></label>
<label>SEO 描述<textarea name="description" rows="2" maxlength="300"><?= $e($page['description']) ?></textarea></label> <label>SEO 描述<textarea name="description" rows="2" maxlength="300"><?= $e($page['description']) ?></textarea></label>
+4 -10
View File
@@ -17,23 +17,17 @@ $feed = json_decode($section['feed'] ?? '{}', true, flags: JSON_THROW_ON_ERROR);
<input type="hidden" name="version" value="<?= $e($section['version']) ?>"> <input type="hidden" name="version" value="<?= $e($section['version']) ?>">
<label>区块标题<input name="title" value="<?= $e($section['title']) ?>" required maxlength="100"></label> <label>区块标题<input name="title" value="<?= $e($section['title']) ?>" required maxlength="100"></label>
<label>区块简介<textarea name="lead" rows="2" maxlength="500"><?= $e($section['lead']) ?></textarea></label> <label>区块简介<textarea name="lead" rows="2" maxlength="500"><?= $e($section['lead']) ?></textarea></label>
<?php if ($savedStyle !== 'hero-links'): ?>
<label>区块背景<select name="style"> <label>区块背景<select name="style">
<?php foreach (array_unique([$savedStyle, 'plain', 'tinted']) as $style): ?> <?php foreach (array_unique([$savedStyle, 'plain', 'tinted']) as $style): ?>
<option value="<?= $e($style) ?>" <?= $style === $section['style'] ? 'selected' : '' ?>><?= $e(['plain' => '默认', 'tinted' => '浅色背景'][$style] ?? '保留原布局') ?></option> <option value="<?= $e($style) ?>" <?= $style === $section['style'] ? 'selected' : '' ?>><?= $e(['plain' => '默认', 'tinted' => '浅色背景'][$style] ?? '保留原布局') ?></option>
<?php endforeach ?> <?php endforeach ?>
</select></label> </select></label>
<details class="admin-options" <?= $feed ? 'open' : '' ?>> <details class="admin-options" <?= $feed ? 'open' : '' ?>>
<summary>文章组件</summary> <summary>动态模块</summary>
<div class="form-grid"> <?= View::fragment('studio-feed-fields', ['categories' => $categories, 'feed' => $feed, 'allowOff' => true]) ?>
<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> </details>
<?php endif ?>
<?= View::fragment('admin-editor', ['format' => 'html', 'body' => $section['body']]) ?> <?= View::fragment('admin-editor', ['format' => 'html', 'body' => $section['body']]) ?>
<div class="form-submit"><button class="button button-primary" type="submit">保存区块</button></div> <div class="form-submit"><button class="button button-primary" type="submit">保存区块</button></div>
</form> </form>
+11 -7
View File
@@ -6,22 +6,26 @@ $e = View::escape(...);
<section class="section article-page" aria-labelledby="archive-title" data-enter> <section class="section article-page" aria-labelledby="archive-title" data-enter>
<div class="wrap"> <div class="wrap">
<div class="section-heading"> <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> <h1 id="archive-title"><?= $e($headline) ?></h1>
<p>来笙的公告、新闻和产品动态。</p> <p><?= $e($description) ?></p>
</div> </div>
<nav class="filter-nav" aria-label="动态分类"> <nav class="filter-nav" aria-label="动态分类">
<a href="/articles" <?= !$category && !$tag ? 'aria-current="page"' : '' ?>>全部</a> <a href="<?= $e($allPath) ?>" <?= !$category && !$tag ? 'aria-current="page"' : '' ?>>全部</a>
<?php foreach ($categories as $key => $label): ?> <?php foreach ($categories as $key => $label): ?>
<a href="/articles/category/<?= $e($key) ?>" <?= $category === $key ? 'aria-current="page"' : '' ?>><?= $e($label) ?></a> <a href="<?= $e($categoryLinks[$key]) ?>" <?= $category === (string) $key ? 'aria-current="page"' : '' ?>><?= $e($label) ?></a>
<?php endforeach ?> <?php endforeach ?>
</nav> </nav>
<?= View::fragment('article-list', ['articles' => $articles]) ?> <?php if (!empty($catalog)): ?>
<?= View::fragment('service-cards', ['products' => $articles]) ?>
<?php else: ?>
<?= View::fragment('article-list', ['articles' => $articles, 'categoryScope' => $categoryScope ?? null]) ?>
<?php endif ?>
<?php if ($pageNumber > 1 || $hasNext): ?> <?php if ($pageNumber > 1 || $hasNext): ?>
<nav class="pagination" aria-label="动态分页"> <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> <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> </nav>
<?php endif ?> <?php endif ?>
</div> </div>
+4 -1
View File
@@ -14,7 +14,10 @@ $e = View::escape(...);
<?php foreach ($groups as $index => $group): ?> <?php foreach ($groups as $index => $group): ?>
<div id="<?= $e($sectionKey) ?>-articles-<?= $index ?>" data-tab-panel> <div id="<?= $e($sectionKey) ?>-articles-<?= $index ?>" data-tab-panel>
<?php if ($group['label'] !== ''): ?><h3 data-tab-heading><?= $e($group['label']) ?></h3><?php endif ?> <?php if ($group['label'] !== ''): ?><h3 data-tab-heading><?= $e($group['label']) ?></h3><?php endif ?>
<?= View::fragment('article-list', ['articles' => $group['articles']]) ?> <?= View::fragment('article-list', ['articles' => $group['articles'], 'categoryScope' => $group['categories']]) ?>
</div> </div>
<?php endforeach ?> <?php endforeach ?>
<?php if ($archivePath !== null): ?>
<p class="article-feed-archive"><a class="back-link" href="<?= $e($archivePath) ?>">查看全部动态</a></p>
<?php endif ?>
</div> </div>
+3 -1
View File
@@ -2,13 +2,15 @@
use App\Content\View; use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
$scope = isset($categoryScope) ? array_flip($categoryScope) : null;
?> ?>
<?php if ($articles): ?> <?php if ($articles): ?>
<ul class="article-list"> <ul class="article-list">
<?php foreach ($articles as $item): ?> <?php foreach ($articles as $item): ?>
<?php $labels = $scope === null ? $item['categories'] : array_intersect_key($item['categories'], $scope); ?>
<li> <li>
<a class="article-row" href="/articles/<?= $e($item['slug']) ?>"> <a class="article-row" href="/articles/<?= $e($item['slug']) ?>">
<span class="article-category"><?= $e(implode('、', $item['categories'])) ?></span> <span class="article-category"><?= $e(implode('、', $labels)) ?></span>
<span class="article-row-title"><?= $e($item['title']) ?> <span class="article-row-title"><?= $e($item['title']) ?>
<?php if ($item['summary']): ?><small><?= $e($item['summary']) ?></small><?php endif ?> <?php if ($item['summary']): ?><small><?= $e($item['summary']) ?></small><?php endif ?>
</span> </span>
+18 -8
View File
@@ -8,7 +8,7 @@ $e = View::escape(...);
<div class="footer-grid"> <div class="footer-grid">
<div class="footer-company" itemscope itemtype="https://schema.org/Organization"> <div class="footer-company" itemscope itemtype="https://schema.org/Organization">
<?php if ($footer['logo'] !== ''): ?> <?php if ($footer['logo'] !== ''): ?>
<a href="/" itemprop="url" aria-label="来笙 Laysense 首页"> <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"> <img src="<?= $e($footer['logo']) ?>" alt="<?= $e($footer['alt']) ?>" width="130" height="33" itemprop="logo" loading="lazy">
</a> </a>
<?php endif ?> <?php endif ?>
@@ -17,31 +17,41 @@ $e = View::escape(...);
<?php if ($footer['email']): ?> <?php if ($footer['email']): ?>
<a itemprop="email" href="mailto:<?= $e($footer['email']) ?>"><?= $e($footer['email']) ?></a> <a itemprop="email" href="mailto:<?= $e($footer['email']) ?>"><?= $e($footer['email']) ?></a>
<?php endif ?> <?php endif ?>
<p class="footer-payment-label">支持的付款方式</p>
<div class="payment-methods" aria-label="支持的付款方式"> <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-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-alipay.png" alt="支付宝" width="26" height="26" loading="lazy">
<img src="/assets/original/payment-wechat.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> </div>
<?php foreach (['products', 'company'] as $group): ?> <nav class="footer-links" aria-label="页脚导航">
<?php foreach (['products', 'company', 'resources'] as $group): ?>
<?php if (!$footer[$group] && $footer[$group . '_title'] === '') { continue; } ?> <?php if (!$footer[$group] && $footer[$group . '_title'] === '') { continue; } ?>
<div> <div>
<?php if ($footer[$group . '_title'] !== ''): ?><p class="footer-label"><?= $e($footer[$group . '_title']) ?></p><?php endif ?> <?php if ($footer[$group . '_title'] !== ''): ?><h2 class="footer-label"><?= $e($footer[$group . '_title']) ?></h2><?php endif ?>
<?php foreach ($footer[$group] as [$url, $label]): ?><a href="<?= $e($url) ?>"><?= $e($label) ?></a><?php endforeach ?> <?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> </div>
<?php endforeach ?> <?php endforeach ?>
</nav>
</div> </div>
<div class="footer-meta"> <div class="footer-meta">
<?php if ($footer['copyright']): ?><p><?= $e($footer['copyright']) ?> 2024–<?= $e(date('Y')) ?></p><?php endif ?> <?php if ($footer['copyright']): ?><p><?= $e($footer['copyright']) ?></p><?php endif ?>
<?php if ($footer['phones']): ?> <?php if ($footer['email'] || $footer['phones']): ?>
<p>全球号码 <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]): ?> <?php foreach ($footer['phones'] as $index => [$url, $label]): ?>
<?= $index ? ' / ' : '' ?><a href="<?= $e($url) ?>"><?= $e($label) ?></a> <?= $index ? ' / ' : '' ?><a href="<?= $e($url) ?>"><?= $e($label) ?></a>
<?php endforeach ?> <?php endforeach ?>
<?php endif ?>
</p> </p>
<?php endif ?> <?php endif ?>
<?php if ($footer['registration']): ?><a href="https://beian.miit.gov.cn/"><?= $e($footer['registration']) ?></a><?php endif ?>
<?php if ($footer['terms']): ?><p class="footer-terms"><?= $e($footer['terms']) ?></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>
</div> </div>
</footer> </footer>
+1 -1
View File
@@ -13,7 +13,7 @@ if (str_starts_with($imageUrl, '/')) {
$kind = in_array($page['slug'] ?? '', ['sc', 'shnu-sc'], true) ? 'service' : 'software'; $kind = in_array($page['slug'] ?? '', ['sc', 'shnu-sc'], true) ? 'service' : 'software';
$siteKind = $kind === 'service' ? 'other' : 'software'; $siteKind = $kind === 'service' ? 'other' : 'software';
$header = ($site['header'] ?? []) + SiteDesign::DEFAULT_HEADER; $header = ($site['header'] ?? []) + SiteDesign::DEFAULT_HEADER;
$footer = ($site['footer'] ?? []) + SiteDesign::DEFAULT_FOOTER + $site; $footer = SiteDesign::footer($site);
$nav = $header['links']; $nav = $header['links'];
$contact = $header['button']; $contact = $header['button'];
?> ?>
+1 -16
View File
@@ -15,22 +15,7 @@ $e = View::escape(...);
<div class="network-group" id="<?= $e($slug) ?>"> <div class="network-group" id="<?= $e($slug) ?>">
<?php if ($standalone): ?><h2><?= $e($group['name']) ?></h2><?php else: ?><h3><?= $e($group['name']) ?></h3><?php endif ?> <?php if ($standalone): ?><h2><?= $e($group['name']) ?></h2><?php else: ?><h3><?= $e($group['name']) ?></h3><?php endif ?>
<?php if (!$group['articles']): ?><p class="empty-state">暂无已发布条目。</p><?php endif ?> <?php if (!$group['articles']): ?><p class="empty-state">暂无已发布条目。</p><?php endif ?>
<ul class="network-list"> <?= View::fragment('network-items', ['articles' => $group['articles'], 'standalone' => $standalone]) ?>
<?php foreach ($group['articles'] as $item): ?>
<?php $card = $item['card']; $articlePath = '/articles/' . $item['slug']; ?>
<li>
<a href="<?= $e(($card['url'] ?? '') ?: $articlePath) ?>">
<?php if (!empty($card['image'])): ?>
<img src="<?= $e($card['image']) ?>" alt="" loading="lazy" width="76" height="28">
<?php endif ?>
<span><?= $e($item['title']) ?></span>
</a>
<?php if ($standalone && !empty($card['url']) && ($item['body'] !== '' || $item['summary'] !== '')): ?>
<a class="network-detail" href="<?= $e($articlePath) ?>">查看详情</a>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
</div> </div>
<?php endforeach ?> <?php endforeach ?>
</div> </div>
+27
View File
@@ -0,0 +1,27 @@
<?php
use App\Content\DirectoryCard;
use App\Content\Html;
use App\Content\View;
$e = View::escape(...);
?>
<ul class="network-list">
<?php foreach ($articles as $item): ?>
<?php
$card = $item['card'];
['primary' => $target, 'detail' => $detail] = DirectoryCard::links($item, Html::articleBody($item));
?>
<li>
<?php if ($target !== ''): ?><a href="<?= $e($target) ?>"><?php else: ?><span class="network-static"><?php endif ?>
<?php if (!empty($card['image'])): ?>
<img src="<?= $e($card['image']) ?>" alt="" loading="lazy" width="76" height="28">
<?php endif ?>
<span><?= $e($item['title']) ?></span>
<?php if ($target !== ''): ?></a><?php else: ?></span><?php endif ?>
<?php if ($standalone && $detail !== ''): ?>
<a class="network-detail" href="<?= $e($detail) ?>">查看详情</a>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
+13 -16
View File
@@ -5,6 +5,8 @@ use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
$home = $page['slug'] === 'home'; $home = $page['slug'] === 'home';
$service = in_array($page['slug'], ['sc', 'shnu-sc'], true); $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 . '"' : ''; $field = static fn (string $name): string => $canvas ? ' data-studio-field="' . $name . '"' : '';
?> ?>
<section class="hero hero-<?= $e($page['slug']) ?>" id="home" data-enter> <section class="hero hero-<?= $e($page['slug']) ?>" id="home" data-enter>
@@ -25,16 +27,16 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' .
<?php else: ?> <?php else: ?>
<p class="overline hero-label"><?= $e($site['footer']['name'] ?? $site['name']) ?></p> <p class="overline hero-label"><?= $e($site['footer']['name'] ?? $site['name']) ?></p>
<?php endif ?> <?php endif ?>
<h1><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> <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"<?= $field('lead') ?>><?= $e($page['lead']) ?></p> <p class="hero-lead<?= View::alignmentClass($alignments['lead'] ?? null) ?>"<?= $field('lead') ?><?= $alignField('lead') ?>><?= $e($page['lead']) ?></p>
<div class="actions hero-actions"> <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]): ?> <?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> <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 ?> <?php endforeach ?>
</div> </div>
</div> </div>
<?php if ($canvas || $page['image'] !== ''): ?> <?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']) : '' ?>" data-visual<?= $page['image'] === '' ? ' hidden' : '' ?>> <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' : '' ?>> <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'): ?> <?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"> <svg class="home-pipe-flow" viewBox="0 0 640 480" aria-hidden="true" focusable="false">
@@ -53,15 +55,11 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' .
</div> </div>
<?php endif ?> <?php endif ?>
</div> </div>
<?php if ($home): ?> <?php foreach ($page['sections'] as $section): ?>
<div class="wrap hero-directory"> <?php if ($section['style'] === 'hero-links'): ?>
<a class="overline directory-label" href="/services">产品与服务</a> <?= View::fragment('section', ['section' => $section, 'moment' => false, 'canvas' => $canvas, 'pageSlug' => $page['slug']]) ?>
<a href="/pagepan"><span>PAGEPAN</span><small>可视化建站</small></a>
<a href="/highspeaker"><span>HighSpeaker DNS</span><small>开源智能解析</small></a>
<a href="/sc"><span>软著代理</span><small>登记申请与材料服务</small></a>
<a href="/shnu-sc"><span>SHNU 学生</span><small>软著申请方案</small></a>
</div>
<?php endif ?> <?php endif ?>
<?php endforeach ?>
</section> </section>
<?php if ($canvas || $page['quicklinks']): ?> <?php if ($canvas || $page['quicklinks']): ?>
<nav class="section-nav" aria-label="本页目录"<?= $canvas ? ' data-studio-navigation' : '' ?><?= !$page['quicklinks'] ? ' hidden' : '' ?>> <nav class="section-nav" aria-label="本页目录"<?= $canvas ? ' data-studio-navigation' : '' ?><?= !$page['quicklinks'] ? ' hidden' : '' ?>>
@@ -73,7 +71,9 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' .
</nav> </nav>
<?php endif ?> <?php endif ?>
<?php foreach ($page['sections'] as $section): ?> <?php foreach ($page['sections'] as $section): ?>
<?= View::fragment('section', ['section' => $section, 'moment' => $home && $section['key'] === 'about', 'canvas' => $canvas]) ?> <?php if ($section['style'] !== 'hero-links'): ?>
<?= View::fragment('section', ['section' => $section, 'moment' => $home && $section['key'] === 'about', 'canvas' => $canvas, 'pageSlug' => $page['slug']]) ?>
<?php endif ?>
<?php endforeach ?> <?php endforeach ?>
<?php if ($canvas): ?> <?php if ($canvas): ?>
<template data-studio-section-end><?= View::fragment('section', [ <template data-studio-section-end><?= View::fragment('section', [
@@ -81,6 +81,3 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' .
'moment' => false, 'canvas' => true, 'moment' => false, 'canvas' => true,
]) ?></template> ]) ?></template>
<?php endif ?> <?php endif ?>
<?php if ($home): ?>
<?= View::fragment('network-groups', ['network' => $network, 'standalone' => false]) ?>
<?php endif ?>
+42 -6
View File
@@ -3,16 +3,52 @@ use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
$canvas ??= false; $canvas ??= false;
$body = $section['body'];
$dynamic = isset($section['feed']);
$studio = $canvas ? ' data-studio-section="' . $e($section['version']) . '" data-studio-source="' . $e(base64_encode($section['body'])) . '"' : '';
if ($canvas && $dynamic) {
$studio .= ' data-studio-dynamic data-studio-feed="' . $e($section['feed']) . '" tabindex="0"';
}
if ($section['style'] === 'hero-links'):
?> ?>
<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 hero-directory-slot" id="<?= $e($section['key']) ?>"<?= $studio ?>>
<?php if ($canvas): ?><span data-studio-part="title" hidden><?= $e($section['title']) ?></span><span data-studio-part="lead" hidden><?= $e($section['lead']) ?></span><?php endif ?>
<div<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $body ?></div>
</div>
<?php
return;
endif;
$alignments = json_decode($section['alignments'] ?? '{}', true, flags: JSON_THROW_ON_ERROR);
if ($dynamic && $body === '<p><a class="back-link" href="/articles">查看全部动态</a></p>') {
$body = '';
}
$network = $section['networkFeed'] ?? false;
$catalog = $section['catalogFeed'] ?? false;
?>
<section class="section section-<?= $e($section['style']) ?><?= $network ? ' network' : '' ?>" id="<?= $e($section['key']) ?>" aria-labelledby="heading-<?= $e($section['key']) ?>" <?= $moment ? 'data-moment="iris-opens"' : '' ?><?= $studio ?>>
<div class="wrap"> <div class="wrap">
<div class="section-heading"> <div class="section-heading">
<h2 id="heading-<?= $e($section['key']) ?>"<?= $canvas ? ' data-studio-part="title"' : '' ?>><?= $e($section['title']) ?></h2> <h2 id="heading-<?= $e($section['key']) ?>"<?= isset($alignments['title']) ? ' class="' . trim(View::alignmentClass($alignments['title'])) . '"' : '' ?><?= $canvas ? ' data-studio-part="title"' : '' ?>><?= $e($section['title']) ?></h2>
<?php if ($canvas || $section['lead']): ?><p<?= $canvas ? ' data-studio-part="lead"' : '' ?>><?= $e($section['lead']) ?></p><?php endif ?> <?php if ($canvas || $section['lead']): ?><p<?= isset($alignments['lead']) ? ' class="' . trim(View::alignmentClass($alignments['lead'])) . '"' : '' ?><?= $canvas ? ' data-studio-part="lead"' : '' ?>><?= $e($section['lead']) ?></p><?php endif ?>
</div> </div>
<?php if (!empty($section['articleFeed'])): ?> <?php if ($network): ?>
<?= View::fragment('article-feed', ['groups' => $section['articleFeed'], 'sectionKey' => $section['key']]) ?> <?php foreach ($section['articleFeed'] as $group): ?>
<?php $slug = $group['categories'][0]; $anchor = ($pageSlug ?? '') === 'home' && $section['key'] === 'network' ? $slug : $section['key'] . '-group-' . $slug; ?>
<div class="network-group" id="<?= $e($anchor) ?>">
<h3><?= $e($group['label']) ?></h3>
<?= View::fragment('network-items', ['articles' => $group['articles'], 'standalone' => false]) ?>
</div>
<?php endforeach ?>
<?php if ($section['archivePath'] !== null): ?><p class="article-feed-archive"><a class="back-link" href="<?= $e($section['archivePath']) ?>">查看全部</a></p><?php endif ?>
<?php elseif ($catalog): ?>
<?= View::fragment('service-cards', ['products' => $section['articleFeed'][0]['articles']]) ?>
<?php if ($section['archivePath'] !== null && count($section['articleFeed'][0]['articles']) >= $section['feedLimit']): ?>
<p class="article-feed-archive"><a class="back-link" href="<?= $e($section['archivePath']) ?>">查看全部</a></p>
<?php endif ?> <?php endif ?>
<?php if ($canvas || $section['body'] !== ''): ?><div class="rich<?= !empty($section['articleFeed']) ? ' article-feed-note' : '' ?>"<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $section['body'] ?></div><?php endif ?> <?php elseif (!empty($section['articleFeed'])): ?>
<?= View::fragment('article-feed', ['groups' => $section['articleFeed'], 'sectionKey' => $section['key'], 'archivePath' => $section['archivePath']]) ?>
<?php endif ?>
<?php if ($canvas || $body !== ''): ?><div class="rich<?= $dynamic ? ' article-feed-note' : '' ?>"<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $body ?></div><?php endif ?>
</div> </div>
</section> </section>
+38
View File
@@ -0,0 +1,38 @@
<?php
use App\Content\DirectoryCard;
use App\Content\Html;
use App\Content\View;
$e = View::escape(...);
?>
<?php if (!$products): ?><p class="empty-state">暂无可查看的产品和服务。</p><?php endif ?>
<div class="catalog-grid">
<?php foreach ($products as $product): ?>
<?php
$card = $product['card'];
$body = Html::articleBody($product);
$target = DirectoryCard::links($product, $body)['primary'];
$extra = $card['extra_url'] ?? '';
?>
<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 ?>
<h3><?php if ($target !== ''): ?><a href="<?= $e($target) ?>"><?= $e($product['title']) ?></a><?php else: ?><?= $e($product['title']) ?><?php endif ?></h3>
<?php if ($product['summary']): ?>
<p><?= $e($product['summary']) ?></p>
<?php else: ?>
<div class="rich"><?= $body ?></div>
<?php endif ?>
<?php if ($target !== '' || $extra !== ''): ?>
<div class="actions">
<?php if ($target !== ''): ?><a class="button button-primary" href="<?= $e($target) ?>"><?= $e(($card['label'] ?? '') ?: '了解详情') ?></a><?php endif ?>
<?php if ($extra !== '' && $extra !== $target): ?><a href="<?= $e($extra) ?>"><?= $e(($card['extra_label'] ?? '') ?: '相关链接') ?></a><?php endif ?>
</div>
<?php endif ?>
</div>
</article>
<?php endforeach ?>
</div>
-41
View File
@@ -1,41 +0,0 @@
<?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']; $articlePath = '/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><a href="<?= $e($articlePath) ?>"><?= $e($product['title']) ?></a></h2>
<?php if ($product['summary']): ?>
<p><?= $e($product['summary']) ?></p>
<?php else: ?>
<div class="rich"><?= Html::articleBody($product) ?></div>
<?php endif ?>
<div class="actions">
<a class="button button-primary" href="<?= $e(($card['url'] ?? '') ?: $articlePath) ?>"><?= $e(($card['label'] ?? '') ?: '了解详情') ?></a>
<?php if (!empty($card['extra_url'])): ?><a href="<?= $e($card['extra_url']) ?>"><?= $e(($card['extra_label'] ?? '') ?: '相关链接') ?></a><?php endif ?>
</div>
</div>
</article>
<?php endforeach ?>
</div>
</div>
</section>
+24
View File
@@ -0,0 +1,24 @@
<?php
use App\Content\BlockTemplates;
use App\Content\View;
$e = View::escape(...);
?>
<details class="studio-anchor-create">
<summary>按锚点新建区块</summary>
<form class="admin-form" method="post" action="/admin/page-blocks/<?= $e($slug) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="operation" value="create">
<label>锚点<input name="key" pattern="[a-z0-9]+(-[a-z0-9]+)*" maxlength="70" placeholder="overview" required></label>
<label>模板<select name="preset">
<?php foreach (BlockTemplates::groups() as [$category, $templates]): ?>
<optgroup label="<?= $e($category) ?>">
<?php foreach ($templates as $preset => [$label]): ?>
<option value="<?= $e($preset) ?>"><?= $e($label) ?></option>
<?php endforeach ?>
</optgroup>
<?php endforeach ?>
</select></label>
<button type="submit" class="button button-outline">新建</button>
</form>
</details>
+15
View File
@@ -0,0 +1,15 @@
<?php
use App\Content\View;
$e = View::escape(...);
$modes = ($allowOff ? ['off' => '不展示'] : []) + ['merged' => '合并列表', 'tabs' => '分类标签页', 'network' => '项目与伙伴卡片', 'catalog' => '产品与服务卡片'];
?>
<div class="form-grid">
<label>展示方式<select name="feed_mode">
<?php foreach ($modes as $mode => $label): ?>
<option value="<?= $mode ?>" <?= ($feed['mode'] ?? 'off') === $mode ? 'selected' : '' ?>><?= $e($label) ?></option>
<?php endforeach ?>
</select></label>
<label>展示数量<input name="feed_limit" type="number" required min="1" max="30" value="<?= $e($feed['limit'] ?? 6) ?>"><small>分组时每个分类独立计数。</small></label>
</div>
<?= View::fragment('admin-category-checkboxes', ['name' => 'feed_categories', 'selected' => $feed['categories'] ?? [], 'categories' => $categories, 'legend' => '展示分类']) ?>
+12
View File
@@ -0,0 +1,12 @@
<?php
$paths = [
'left' => '<path d="M3 6h18M3 10h12M3 14h18M3 18h12"/>',
'center' => '<path d="M3 6h18M6 10h12M3 14h18M6 18h12"/>',
'right' => '<path d="M3 6h18M9 10h12M3 14h18M9 18h12"/>',
'settings' => '<path d="M4 6h12m4 0h0M4 12h3m4 0h9M4 18h10m4 0h2"/><circle cx="17" cy="6" r="2"/><circle cx="9" cy="12" r="2"/><circle cx="16" cy="18" r="2"/>',
'edit' => '<path d="m14 5 5 5M5 19l4-.8L20 7.3 16.7 4 5.8 15z"/>',
'copy' => '<rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 4H6a2 2 0 0 0-2 2v10"/>',
'delete' => '<path d="M4 7h16M9 7V4h6v3m3 0-.8 13H6.8L6 7m4 4v5m4-5v5"/>',
];
?>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><?= $paths[$icon] ?></svg>
+30
View File
@@ -0,0 +1,30 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<details class="studio-layers" id="blocks">
<summary>区块顺序</summary>
<ul class="admin-list studio-blocks">
<?php foreach ($page['sections'] as $index => $item): ?>
<?php $fixedSlot = $item['style'] === 'hero-links'; ?>
<li>
<div><strong><?= $e($item['title']) ?></strong><small>#<?= $e($item['key']) ?></small></div>
<div class="actions studio-block-actions">
<button class="button button-outline" type="button" data-canvas-jump="<?= $e($item['key']) ?>" hidden>在画布编辑</button>
<a class="button button-outline" href="/admin/pages/<?= $e($slug) ?>/<?= $e($item['key']) ?>">区块设置</a>
<form method="post" action="/admin/page-blocks/<?= $e($slug) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<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" <?= $fixedSlot || $index === 0 || $page['sections'][$index - 1]['style'] === 'hero-links' ? 'disabled' : '' ?>>上移</button>
<button class="button button-outline" name="operation" value="down" type="submit" <?= $fixedSlot || $index === count($page['sections']) - 1 ? 'disabled' : '' ?>>下移</button>
<button class="button button-outline" name="operation" value="delete" type="submit" data-confirm="删除这个区块?">删除</button>
</form>
</div>
</li>
<?php endforeach ?>
</ul>
</details>
+63
View File
@@ -0,0 +1,63 @@
<?php
use App\Content\View;
$e = View::escape(...);
$modules = $kind === 'modules';
?>
<section role="tabpanel" id="studio-panel-<?= $kind ?>" aria-labelledby="studio-tab-<?= $kind ?>" data-library-panel="<?= $kind ?>" hidden>
<ul class="studio-library-categories" data-library-index>
<?php foreach ($groups as $group => [$category, $items]): ?>
<li><button type="button" data-library-category="<?= $e($group) ?>" data-library-label="<?= $e($category) ?>">
<span><?= $e($category) ?></span><small><?= count($items) ?></small>
</button></li>
<?php endforeach ?>
</ul>
<?php if ($modules): ?><?= $anchorForm ?><?php endif ?>
<div class="studio-library-content" data-library-content hidden>
<div class="studio-library-category-title">
<button type="button" data-library-back>返回分类</button>
<h3 data-library-title></h3>
</div>
<label class="studio-template-search">查找本分类<input type="search" data-template-search autocomplete="off"></label>
<?php if ($modules): ?>
<label class="studio-insert-mode"><input type="checkbox" data-template-inline> 插入当前正文</label>
<?php endif ?>
<p class="field-note" data-template-empty hidden role="status">没有匹配的<?= $modules ? '组件' : '元素' ?>。</p>
<?php foreach ($groups as $group => [$category, $items]): ?>
<div class="<?= $modules ? 'studio-template-cards' : 'studio-element-items' ?>" data-template-group="<?= $e($group) ?>" hidden>
<?php foreach ($items as $key => $item): ?>
<?php [$label, $markup, $option, $feed] = array_pad($item, 4, null); ?>
<?php if ($modules): ?>
<article class="studio-template-card" data-template-card data-library-item data-template-search-text="<?= $e($label . ' ' . $key) ?>">
<button type="button" class="studio-template-image" data-template-preview="<?= $e($key) ?>" data-template-title="<?= $e($label) ?>"
aria-label="预览<?= $e($label) ?>组件">
<img src="/assets/template-previews/<?= $e($key) ?>.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($key) ?>"
data-template-title="<?= $e($label) ?>" data-template-lead="<?= $e($option) ?>" data-template-style="<?= $e($item[4] ?? 'plain') ?>"
<?= $feed !== null ? 'data-template-feed="' . $e($feed) . '"' : '' ?> aria-label="添加<?= $e($label) ?>组件">添加</button>
</div>
<template data-preset="<?= $e($key) ?>"><?= $markup ?></template>
</article>
<?php else: ?>
<div data-library-item data-template-search-text="<?= $e($label . ' ' . $key) ?>">
<button type="button" disabled data-canvas-element="<?= $e($key) ?>"
<?php if ($option): ?>data-element-mime="<?= $e($option) ?>"<?php endif ?>
aria-label="插入<?= $e($label) ?>"><?= $e($label) ?></button>
<template data-element="<?= $e($key) ?>"><?= $markup ?></template>
</div>
<?php endif ?>
<?php endforeach ?>
</div>
<?php endforeach ?>
</div>
<?php if ($modules): ?>
<p class="field-note" data-template-status role="status"></p>
<ul class="studio-pending" data-template-pending aria-label="待保存区块" hidden></ul>
<?php else: ?>
<p class="field-note" data-element-status role="status"></p>
<?php endif ?>
</section>
+9 -1
View File
@@ -36,7 +36,7 @@ $e = View::escape(...);
<small>每行填写「显示号码 | tel:号码」。</small> <small>每行填写「显示号码 | tel:号码」。</small>
</label> </label>
<div class="form-grid"> <div class="form-grid">
<?php foreach (['products' => '第一列', 'company' => '第二列'] as $key => $text): ?> <?php foreach (['products' => '第一列', 'company' => '第二列', 'resources' => '第三列'] as $key => $text): ?>
<div class="admin-form"> <div class="admin-form">
<label><?= $text ?>标题<input name="<?= $key ?>_title" value="<?= $e($config[$key . '_title']) ?>"></label> <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> <label><?= $text ?>链接<textarea name="<?= $key ?>" rows="6"><?= $e(SiteDesign::linkText($config[$key])) ?></textarea>
@@ -50,3 +50,11 @@ $e = View::escape(...);
<?php endif ?> <?php endif ?>
<div class="form-submit"><button class="button button-primary" type="submit">保存设置</button></div> <div class="form-submit"><button class="button button-primary" type="submit">保存设置</button></div>
</form> </form>
<?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 ?>
+10 -30
View File
@@ -4,42 +4,22 @@ use App\Content\BlockTemplates;
use App\Content\View; use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
$labels = ['modules' => '组件', 'elements' => '元素', 'layers' => '图层'];
?> ?>
<div class="studio-presets" data-canvas-presets> <div class="studio-presets" data-canvas-presets>
<label class="studio-template-search">搜索模板<input type="search" data-template-search placeholder="按名称或分类搜索" autocomplete="off"></label> <div class="studio-library-tabs" role="tablist" aria-label="页面编辑工具" data-library-tabs hidden>
<div class="studio-template-filters" role="group" aria-label="模板分类"> <?php foreach ($labels as $kind => $label): ?>
<button type="button" data-template-filter="" aria-pressed="true">全部</button> <button type="button" role="tab" id="studio-tab-<?= $kind ?>" aria-controls="studio-panel-<?= $kind ?>"
<?php foreach (BlockTemplates::GROUPS as $group => [$category]): ?> aria-selected="false" tabindex="-1" data-library-tab="<?= $kind ?>"><?= $e($label) ?></button>
<button type="button" data-template-filter="<?= $e($group) ?>" aria-pressed="false"><?= $e($category) ?></button>
<?php endforeach ?> <?php endforeach ?>
</div> </div>
<label class="studio-insert-mode"><input type="checkbox" data-template-inline> 插入当前正文</label> <?php foreach (['modules' => BlockTemplates::groups(), 'elements' => BlockTemplates::ELEMENT_GROUPS] as $kind => $groups): ?>
<p class="field-note" data-template-status role="status"></p> <?= View::fragment('studio-library-panel', compact('kind', 'groups', 'anchorForm')) ?>
<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 ?> <?php endforeach ?>
</div> <section role="tabpanel" id="studio-panel-layers" aria-labelledby="studio-tab-layers" data-library-panel="layers">
<?= $layers ?>
</section> </section>
<?php endforeach ?>
</div>
<div class="studio-template-peek" data-template-peek aria-hidden="true" hidden> <div class="studio-template-peek" data-template-peek aria-hidden="true" hidden>
<img alt=""> <img alt="">
<p></p> <p></p>
+2 -2
View File
@@ -10,12 +10,11 @@ use Webman\Route;
Route::disableDefaultRoute(); Route::disableDefaultRoute();
Route::get('/', [SiteController::class, 'home']); Route::get('/', [SiteController::class, 'home']);
Route::get('/services', [SiteController::class, 'services']);
Route::get('/network', [SiteController::class, 'network']); Route::get('/network', [SiteController::class, 'network']);
Route::get('/assets/uploads/{name:[a-f0-9]{32}\.[a-z0-9]+}', [MediaController::class, 'file']); 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:[a-z0-9-]+}', [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/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('/articles/{slug:[a-z0-9-]+}', [SiteController::class, 'article']);
Route::get('/main', static fn () => View::redirect('/articles', 301)); Route::get('/main', static fn () => View::redirect('/articles', 301));
Route::get('/main/category/{id:[0-9]+}.html', [SiteController::class, 'legacyCategory']); Route::get('/main/category/{id:[0-9]+}.html', [SiteController::class, 'legacyCategory']);
@@ -32,6 +31,7 @@ Route::add(['GET', 'POST'], '/admin/article-categories', [AdminController::class
Route::get('/admin/articles', [AdminController::class, 'articles']); Route::get('/admin/articles', [AdminController::class, 'articles']);
Route::add(['GET', 'POST'], '/admin/articles/new', [AdminController::class, 'article']); 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/articles/{id:[0-9]+}', [AdminController::class, 'article']);
Route::post('/admin/articles/{id:[0-9]+}/delete', [AdminController::class, 'deleteArticle']);
Route::add(['GET', 'POST'], '/admin/new-page', [StudioController::class, 'newPage']); Route::add(['GET', 'POST'], '/admin/new-page', [StudioController::class, 'newPage']);
Route::get('/admin/pages/{slug:[a-z0-9-]+}/preview', [StudioController::class, 'previewPage']); 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::post('/admin/page-blocks/{slug:[a-z0-9-]+}', [StudioController::class, 'blocks']);
+100 -20
View File
@@ -37,6 +37,8 @@
.feedback { padding: .8rem 1rem; border-radius: .5rem; } .feedback { padding: .8rem 1rem; border-radius: .5rem; }
.feedback.error { background: #feebeb; color: #9c252a; } .feedback.error { background: #feebeb; color: #9c252a; }
.feedback.success { background: #e5f6ed; color: #126044; } .feedback.success { background: #e5f6ed; color: #126044; }
.button-danger { color: #9c252a; background: transparent; border-color: #e6b6b9; }
.button-danger:hover { color: #9c252a; background: #feebeb; }
.editor { display: grid; gap: .45rem; } .editor { display: grid; gap: .45rem; }
.editor-toolbar { display: flex; flex-wrap: wrap; gap: .45rem; justify-content: space-between; padding: .45rem; border: 1px solid var(--line); background: var(--paper); border-radius: .5rem; } .editor-toolbar { display: flex; flex-wrap: wrap; gap: .45rem; justify-content: space-between; padding: .45rem; border: 1px solid var(--line); background: var(--paper); border-radius: .5rem; }
.editor-toolbar > div { display: flex; flex-wrap: wrap; gap: .25rem; } .editor-toolbar > div { display: flex; flex-wrap: wrap; gap: .25rem; }
@@ -132,16 +134,19 @@
.studio-layers .studio-block-actions .button { min-height: 2.25rem; padding: .25rem .5rem; font-size: .8rem; } .studio-layers .studio-block-actions .button { min-height: 2.25rem; padding: .25rem .5rem; font-size: .8rem; }
.studio-media-sizing { position: absolute; z-index: 1; inset: auto .6rem .6rem auto; display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; padding: .45rem .6rem; max-width: calc(100% - 1.2rem); background: var(--accent-light); border: 1px solid var(--line); border-radius: .45rem; } .studio-media-sizing { position: absolute; z-index: 1; inset: auto .6rem .6rem auto; display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; padding: .45rem .6rem; max-width: calc(100% - 1.2rem); background: var(--accent-light); border: 1px solid var(--line); border-radius: .45rem; }
.studio-element-tools { .studio-element-tools {
position: absolute; z-index: 3; display: flex; align-items: center; gap: .15rem; padding: .2rem; position: absolute; z-index: 3; display: flex; align-items: center; gap: .12rem; padding: .18rem;
border: 1px solid #3f62e0; border-radius: .65rem; background: #244bc8; border: 1px solid #c7d6f3; border-radius: .52rem; background: var(--white);
box-shadow: 0 .22rem .7rem #13297538; box-shadow: 0 .22rem .85rem #16305230;
} }
.studio-element-tools button { .studio-element-tools button {
min-height: 2rem; padding: .22rem .6rem; border: 0; border-radius: .42rem; display: grid; place-items: center; width: 2rem; height: 2rem; padding: 0;
background: transparent; color: white; font-size: .84rem; white-space: nowrap; cursor: pointer; border: 0; border-radius: .32rem; background: transparent; color: #35496d; cursor: pointer;
} }
.studio-element-tools button:hover, .studio-element-tools button:focus-visible { background: #ffffff32; } .studio-element-tools button svg { width: 1rem; height: 1rem; pointer-events: none; }
.studio-element-tools button:focus-visible { outline: 1px solid white; outline-offset: -2px; } .studio-element-tools button:hover, .studio-element-tools button:focus-visible { background: var(--accent-light); color: var(--accent-deep); }
.studio-element-tools button:focus-visible { outline: 1px solid var(--accent); outline-offset: -2px; }
.studio-element-tools button[data-element-delete]:hover { color: #a12727; background: #fceeee; }
.studio-element-tools.is-module [data-element-module-settings] { background: var(--accent-light); color: var(--accent-deep); }
.studio-media-handle { .studio-media-handle {
position: absolute; z-index: 2; width: 1.4rem; height: 2.8rem; translate: -50% -50%; position: absolute; z-index: 2; width: 1.4rem; height: 2.8rem; translate: -50% -50%;
display: grid; place-content: center; border: 2px solid white; border-radius: .42rem; display: grid; place-content: center; border: 2px solid white; border-radius: .42rem;
@@ -167,19 +172,29 @@
border: 1px solid var(--line); border: 1px solid var(--line);
border-radius: .5rem; border-radius: .5rem;
} }
.studio-template-filters { display: flex; gap: .3rem; flex-wrap: wrap; margin-block: .25rem; } .studio-library-tabs { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .2rem; padding: .22rem; margin-bottom: .45rem; border-radius: .6rem; background: var(--paper); }
.studio-template-filters button { .studio-library-tabs button, .studio-library-categories button, .studio-library-category-title button, .studio-element-items button {
min-height: 36px; color: var(--ink); font-family: inherit; cursor: pointer;
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-library-tabs button { min-height: 2.4rem; padding: .3rem .18rem; border: 1px solid transparent; border-radius: .42rem; background: transparent; font-size: .84rem; }
.studio-template-group + .studio-template-group { margin-top: .9rem; } .studio-library-tabs button[aria-selected="true"] { border-color: var(--line); background: var(--white); color: var(--accent-deep); font-weight: 650; box-shadow: 0 1px 2px #182e5110; }
.studio-template-group h3 { margin: 0 0 .4rem; font-size: .9rem; font-weight: 650; } .studio-library-categories { list-style: none; padding: 0; margin: 0; }
.studio-library-categories li + li { border-top: 1px solid var(--line); }
.studio-library-categories button, .studio-element-items button {
display: flex; gap: .35rem; align-items: center; width: 100%; min-height: 2.65rem; padding: .4rem .32rem;
text-align: left; border: 1px solid transparent; border-radius: .35rem; background: transparent; font-size: .9rem;
}
.studio-library-categories button::after { content: ''; width: .38rem; height: .38rem; border: solid currentColor; border-width: 1px 1px 0 0; rotate: 45deg; margin-inline-end: .25rem; }
.studio-library-categories small { margin-inline-start: auto; color: var(--muted); font-variant-numeric: tabular-nums; }
.studio-library-content { display: grid; gap: .55rem; min-width: 0; }
.studio-library-category-title { display: grid; gap: .28rem; }
.studio-library-category-title h3 { font-size: 1rem; margin: 0; }
.studio-library-category-title button { justify-self: start; min-height: 2.25rem; padding: .25rem .45rem; background: var(--white); border: 1px solid var(--line); border-radius: .38rem; font-size: .8rem; }
.studio-library-category-title button::before { content: '‹'; margin-inline-end: .3em; }
.studio-element-items { display: grid; gap: .35rem; }
.studio-element-items button { justify-content: space-between; padding-inline: .55rem; border-color: var(--line); background: var(--white); }
.studio-element-items button::after { content: '+'; color: var(--accent-deep); }
.studio-element-items button:disabled { opacity: .55; cursor: wait; }
.studio-template-cards { display: grid; gap: .48rem; } .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 { 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-card:focus-within { border-color: var(--accent); }
@@ -213,7 +228,7 @@
.studio-template-dialog > .actions { justify-content: flex-end; margin-top: .75rem; } .studio-template-dialog > .actions { justify-content: flex-end; margin-top: .75rem; }
@media (max-width: 54rem) { @media (max-width: 54rem) {
.studio-template-groups { max-height: 44dvh; overflow-y: auto; padding: .2rem; } .studio-library-content { max-height: 55dvh; overflow-y: auto; padding: .2rem; }
.studio-template-cards { grid-template-columns: repeat(auto-fill, minmax(8.5rem, 1fr)); } .studio-template-cards { grid-template-columns: repeat(auto-fill, minmax(8.5rem, 1fr)); }
.studio-template-meta { flex-wrap: wrap; } .studio-template-meta { flex-wrap: wrap; }
.studio-template-peek { display: none; } .studio-template-peek { display: none; }
@@ -234,3 +249,68 @@
.article-editor-heading { display: flex; align-items: center; justify-content: space-between; gap: .6rem; margin-bottom: .45rem; } .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-heading > .button { min-height: 2.1rem; padding: .25rem .6rem; }
.article-editor-help:empty { display: none; } .article-editor-help:empty { display: none; }
.studio-element-align { display: flex; gap: .05rem; padding-inline-end: .15rem; border-inline-end: 1px solid var(--line); }
.studio-element-align button[aria-pressed="true"] { background: var(--accent-light); color: var(--accent-deep); }
.admin-primary a { padding: .28rem .65rem; border-radius: .48rem; color: var(--muted); }
.admin-primary a[aria-current="page"] { background: var(--accent-light); color: var(--accent-deep); }
.admin-utility { display: flex; gap: .8rem; align-items: center; font-size: .88rem; }
.admin-utility > a { padding-block: .55rem; white-space: nowrap; }
.admin-account { position: relative; z-index: 5; }
.admin-account summary {
min-height: 2.45rem; padding: .43rem .6rem; border: 1px solid var(--line);
border-radius: .45rem; color: var(--ink); cursor: pointer;
}
.admin-account-menu {
position: absolute; inset: calc(100% + .4rem) 0 auto auto; min-width: 8rem; padding: .3rem;
border: 1px solid var(--line); border-radius: .5rem; background: white; box-shadow: 0 .55rem 1.5rem #1d315026;
}
.admin-account-menu a, .admin-account-menu button {
display: block; width: 100%; padding: .52rem .65rem; border: 0; border-radius: .3rem; background: white;
color: var(--ink); text-align: left; text-decoration: none; font: inherit; cursor: pointer;
}
.admin-account-menu :is(a, button):hover { background: var(--paper); color: var(--accent-deep); }
.dashboard-heading { margin-bottom: 1.55rem; }
.dashboard-grid { display: grid; grid-template-columns: minmax(0, 1.8fr) minmax(0, 1fr); align-items: start; gap: 1.05rem; }
.dashboard-grid .admin-panel { padding: clamp(.95rem, 2.3vw, 1.55rem); }
.dashboard-filters { display: grid; grid-template-columns: 1fr minmax(6.8rem, 9rem); gap: .7rem; margin-bottom: .8rem; }
.dashboard-filters label { display: grid; min-width: 0; gap: .25rem; font-size: .83rem; color: var(--muted); }
.dashboard-filters :is(input, select) { width: 100%; min-height: 2.65rem; padding: .38rem .52rem; border: 1px solid var(--line); border-radius: .45rem; color: var(--ink); background: var(--white); font: inherit; }
.dashboard-page-list li { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; gap: .55rem .85rem; }
.dashboard-page-label { min-width: 0; overflow-wrap: anywhere; }
.dashboard-page-state { padding: .15rem .48rem; border-radius: .35rem; background: var(--paper); color: var(--muted); font-size: .78rem; white-space: nowrap; }
.dashboard-page-state[data-published="true"] { background: #e9f6ef; color: #1b6744; }
.dashboard-page-actions { display: flex; align-items: center; gap: .55rem; white-space: nowrap; }
.dashboard-page-actions > a { font-size: .84rem; }
.dashboard-page-actions > .button { min-height: 2.25rem; padding: .28rem .55rem; }
.dashboard-secondary .admin-list li { gap: .35rem .65rem; }
.dashboard-secondary .admin-list .button { min-height: 2.15rem; padding: .25rem .5rem; font-size: .82rem; }
.dashboard-settings h2 { margin-bottom: .55rem; }
.dashboard-setting-buttons { display: flex; flex-wrap: wrap; gap: .45rem; list-style: none; padding: 0; margin: 0; }
.dashboard-setting-buttons .button { min-height: 2.45rem; padding: .3rem .6rem; font-size: .85rem; }
@media (max-width: 51rem) {
.dashboard-grid { grid-template-columns: 1fr; gap: 0; }
.admin-bar .admin-primary { order: 3; width: 100%; gap: .15rem .35rem; }
}
@media (max-width: 28rem) {
.dashboard-page-list li { grid-template-columns: minmax(0, 1fr) auto; }
.dashboard-page-actions { grid-column: 1 / -1; }
}
.studio-page-meta { display: flex; flex-wrap: wrap; align-items: center; gap: .65rem; }
.studio-page-meta code { color: var(--muted); font-size: .86rem; }
.studio-anchor-create, .studio-hero-settings { padding: .55rem .65rem; border: 1px solid var(--line); border-radius: .45rem; }
.studio-anchor-create { margin-top: .55rem; font-size: .84rem; }
.studio-anchor-create summary, .studio-hero-settings summary { cursor: pointer; font-weight: 630; }
.studio-anchor-create[open] form, .studio-hero-controls { margin-top: .6rem; }
.studio-hero-controls { display: flex; flex-wrap: wrap; gap: .42rem; }
.studio-hero-controls .button { min-height: 2.35rem; padding: .3rem .62rem; font-size: .85rem; }
.studio-canvas-status:empty { display: none; }
.canvas-module-settings { max-width: min(92vw, 40rem); }
@media (pointer: coarse) {
.studio-element-tools button { width: 2.5rem; height: 2.5rem; }
}
.canvas-module-settings .category-checks { max-height: min(15rem, 27dvh); overflow-y: auto; }
.canvas-module-settings .actions { position: sticky; bottom: 0; padding-block: .35rem; margin: 0; background: var(--white); }
+19
View File
@@ -1,6 +1,25 @@
'use strict'; 'use strict';
jQuery(function ($) { jQuery(function ($) {
$('[data-page-list]').each(function () {
const $panel = $(this);
const $search = $panel.find('[data-page-search]');
const $status = $panel.find('[data-page-status]');
const $pages = $panel.find('[data-page-item]');
$panel.find('[data-page-filters]').prop('hidden', false);
$search.add($status).on('input change', function () {
const query = $search.val().trim().toLowerCase();
const status = $status.val();
let count = 0;
$pages.each(function () {
const visible = (!status || this.dataset.pageItem === status) && this.dataset.pageLabel.toLowerCase().includes(query);
$(this).prop('hidden', !visible);
if (visible) count++;
});
$panel.find('[data-page-empty]').prop('hidden', count !== 0);
});
});
const formats = { const formats = {
markdown: { markdown: {
heading: ['## ', '', '小标题'], heading: ['## ', '', '小标题'],
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+107 -18
View File
@@ -152,15 +152,14 @@ address { font-style: normal; }
.breadcrumbs a:hover { color: var(--accent); text-decoration: underline; } .breadcrumbs a:hover { color: var(--accent); text-decoration: underline; }
.crumb-divider { color: #74859d; } .crumb-divider { color: #74859d; }
.hero-directory { .hero-directory {
display: grid; display: flex;
grid-template-columns: minmax(0, .9fr) repeat(4, minmax(0, 1fr));
border: 1px solid var(--line); border: 1px solid var(--line);
border-radius: .85rem .85rem 0 0; border-radius: .85rem .85rem 0 0;
background: #ffffffb8; background: #ffffffb8;
min-height: 7rem; min-height: 7rem;
border-bottom: 0; border-bottom: 0;
} }
.hero-directory > * { display: flex; flex-direction: column; justify-content: center; gap: .12rem; padding: .75rem clamp(.6rem, 2vw, 1.85rem); } .hero-directory > * { flex: 1 1 0; min-width: 0; display: flex; flex-direction: column; justify-content: center; gap: .12rem; padding: .75rem clamp(.6rem, 2vw, 1.85rem); overflow-wrap: anywhere; }
.hero-directory a { color: var(--ink); text-decoration: none; border-inline-start: 1px solid var(--line); transition: background-color 160ms ease, color 160ms ease; } .hero-directory a { color: var(--ink); text-decoration: none; border-inline-start: 1px solid var(--line); transition: background-color 160ms ease, color 160ms ease; }
.hero-directory a:hover { color: var(--accent); background: #fff; } .hero-directory a:hover { color: var(--accent); background: #fff; }
.hero-directory a span { font-size: 1.12rem; font-weight: 670; } .hero-directory a span { font-size: 1.12rem; font-weight: 670; }
@@ -282,7 +281,9 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
.network-group + .network-group { margin-top: 2.2rem; } .network-group + .network-group { margin-top: 2.2rem; }
.network-group h3 { margin-bottom: .8rem; } .network-group h3 { margin-bottom: .8rem; }
.network-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 11rem), 1fr)); gap: .7rem; } .network-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 11rem), 1fr)); gap: .7rem; }
.network-list li > * { display: flex; align-items: center; gap: .75rem; min-height: 4rem; height: 100%; border-radius: .65rem; background: var(--white); border: 1px solid var(--line); color: var(--ink); text-decoration: none; padding: .75rem; transition: transform 160ms ease, border-color 160ms ease; } .network-list li { display: flex; flex-direction: column; gap: .35rem; }
.network-list li > * { display: flex; align-items: center; gap: .75rem; min-height: 4rem; border-radius: .65rem; background: var(--white); border: 1px solid var(--line); color: var(--ink); text-decoration: none; padding: .75rem; transition: transform 160ms ease, border-color 160ms ease; }
.network-list li > :first-child { flex: 1; }
.network-list a:hover { transform: translateY(-2px); border-color: var(--accent); color: var(--accent); } .network-list a:hover { transform: translateY(-2px); border-color: var(--accent); color: var(--accent); }
.network-list img { max-width: 3rem; max-height: 1.8rem; object-fit: contain; object-position: left; } .network-list img { max-width: 3rem; max-height: 1.8rem; object-fit: contain; object-position: left; }
.network-list img[src$="oneprovider_invert.svg"] { background: #29354a; border-radius: .25rem; padding: .21rem; } .network-list img[src$="oneprovider_invert.svg"] { background: #29354a; border-radius: .25rem; padding: .21rem; }
@@ -301,18 +302,22 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
.pagination { display: flex; align-items: center; gap: 1rem; margin-top: 1.5rem; } .pagination { display: flex; align-items: center; gap: 1rem; margin-top: 1.5rem; }
.empty-state { background: var(--paper); padding: 1rem; border-radius: .6rem; } .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); } .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, 1.4fr) repeat(2, minmax(0, .75fr)); gap: 1.5rem 3rem; } .footer-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 1.6rem clamp(2rem, 7vw, 7rem); }
.footer-grid > div { display: flex; flex-direction: column; align-items: flex-start; } .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, .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: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-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 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-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-meta p { margin: 0; }
.footer-terms { flex-basis: 100%; }
@media (max-width: 62rem) { @media (max-width: 62rem) {
.masthead-inner { gap: .85rem; } .masthead-inner { gap: .85rem; }
@@ -344,10 +349,11 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
.hero-lead { margin-bottom: 1.3rem; } .hero-lead { margin-bottom: 1.3rem; }
.hero-illustration { border-radius: 1.15rem; } .hero-illustration { border-radius: 1.15rem; }
.hero-illustration img { border-radius: .8rem; } .hero-illustration img { border-radius: .8rem; }
.hero-directory { grid-template-columns: repeat(2, minmax(0, 1fr)); margin-top: .2rem; } .hero-directory { flex-wrap: wrap; margin-top: .2rem; }
.hero-directory > .overline { grid-column: 1 / -1; } .hero-directory > * { flex-basis: 50%; }
.hero-directory > .directory-label { flex-basis: 100%; border-top: 0; }
.hero-directory a { border-top: 1px solid var(--line); min-height: 4rem; padding-inline: .8rem; } .hero-directory a { border-top: 1px solid var(--line); min-height: 4rem; padding-inline: .8rem; }
.hero-directory a:nth-child(even) { border-inline-start: 0; } .hero-directory > a:nth-child(odd of :not(.directory-label)) { border-inline-start: 0; }
.section-nav-inner { column-gap: 1.1rem; } .section-nav-inner { column-gap: 1.1rem; }
.section-nav a { font-size: .875rem; } .section-nav a { font-size: .875rem; }
.project, .project:nth-child(even) { grid-template-columns: 1fr; gap: 1rem; } .project, .project:nth-child(even) { grid-template-columns: 1fr; gap: 1rem; }
@@ -358,8 +364,9 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
.article-category { grid-column: 1; grid-row: 1; } .article-category { grid-column: 1; grid-row: 1; }
.article-row-title { grid-column: 1 / -1; grid-row: 2; } .article-row-title { grid-column: 1 / -1; grid-row: 2; }
.article-row time { grid-column: 2; grid-row: 1; } .article-row time { grid-column: 2; grid-row: 1; }
.footer-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); column-gap: 1rem; } .footer-grid { grid-template-columns: 1fr; }
.footer-company { grid-column: 1 / -1; } .footer-company { align-items: center; text-align: center; }
.footer-links, .footer-meta { text-align: center; }
} }
@media (max-width: 23rem) { @media (max-width: 23rem) {
.hero-actions .button { width: 100%; } .hero-actions .button { width: 100%; }
@@ -377,13 +384,12 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
.catalog-hero { background: var(--paper); padding-block: clamp(3rem, 6vw, 6rem); } .catalog-hero { background: var(--paper); padding-block: clamp(3rem, 6vw, 6rem); }
.catalog-hero h1 { margin-bottom: .85rem; } .catalog-hero h1 { margin-bottom: .85rem; }
.catalog-hero p { margin: 0; font-size: 1.15rem; } .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-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-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 { 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-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 { 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 h3 { font-size: clamp(1.45rem, 3vw, 2.6rem); margin-bottom: .7rem; }
.catalog-content .overline { margin-bottom: .4rem; } .catalog-content .overline { margin-bottom: .4rem; }
.catalog-content .actions { margin-top: auto; padding-top: 1rem; } .catalog-content .actions { margin-top: auto; padding-top: 1rem; }
@@ -467,7 +473,6 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
} }
@media (max-width: 44rem) { @media (max-width: 44rem) {
.catalog-grid, .copyright-service #materials .feature-grid { grid-template-columns: 1fr; } .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 > .wrap { padding: 1.55rem; min-height: 0; }
.copyright-service #go .contact-panel { display: flex; gap: 1rem; } .copyright-service #go .contact-panel { display: flex; gap: 1rem; }
.copyright-service #go .contact-panel img { position: static; transform: none; width: 7rem; } .copyright-service #go .contact-panel img { position: static; transform: none; width: 7rem; }
@@ -647,3 +652,87 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
.article-tabs button { padding: .38rem .8rem; background: white; border: 1px solid var(--line); border-radius: .45rem; color: inherit; cursor: pointer; } .article-tabs button { 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); } .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; } .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); }
.studio-lead { font-size: 1.2rem; color: var(--ink); }
.studio-definitions { margin: 0; }
.studio-definitions dt { font-weight: 650; }
.studio-definitions dd { margin: .2rem 0 .8rem; color: var(--muted); }
.studio-definitions dd:last-child { margin-bottom: 0; }
.studio-spacer { height: clamp(1.5rem, 4vw, 4rem); }
[data-studio-editing] .studio-spacer { border: 1px dashed var(--line); }
.studio-banner-two, .studio-contact { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 1.25rem 2rem; }
.studio-banner-two p, .studio-contact p { margin-bottom: 0; }
.studio-banner-two .actions { margin: 0; }
.studio-contact { border: 1px solid var(--line); border-radius: var(--radius); padding: clamp(1rem, 4vw, 2rem); }
.studio-releases article { padding: 1.05rem 0; border-block-start: 1px solid var(--line); }
.studio-releases article:last-child { border-block-end: 1px solid var(--line); }
.studio-pricing { grid-template-columns: repeat(2, minmax(0, 1fr)); }
@media (max-width: 36rem) { .studio-pricing { grid-template-columns: 1fr; } }
.hero-directory-slot > [data-studio-part="body"] { min-height: 2.2rem; }
[data-studio-editing] [data-studio-dynamic] { cursor: pointer; }
[data-studio-editing] [data-studio-dynamic]:focus-visible { outline: 1px solid var(--accent); }
.studio-module-note { margin: 1rem 0 0; color: var(--accent-deep); padding: .6rem .8rem; background: var(--accent-light); border-radius: .4rem; }
.studio-badge { display: inline-flex; padding: .13rem .63rem; border-radius: 999px; background: var(--accent-light); color: var(--accent-deep); font-size: .85rem; }
.studio-progress progress { width: min(100%, 28rem); accent-color: var(--accent); display: block; }
.studio-progress p { margin-bottom: .3rem; }
.studio-empty { text-align: center; border: 1px dashed var(--line); border-radius: .6rem; padding: clamp(1.25rem, 4vw, 2.7rem); }
.studio-success-note { border-inline-start-color: #257b50; background: #e7f6ed; }
.rich .hero-directory { border-bottom: 1px solid var(--line); border-radius: .85rem; }
.hero:is(.hero-services, .hero-articles, .hero-contact) .hero-text-only { min-height: auto; }
+376 -80
View File
@@ -182,44 +182,82 @@ jQuery(function ($) {
$('[data-canvas-presets]').each(function () { $('[data-canvas-presets]').each(function () {
const $gallery = $(this); const $gallery = $(this);
const $search = $gallery.find('[data-template-search]'); const $tabs = $gallery.find('[data-library-tab]');
const $groups = $gallery.find('[data-template-group]'); const $panels = $gallery.find('[data-library-panel]');
const $filters = $gallery.find('[data-template-filter]');
const $peek = $gallery.find('[data-template-peek]'); const $peek = $gallery.find('[data-template-peek]');
const $dialog = $gallery.find('[data-template-dialog]'); const $dialog = $gallery.find('[data-template-dialog]');
const $use = $dialog.find('[data-template-use]'); const $use = $dialog.find('[data-template-use]');
let category = '';
let $selection; let $selection;
function hidePeek() { function hidePeek() {
$peek.prop('hidden', true); $peek.prop('hidden', true);
} }
function filter() { function selectTab(kind, focus = false) {
const query = String($search.val()).trim().toLowerCase(); const $current = $tabs.filter((_, tab) => tab.dataset.libraryTab === kind);
let count = 0; $tabs.attr({'aria-selected': 'false', tabindex: '-1'});
$groups.each(function () { $current.attr({'aria-selected': 'true', tabindex: '0'});
const $group = $(this); $panels.each(function () {
const allowed = !category || this.dataset.templateGroup === category; $(this).prop('hidden', this.dataset.libraryPanel !== kind);
let groupCount = 0; });
$group.find('[data-template-card]').each(function () { $gallery.closest('.studio-library').scrollTop(0);
const visible = allowed && this.dataset.templateSearchText.toLowerCase().includes(query); hidePeek();
if (focus) $current.trigger('focus');
}
function filterItems($panel) {
const query = $panel.find('[data-template-search]').val().trim().toLowerCase();
let matches = 0;
$panel.find('[data-template-group]').filter((_, group) => !group.hidden).find('[data-library-item]').each(function () {
const visible = this.dataset.templateSearchText.toLowerCase().includes(query);
$(this).prop('hidden', !visible); $(this).prop('hidden', !visible);
if (visible) groupCount++; if (visible) matches++;
}); });
$group.prop('hidden', groupCount === 0); $panel.find('[data-template-empty]').prop('hidden', matches !== 0);
count += groupCount;
});
$gallery.find('[data-template-empty]').prop('hidden', count !== 0);
hidePeek(); hidePeek();
} }
$search.on('input', filter); $gallery.find('[data-library-tabs]').prop('hidden', false);
$filters.on('click', function () { function openLayersFromHash() {
category = this.dataset.templateFilter; if (window.location.hash !== '#blocks') return false;
$filters.attr('aria-pressed', 'false'); selectTab('layers');
$(this).attr('aria-pressed', 'true'); $gallery.find('#blocks').prop('open', true);
filter(); return true;
}
if (!openLayersFromHash()) selectTab('modules');
$(window).on('hashchange', openLayersFromHash);
$tabs.on('click', function () {
selectTab(this.dataset.libraryTab);
}).on('keydown', function (event) {
const index = $tabs.index(this);
const last = $tabs.length - 1;
const next = {Home: 0, End: last, ArrowLeft: index === 0 ? last : index - 1, ArrowRight: index === last ? 0 : index + 1}[event.key];
if (typeof next !== 'number') return;
event.preventDefault();
selectTab($tabs.get(next).dataset.libraryTab, true);
});
$gallery.on('click', '[data-library-category]', function () {
const $panel = $(this).closest('[data-library-panel]');
$panel.data('categoryTrigger', this);
$panel.find('[data-library-index], .studio-anchor-create').prop('hidden', true);
$panel.find('[data-library-content]').prop('hidden', false);
$panel.find('[data-library-title]').text(this.dataset.libraryLabel);
$panel.find('[data-template-search]').val('');
const key = this.dataset.libraryCategory;
$panel.find('[data-template-group]').each(function () {
$(this).prop('hidden', this.dataset.templateGroup !== key);
});
filterItems($panel);
$panel.find('[data-library-back]').trigger('focus');
}).on('click', '[data-library-back]', function () {
const $panel = $(this).closest('[data-library-panel]');
$panel.find('[data-library-content]').prop('hidden', true);
$panel.find('[data-library-index], .studio-anchor-create').prop('hidden', false);
hidePeek();
$($panel.data('categoryTrigger')).trigger('focus');
}).on('input', '[data-template-search]', function () {
filterItems($(this).closest('[data-library-panel]'));
}); });
$gallery.on('mouseenter focusin', '[data-template-preview]', function (event) { $gallery.on('mouseenter focusin', '[data-template-preview]', function (event) {
@@ -265,8 +303,12 @@ jQuery(function ($) {
const $settings = $layout.find('.studio-inspector'); const $settings = $layout.find('.studio-inspector');
const $sizing = $studio.find('[data-media-sizing]'); const $sizing = $studio.find('[data-media-sizing]');
const $elementTools = $studio.find('[data-element-tools]'); const $elementTools = $studio.find('[data-element-tools]');
const $alignTools = $elementTools.find('[data-element-align]');
const alignments = ['left', 'center', 'right'];
const alignmentClasses = alignments.map((value) => 'studio-align-' + value);
const heroOrOptional = '[data-studio-field="accent"], [data-studio-field="lead"], [data-studio-part="lead"], [data-studio-action], [data-studio-nav-index]'; const heroOrOptional = '[data-studio-field="accent"], [data-studio-field="lead"], [data-studio-part="lead"], [data-studio-action], [data-studio-nav-index]';
const bodyElements = 'a, article, blockquote, details, div, dl, dt, dd, figure, h1, h2, h3, h4, h5, h6, hr, li, ol, p, pre, table, ul'; const canvasFields = heroOrOptional + ', [data-studio-field="heading"], [data-studio-part="title"]';
const bodyElements = 'a, article, blockquote, details, div, dl, dt, dd, figure, h1, h2, h3, h4, h5, h6, hr, li, ol, p, pre, progress, table, ul';
const mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video'; const mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video';
const $handle = $studio.find('[data-media-handle]'); const $handle = $studio.find('[data-media-handle]');
const $mediaSize = $sizing.find('[data-media-size]'); const $mediaSize = $sizing.find('[data-media-size]');
@@ -313,6 +355,11 @@ jQuery(function ($) {
const $properties = $studio.find('[data-canvas-properties]'); const $properties = $studio.find('[data-canvas-properties]');
const $propertyForm = $properties.find('form'); const $propertyForm = $properties.find('form');
const $propertyError = $properties.find('[data-property-error]'); const $propertyError = $properties.find('[data-property-error]');
const $moduleDialog = $studio.find('[data-module-dialog]');
const $moduleForm = $moduleDialog.find('form');
const moduleInput = (name) => $moduleForm.find('[name="' + name + '"]');
let editedModule;
let deletedModules = [];
const propertyInput = (name) => $propertyForm.find('[name="' + name + '"]'); const propertyInput = (name) => $propertyForm.find('[name="' + name + '"]');
const pageInput = (name) => $settings.find('[name="' + name + '"]'); const pageInput = (name) => $settings.find('[name="' + name + '"]');
const settingsSnapshot = () => $settings.serializeArray() const settingsSnapshot = () => $settings.serializeArray()
@@ -326,9 +373,16 @@ jQuery(function ($) {
let saveComplete = false; let saveComplete = false;
function sectionChanges(withEdits = true) { function sectionChanges(withEdits = true) {
return sections.flatMap(({key, version, fields, source, template}) => { const edits = sections.flatMap(({key, version, fields, source, template, copyOf, feed, initialFeed}) => {
const changes = {}; const changes = {};
for (const [field, {node, initial}] of Object.entries(fields)) { const aligned = {};
let alignmentChanged = false;
for (const [field, {node, initial, initialAlignment}] of Object.entries(fields)) {
if (field !== 'body') {
const value = getAlignment(node);
if (value) aligned[field] = value;
if (value !== initialAlignment) alignmentChanged = true;
}
let value = field === 'body' ? node.innerHTML : node.textContent; let value = field === 'body' ? node.innerHTML : node.textContent;
if (field === 'body' && node.contains(selectedElement)) { if (field === 'body' && node.contains(selectedElement)) {
const copy = node.cloneNode(true); const copy = node.cloneNode(true);
@@ -339,8 +393,16 @@ jQuery(function ($) {
changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value; changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value;
} }
} }
return Object.keys(changes).length ? [{key, version, fields: changes, ...(template ? {template} : {})}] : []; const feedChanged = feed && (version === null || JSON.stringify(feed) !== initialFeed);
if (!Object.keys(changes).length && !alignmentChanged && !feedChanged) return [];
const edit = {key, version, fields: changes};
if (alignmentChanged || (version === null && Object.keys(aligned).length)) edit.alignments = aligned;
if (template) edit.template = template;
if (copyOf) edit.copyOf = copyOf;
if (feedChanged) edit.feed = feed;
return [edit];
}); });
return [...edits, ...deletedModules];
} }
$settings.on('studio:sync', () => pageInput('canvas_sections').val(JSON.stringify(sectionChanges()))); $settings.on('studio:sync', () => pageInput('canvas_sections').val(JSON.stringify(sectionChanges())));
@@ -359,7 +421,7 @@ jQuery(function ($) {
function openProperties(heading, values, apply, mime = null, allowEmptyUrl = false) { function openProperties(heading, values, apply, mime = null, allowEmptyUrl = false) {
$properties.find('[data-property-heading]').text(heading); $properties.find('[data-property-heading]').text(heading);
$propertyError.prop('hidden', true); $propertyError.prop('hidden', true);
for (const key of ['label', 'url', 'alt', 'poster', 'quicklinks']) { for (const key of ['label', 'note', 'url', 'alt', 'poster', 'quicklinks', 'value', 'max']) {
const visible = Object.hasOwn(values, key); const visible = Object.hasOwn(values, key);
$propertyForm.find('[data-property-row="' + key + '"]').prop('hidden', !visible); $propertyForm.find('[data-property-row="' + key + '"]').prop('hidden', !visible);
propertyInput(key).val(visible ? values[key] : ''); propertyInput(key).val(visible ? values[key] : '');
@@ -571,16 +633,40 @@ jQuery(function ($) {
function editResource(node) { function editResource(node) {
const tag = node.localName; const tag = node.localName;
if (tag === 'progress') {
openProperties('进度条', {value: node.getAttribute('value') || '0', max: node.getAttribute('max') || '100'}, ({value, max}) => {
if (!/^\d+$/.test(value) || !/^\d+$/.test(max) || Number(max) < 1 || Number(value) > Number(max)) {
$propertyError.prop('hidden', false).text('请输入不超过最大值的非负整数。');
return false;
}
node.max = Number(max);
node.value = Number(value);
node.textContent = Math.round(100 * node.value / node.max) + '%';
});
return;
}
if (tag === 'a') { if (tag === 'a') {
const product = node.parentElement.matches('.hero-directory');
const title = product ? node.querySelector(':scope > span') : null;
const note = product ? node.querySelector(':scope > small') : null;
const onlyChild = node.firstElementChild; const onlyChild = node.firstElementChild;
const text = node.childElementCount === 0 ? node : ( const text = title || (node.childElementCount === 0 ? node : (
node.childElementCount === 1 && onlyChild.matches('span, strong, b, em, i, small') node.childElementCount === 1 && onlyChild.matches('span, strong, b, em, i, small')
&& !onlyChild.childElementCount && node.textContent.trim() === onlyChild.textContent.trim() ? onlyChild : null && !onlyChild.childElementCount && node.textContent.trim() === onlyChild.textContent.trim() ? onlyChild : null
); ));
const values = text ? {label: text.textContent, url: node.getAttribute('href') || ''} : {url: node.getAttribute('href') || ''}; const values = text ? {label: text.textContent, url: node.getAttribute('href') || ''} : {url: node.getAttribute('href') || ''};
openProperties('正文链接', values, ({label, url}) => { if (title) values.note = note?.textContent || '';
openProperties(product ? '导航卡片' : '正文链接', values, ({label, note: description, url}) => {
if (text && !label) {
$propertyError.prop('hidden', false).text('请填写链接文案。');
return false;
}
node.setAttribute('href', url); node.setAttribute('href', url);
if (text && label !== values.label) text.textContent = label; if (text && label !== values.label) text.textContent = label;
if (description !== undefined) {
if (note) $(note).text(description);
else if (description) $('<small>').text(description).appendTo(node);
}
}); });
return; return;
} }
@@ -603,25 +689,28 @@ jQuery(function ($) {
}, (tag === 'img' ? 'image' : tag) + '/'); }, (tag === 'img' ? 'image' : tag) + '/');
} }
function registerSection(section, version = Number(section.dataset.studioSection)) { function registerSection(section, version = Number(section.dataset.studioSection), metadata = {}) {
const fields = {}; const fields = {};
const feed = section.dataset.studioFeed ? JSON.parse(section.dataset.studioFeed) : null;
for (const node of section.querySelectorAll('[data-studio-part]')) { for (const node of section.querySelectorAll('[data-studio-part]')) {
const part = node.dataset.studioPart; const part = node.dataset.studioPart;
const body = part === 'body'; const body = part === 'body';
const label = {title: '区块标题', lead: '添加区块简介', body: '区块正文'}[part]; const label = {title: '区块标题', lead: '添加区块简介', body: '区块正文'}[part];
if (body) { if (!feed && body) {
node.contentEditable = 'true'; node.contentEditable = 'true';
node.setAttribute('aria-label', label); node.setAttribute('aria-label', label);
node.dataset.studioPlaceholder = label; node.dataset.studioPlaceholder = label;
} else { } else if (!feed && !node.hidden) {
configureText(node, label, part === 'lead'); configureText(node, label, part === 'lead');
} }
fields[part] = {node, initial: body ? node.innerHTML : node.textContent}; fields[part] = {node, initial: body ? node.innerHTML : node.textContent, initialAlignment: body ? '' : getAlignment(node)};
} }
const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from( const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from(
atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0) atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0)
)); ));
sections.push({key: section.id, version, fields, source, template: section.dataset.studioTemplate}); const entry = {node: section, key: section.id, version, fields, source, feed, initialFeed: JSON.stringify(feed), ...metadata};
sections.push(entry);
return entry;
} }
function setMediaWidth(node, width) { function setMediaWidth(node, width) {
@@ -662,11 +751,12 @@ jQuery(function ($) {
const node = sizingTarget(); const node = sizingTarget();
if (node) { if (node) {
const bounds = previewBounds(node); const bounds = previewBounds(node);
const x = getAlignment(node) === 'right' ? bounds.left : bounds.right;
const y = (bounds.top + bounds.bottom) / 2; const y = (bounds.top + bounds.bottom) / 2;
const visible = bounds.width > 0 && y >= 0 && y <= container.clientHeight const visible = bounds.width > 0 && y >= 0 && y <= container.clientHeight
&& bounds.right > 0 && bounds.right <= container.clientWidth + 1; && x >= 0 && x <= container.clientWidth + 1;
$handle.prop('hidden', !mediaDrag && !visible); $handle.prop('hidden', !mediaDrag && !visible);
$handle.css({left: Math.min(bounds.right, container.clientWidth - 11), top: y}); $handle.css({left: Math.max(11, Math.min(x, container.clientWidth - 11)), top: y});
} else { } else {
$handle.prop('hidden', true); $handle.prop('hidden', true);
} }
@@ -706,10 +796,30 @@ jQuery(function ($) {
return element !== body && body.contains(element) ? element : null; return element !== body && body.contains(element) ? element : null;
} }
function getAlignment(node) {
return alignments.find((value) => node.classList.contains('studio-align-' + value)) || '';
}
function alignmentTarget(node) {
if (!node) return null;
const hero = node.closest('[data-studio-align-field]');
if (hero) return hero;
return node.matches('[data-studio-part="title"], [data-studio-part="lead"]') || node.closest('[data-studio-part="body"]')
? node : null;
}
function syncAlignmentButtons(target) {
$alignTools.prop('hidden', !target).find('[data-align]').each(function () {
$(this).attr('aria-pressed', String(Boolean(target) && getAlignment(target) === this.dataset.align));
});
}
function selectElement(node) { function selectElement(node) {
selectionObserver?.disconnect(); selectionObserver?.disconnect();
selectedElement?.removeAttribute('data-studio-selected'); selectedElement?.removeAttribute('data-studio-selected');
selectedElement = node; selectedElement = node;
const dynamic = node?.hasAttribute('data-studio-dynamic');
$elementTools.toggleClass('is-module', Boolean(dynamic)).find('[data-element-module-settings]').prop('hidden', !dynamic);
selectedMedia = node?.matches(mediaTargets) ? node : null; selectedMedia = node?.matches(mediaTargets) ? node : null;
$sizing.prop('hidden', !selectedMedia); $sizing.prop('hidden', !selectedMedia);
if (node) { if (node) {
@@ -717,12 +827,15 @@ jQuery(function ($) {
const target = sizingTarget(); const target = sizingTarget();
const nav = node.hasAttribute('data-studio-nav-index'); const nav = node.hasAttribute('data-studio-nav-index');
const inBody = node.closest('[data-studio-part="body"]') !== null; const inBody = node.closest('[data-studio-part="body"]') !== null;
const canCopy = inBody || (nav && $(node).siblings().length < 19); const canCopy = dynamic || inBody || (nav && $(node).siblings().length < 19);
const hasProperties = selectedMedia || node.matches('a'); const hasProperties = !dynamic && (selectedMedia || node.matches('a, progress'));
const aligned = dynamic ? null : alignmentTarget(node);
syncAlignmentButtons(aligned);
$elementTools.find('[data-element-copy]').prop('hidden', !canCopy); $elementTools.find('[data-element-copy]').prop('hidden', !canCopy);
$elementTools.find('[data-element-delete]').prop('hidden', !dynamic && !inBody && !selectedMedia && !node.matches(heroOrOptional));
$elementTools.find('[data-element-properties]').prop('hidden', !hasProperties); $elementTools.find('[data-element-properties]').prop('hidden', !hasProperties);
if (target) showMediaWidth(currentMediaWidth(target)); if (target) showMediaWidth(currentMediaWidth(target));
selectionObserver?.observe(target || node); selectionObserver?.observe(target || aligned || node);
} }
positionSelection(); positionSelection();
} }
@@ -730,6 +843,10 @@ jQuery(function ($) {
function changeElement(copy) { function changeElement(copy) {
const node = selectedElement; const node = selectedElement;
if (!node?.isConnected) return; if (!node?.isConnected) return;
if (node.hasAttribute('data-studio-dynamic')) {
changeModule(sections.find((section) => section.node === node), copy);
return;
}
const {studioField, studioAction, studioNavIndex} = node.dataset; const {studioField, studioAction, studioNavIndex} = node.dataset;
const inBody = node.closest('[data-studio-part="body"]') !== null; const inBody = node.closest('[data-studio-part="body"]') !== null;
selectElement(null); selectElement(null);
@@ -760,19 +877,140 @@ jQuery(function ($) {
} }
} }
$elementTools.on('click', '[data-element-copy]', () => changeElement(true)) $elementTools.on('click', '[data-align]', function () {
const target = alignmentTarget(selectedElement);
const alignment = this.dataset.align;
if (!target || !alignments.includes(alignment)) return;
target.classList.remove(...alignmentClasses);
target.classList.add('studio-align-' + alignment);
const field = target.dataset.studioAlignField;
if (field) {
const $value = pageInput('alignments');
const values = {...JSON.parse($value.val())};
values[field] = alignment;
$value.val(JSON.stringify(values));
}
syncAlignmentButtons(target);
positionSelection();
}).on('click', '[data-element-copy]', () => changeElement(true))
.on('click', '[data-element-delete]', () => changeElement(false)) .on('click', '[data-element-delete]', () => changeElement(false))
.on('click', '[data-element-properties]', () => { .on('click', '[data-element-properties]', () => {
if (selectedMedia) replaceMedia(); if (selectedMedia) replaceMedia();
else if (selectedElement?.matches('[data-studio-action], [data-studio-nav-index]')) { else if (selectedElement?.matches('[data-studio-action], [data-studio-nav-index]')) {
$(selectedElement).triggerHandler('studio:properties'); $(selectedElement).triggerHandler('studio:properties');
} else if (selectedElement?.matches('a')) { } else if (selectedElement?.matches('a, progress')) {
editResource(selectedElement); editResource(selectedElement);
} }
}).on('keydown', (event) => { }).on('keydown', (event) => {
if (event.key === 'Escape') selectElement(null); if (event.key === 'Escape') selectElement(null);
}); });
function noteModule(section, text) {
const $body = $(section).find('[data-studio-part="body"]');
let $note = $(section).find('[data-studio-module-note]');
if (!$note.length) $note = $('<p>', {class: 'studio-module-note', 'data-studio-module-note': ''}).insertBefore($body);
$note.text(text);
}
$elementTools.on('click', '[data-element-module-settings]', () => {
editedModule = sections.find(({node}) => node === selectedElement);
if (!editedModule?.feed) return;
const {fields, feed} = editedModule;
moduleInput('module_title').val(fields.title.node.textContent);
moduleInput('module_lead').val(fields.lead.node.textContent);
moduleInput('feed_mode').val(feed.mode);
moduleInput('feed_limit').val(feed.limit);
moduleInput('feed_categories[]').each(function () {
this.checked = feed.categories.includes(this.value);
});
$moduleDialog.find('[data-module-error]').prop('hidden', true);
$moduleDialog.get(0).showModal();
});
$moduleDialog.on('click', '[data-module-close]', () => $moduleDialog.get(0).close());
$moduleForm.on('submit', (event) => {
event.preventDefault();
const categories = moduleInput('feed_categories[]').filter(':checked').map((_, node) => node.value).get();
const title = moduleInput('module_title').val().trim();
if (!title || !categories.length) {
$moduleDialog.find('[data-module-error]').text('请填写标题并至少选择一个分类。').prop('hidden', false);
return;
}
const {node, fields} = editedModule;
editedModule.feed = {mode: moduleInput('feed_mode').val(), categories, limit: Number(moduleInput('feed_limit').val())};
fields.title.node.textContent = title;
fields.lead.node.textContent = moduleInput('module_lead').val().trim();
noteModule(node, '模块设置将在保存页面后更新。');
$moduleDialog.get(0).close();
positionSelection();
});
function newSectionId() {
return 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('');
}
function addPending(section) {
const $button = $('<button>', {type: 'button', text: '取消新增:' + section.fields.title.node.textContent});
section.$pending = $('<li>').append($button).appendTo($pending);
$pending.prop('hidden', false);
$button.on('click', () => removeSection(section));
}
function removeSection(section) {
if (section.node.contains(activeBody)) selectBody(null);
if (section.node.contains(selectedElement)) selectElement(null);
if (section.version !== null) deletedModules.push({key: section.key, version: section.version, delete: true});
section.node.remove();
sections = sections.filter((entry) => entry !== section);
section.$pending?.remove();
$pending.prop('hidden', !$pending.children().length);
}
function scopeTemplateIds(root, prefix, oldKey = '') {
const ids = new Map();
$(root).find('[id]').addBack('[id]').each(function () {
const next = oldKey && this.id.includes(oldKey) ? this.id.replace(oldKey, prefix) : prefix + '-' + this.id;
ids.set(this.id, next);
this.id = next;
});
$(root).find('[aria-labelledby], [aria-controls], [href^="#"]').addBack('[aria-labelledby]').each(function () {
for (const attribute of ['aria-labelledby', 'aria-controls', 'href']) {
const value = this.getAttribute(attribute);
if (!value) continue;
if (attribute === 'href') {
const target = ids.get(value.slice(1));
if (value.startsWith('#') && target) this.setAttribute('href', '#' + target);
} else {
this.setAttribute(attribute, value.split(' ').map((part) => ids.get(part) || part).join(' '));
}
}
});
}
function changeModule(section, copy) {
if (!section) return;
if (!copy) {
if (window.confirm('删除此模块?保存页面后生效。')) {
removeSection(section);
$studio.find('[data-canvas-status]').text('模块已移除,保存页面后生效。');
}
return;
}
if (sections.filter(({version}) => version === null).length >= 50) return;
selectElement(null);
const clone = section.node.cloneNode(true);
const id = newSectionId();
scopeTemplateIds(clone, id, section.key);
clone.dataset.studioFeed = JSON.stringify(section.feed);
doc.querySelector('[data-studio-section-end]').before(clone);
const copyOf = section.copyOf || (section.version === null ? null : {key: section.key, version: section.version});
const entry = registerSection(clone, null, {template: copyOf ? null : section.template, copyOf});
addPending(entry);
noteModule(clone, '模块副本将在保存页面后生效。');
clone.scrollIntoView({block: 'start'});
selectElement(clone);
$studio.find('[data-canvas-status]').text('已复制模块,保存页面后生效。');
}
function replaceMedia() { function replaceMedia() {
if (!selectedMedia?.isConnected) return; if (!selectedMedia?.isConnected) return;
if (selectedMedia.hasAttribute('data-studio-hero-image')) heroControls.get('image')(); if (selectedMedia.hasAttribute('data-studio-hero-image')) heroControls.get('image')();
@@ -790,9 +1028,10 @@ jQuery(function ($) {
const narrow = node.getBoundingClientRect(); const narrow = node.getBoundingClientRect();
if (classes === null) node.removeAttribute('class'); if (classes === null) node.removeAttribute('class');
else node.setAttribute('class', classes); else node.setAttribute('class', classes);
const rightEdgeTravel = (full.right - narrow.right) / .9; const fromLeft = getAlignment(node) === 'right';
const available = rightEdgeTravel > full.width * .15 ? rightEdgeTravel : full.width; const edgeTravel = (fromLeft ? narrow.left - full.left : full.right - narrow.right) / .9;
return {available, initialWidth: width || Math.round(100 * natural / (full.width || natural || 1))}; const available = edgeTravel > full.width * .15 ? edgeTravel : full.width;
return {available, fromLeft, initialWidth: width || Math.round(100 * natural / (full.width || natural || 1))};
} }
function resizeMedia(width) { function resizeMedia(width) {
@@ -817,7 +1056,8 @@ jQuery(function ($) {
if (!mediaDrag || mediaDrag.id !== pointer.pointerId || !mediaDrag.available) return; if (!mediaDrag || mediaDrag.id !== pointer.pointerId || !mediaDrag.available) return;
if (pointer.clientX !== mediaDrag.x || mediaDrag.moved) { if (pointer.clientX !== mediaDrag.x || mediaDrag.moved) {
mediaDrag.moved = true; mediaDrag.moved = true;
resizeMedia(mediaDrag.initialWidth + 100 * (pointer.clientX - mediaDrag.x) / (mediaDrag.available * mediaDrag.scale)); const distance = (pointer.clientX - mediaDrag.x) * (mediaDrag.fromLeft ? -1 : 1);
resizeMedia(mediaDrag.initialWidth + 100 * distance / (mediaDrag.available * mediaDrag.scale));
} }
}).on('lostpointercapture', () => { }).on('lostpointercapture', () => {
mediaDrag = null; mediaDrag = null;
@@ -836,23 +1076,62 @@ jQuery(function ($) {
$layout.on('click', '[data-hero-control]', function () { $layout.on('click', '[data-hero-control]', function () {
heroControls.get(this.dataset.heroControl)?.(); heroControls.get(this.dataset.heroControl)?.();
}); });
$presets.on('mousedown', '[data-canvas-template]', (event) => event.preventDefault()); function insertInBody(markup, body, range) {
if (!body.isConnected) return;
const insertion = doc.createRange();
// Insert between blocks so the browser doesn't split a paragraph or duplicate its ID.
let node = range?.endContainer;
if (!node || !body.contains(node)) {
insertion.selectNodeContents(body);
insertion.collapse(false);
} else if (node === body) {
insertion.setStart(body, range.endOffset);
} else {
while (node.parentNode !== body) node = node.parentNode;
insertion.setStartAfter(node);
}
const template = doc.createElement('template');
template.innerHTML = markup;
if (template.content.querySelector('[id]')) scopeTemplateIds(template.content, newSectionId());
editBody(body, insertion, 'insertHTML', template.innerHTML);
}
$presets.on('mousedown', '[data-canvas-template], [data-canvas-element]', (event) => event.preventDefault());
$presets.on('click', '[data-canvas-element]', function () {
const $status = $presets.find('[data-element-status]');
const body = activeBody;
const range = savedRange?.cloneRange();
if (!body) {
$status.text('请先在画布中选中要插入的正文。');
return;
}
const add = (markup) => {
if (!markup) return;
insertInBody(markup, body, range);
selectElement(null);
$status.text('已插入' + $(this).text() + '。');
};
if (this.dataset.elementMime) {
openPicker(this.dataset.elementMime, (file) => add(mediaMarkup(file)));
} else {
add($presets.find('template[data-element="' + this.dataset.canvasElement + '"]').get(0).innerHTML);
}
});
$presets.on('click', '[data-canvas-template]', function () { $presets.on('click', '[data-canvas-template]', function () {
const markup = $presets.find('template[data-preset="' + this.dataset.canvasTemplate + '"]').get(0).innerHTML; const markup = $presets.find('template[data-preset="' + this.dataset.canvasTemplate + '"]').get(0).innerHTML;
const template = this.dataset.canvasTemplate; const template = this.dataset.canvasTemplate;
const feed = this.dataset.templateFeed;
if ($presets.find('[data-template-inline]').prop('checked')) { if ($presets.find('[data-template-inline]').prop('checked')) {
if (template === 'articles') { if (feed) {
$templateStatus.text('分类文章需要作为独立区块添加。'); $templateStatus.text('动态模块需要作为独立区块添加。');
return; return;
} }
if (!activeBody) { if (!activeBody) {
$templateStatus.text('先在画布中选择要插入的区块正文。'); $templateStatus.text('先在画布中选择要插入的区块正文。');
return; return;
} }
// Insert at the saved caret without replacing any selected text. insertInBody(markup, activeBody, savedRange);
const insertion = savedRange?.cloneRange(); selectElement(null);
insertion?.collapse(false);
editBody(activeBody, insertion, 'insertHTML', markup);
$templateStatus.text('已插入当前正文。'); $templateStatus.text('已插入当前正文。');
return; return;
} }
@@ -862,34 +1141,29 @@ jQuery(function ($) {
} }
const end = doc.querySelector('[data-studio-section-end]'); const end = doc.querySelector('[data-studio-section-end]');
const section = end.content.firstElementChild.cloneNode(true); const section = end.content.firstElementChild.cloneNode(true);
const id = 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join(''); const id = newSectionId();
section.id = id; section.id = id;
section.classList.replace('section-plain', 'section-' + this.dataset.templateStyle);
const title = section.querySelector('[data-studio-part="title"]'); const title = section.querySelector('[data-studio-part="title"]');
title.id = 'heading-' + id; title.id = 'heading-' + id;
title.textContent = this.dataset.templateTitle; title.textContent = this.dataset.templateTitle;
section.setAttribute('aria-labelledby', title.id); section.setAttribute('aria-labelledby', title.id);
section.querySelector('[data-studio-part="body"]').innerHTML = markup; section.querySelector('[data-studio-part="lead"]').textContent = this.dataset.templateLead || '';
if (template === 'articles') { const body = section.querySelector('[data-studio-part="body"]');
section.dataset.studioTemplate = template; body.innerHTML = markup;
$('<p>', {class: 'empty-state', text: '保存页面后可在图层的区块设置中选择分类和展示方式。'}) scopeTemplateIds(body, id);
.insertBefore($(section).find('[data-studio-part="body"]')); if (feed) {
section.dataset.studioDynamic = '';
section.dataset.studioFeed = feed;
section.tabIndex = 0;
noteModule(section, '保存页面后将加载动态内容。');
} }
end.before(section); end.before(section);
registerSection(section, null); const entry = registerSection(section, null, {template});
addPending(entry);
section.scrollIntoView({block: 'start'}); section.scrollIntoView({block: 'start'});
section.querySelector('[data-studio-part="body"]').focus({preventScroll: true}); if (feed) selectElement(section);
const $cancel = $('<button>', {type: 'button', text: '取消新增:' + title.textContent}); else entry.fields.body.node.focus({preventScroll: true});
const $item = $('<li>').append($cancel).appendTo($pending);
$pending.prop('hidden', false);
$cancel.on('click', () => {
if (section.contains(activeBody)) selectBody(null);
if (section.contains(selectedElement)) selectElement(null);
section.remove();
sections = sections.filter(({key}) => key !== id);
$item.remove();
$pending.prop('hidden', !$pending.children().length);
$templateStatus.text('已取消新增区块。');
});
$templateStatus.text('已添加 ' + title.textContent + ' 区块。'); $templateStatus.text('已添加 ' + title.textContent + ' 区块。');
}); });
@@ -904,6 +1178,7 @@ jQuery(function ($) {
selectElement(null); selectElement(null);
$pending.empty().prop('hidden', true); $pending.empty().prop('hidden', true);
sections = []; sections = [];
deletedModules = [];
$doc.find('[data-studio-section]').each((_, section) => registerSection(section)); $doc.find('[data-studio-section]').each((_, section) => registerSection(section));
$doc.on('focusin.canvas', '[contenteditable]', function () { $doc.on('focusin.canvas', '[contenteditable]', function () {
@@ -914,22 +1189,42 @@ jQuery(function ($) {
$doc.on('click.canvas dblclick.canvas', mediaTargets, function (event) { $doc.on('click.canvas dblclick.canvas', mediaTargets, function (event) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
const dynamic = this.closest('[data-studio-dynamic]');
if (dynamic) {
selectBody(null);
selectElement(dynamic);
return;
}
selectBody(this.closest('[data-studio-part="body"]')); selectBody(this.closest('[data-studio-part="body"]'));
selectElement(this); selectElement(this);
if (event.type === 'dblclick') replaceMedia(); if (event.type === 'dblclick') replaceMedia();
}); });
$doc.on('click.canvas', (event) => { $doc.on('click.canvas', (event) => {
const node = event.target; const node = event.target;
const optional = node.closest?.(heroOrOptional); const dynamic = node.closest?.('[data-studio-dynamic]');
selectElement(doc.getSelection()?.isCollapsed ? optional || editableBodyElement(node) : null); if (dynamic) {
selectBody(null);
selectElement(dynamic);
return;
}
const field = node.closest?.(canvasFields);
selectElement(doc.getSelection()?.isCollapsed ? field || editableBodyElement(node) : null);
}); });
$doc.on('dblclick.canvas', '[data-studio-part="body"] a', function (event) { $doc.on('dblclick.canvas', '[data-studio-part="body"] a', function (event) {
event.preventDefault(); event.preventDefault();
if (!event.target.closest(mediaTargets)) editResource(this); if (!this.closest('[data-studio-dynamic]') && !event.target.closest(mediaTargets)) editResource(this);
}); });
$doc.on('keydown.canvas', (event) => { $doc.on('keydown.canvas', (event) => {
if (event.key === 'Escape') selectElement(null); if (event.key === 'Escape') selectElement(null);
}); });
$doc.on('keydown.canvas', '[data-studio-dynamic]', function (event) {
if ((event.key === 'Enter' || event.key === ' ') && event.target === this) {
event.preventDefault();
selectBody(null);
selectElement(this);
$elementTools.find('[data-element-module-settings]').trigger('focus');
}
});
$doc.on('keydown.canvas', '[data-studio-hero-image]', function (event) { $doc.on('keydown.canvas', '[data-studio-hero-image]', function (event) {
if (event.key === 'Enter' || event.key === ' ') { if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault(); event.preventDefault();
@@ -950,7 +1245,7 @@ jQuery(function ($) {
}); });
$toolbar.prop('hidden', false); $toolbar.prop('hidden', false);
$layout.find('[data-canvas-jump]').prop('hidden', false); $layout.find('[data-canvas-jump]').prop('hidden', false);
$layout.find('[data-canvas-template], [data-hero-control]').prop('disabled', false); $layout.find('[data-canvas-template], [data-canvas-element], [data-hero-control]').prop('disabled', false);
$presets.triggerHandler('studio:canvas-ready'); $presets.triggerHandler('studio:canvas-ready');
} }
@@ -962,7 +1257,8 @@ jQuery(function ($) {
if (!body) return; if (!body) return;
$studio.get(0).scrollIntoView({block: 'start'}); $studio.get(0).scrollIntoView({block: 'start'});
section.scrollIntoView({block: 'start'}); section.scrollIntoView({block: 'start'});
body.focus({preventScroll: true}); if (section.hasAttribute('data-studio-dynamic')) selectElement(section);
else body.focus({preventScroll: true});
}); });
}); });
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

+7
View File
@@ -13,6 +13,7 @@ CREATE TABLE IF NOT EXISTS pages (
image TEXT NOT NULL, image TEXT NOT NULL,
alt TEXT NOT NULL, alt TEXT NOT NULL,
image_scale INTEGER NOT NULL DEFAULT 0, image_scale INTEGER NOT NULL DEFAULT 0,
alignments TEXT NOT NULL DEFAULT '{}',
actions TEXT NOT NULL, actions TEXT NOT NULL,
quicklinks TEXT NOT NULL, quicklinks TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('draft', 'published')), status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('draft', 'published')),
@@ -26,6 +27,7 @@ CREATE TABLE IF NOT EXISTS sections (
lead TEXT NOT NULL, lead TEXT NOT NULL,
style TEXT NOT NULL DEFAULT 'plain', style TEXT NOT NULL DEFAULT 'plain',
feed TEXT, feed TEXT,
alignments TEXT NOT NULL DEFAULT '{}',
body TEXT NOT NULL, body TEXT NOT NULL,
position INTEGER NOT NULL, position INTEGER NOT NULL,
version INTEGER NOT NULL DEFAULT 0, version INTEGER NOT NULL DEFAULT 0,
@@ -61,6 +63,11 @@ CREATE TABLE IF NOT EXISTS article_redirects (
slug TEXT PRIMARY KEY, slug TEXT PRIMARY KEY,
article_id INTEGER NOT NULL REFERENCES articles(id) ON DELETE CASCADE article_id INTEGER NOT NULL REFERENCES articles(id) ON DELETE CASCADE
); );
CREATE TABLE IF NOT EXISTS article_deletions (
slug TEXT PRIMARY KEY,
article_id INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS article_deletions_id ON article_deletions (article_id);
CREATE TABLE IF NOT EXISTS users ( CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE COLLATE NOCASE, email TEXT NOT NULL UNIQUE COLLATE NOCASE,
+88 -1
View File
@@ -49,7 +49,7 @@
"title": "来笙动态", "title": "来笙动态",
"lead": "", "lead": "",
"style": "plain", "style": "plain",
"body": "<p><a class=\"back-link\" href=\"/articles\">查看全部动态</a></p>", "body": "",
"feed": { "feed": {
"categories": [ "categories": [
"announcement", "announcement",
@@ -428,6 +428,93 @@
"style": "plain" "style": "plain"
} }
] ]
},
{
"slug": "services",
"name": "产品与服务",
"title": "产品与服务 · 来笙 Laysense",
"heading": "产品与服务",
"accent": "",
"description": "自托管建站、开源智能 DNS 与软件著作权代理服务。",
"lead": "自托管建站、开源智能 DNS 与软件著作权代理服务。",
"image": "",
"alt": "",
"actions": [],
"quicklinks": [],
"sections": [
{
"key": "catalog",
"title": "服务目录",
"lead": "",
"body": "",
"style": "plain",
"feed": {
"categories": [
"services"
],
"mode": "catalog",
"limit": 30
}
}
]
},
{
"slug": "articles",
"name": "来笙动态",
"title": "来笙动态 · 来笙 Laysense",
"heading": "来笙动态",
"accent": "",
"description": "查看来笙的公告、新闻和产品动态。",
"lead": "查看来笙的公告、新闻和产品动态。",
"image": "",
"alt": "",
"actions": [],
"quicklinks": [],
"sections": [
{
"key": "updates",
"title": "公告、新闻与产品动态",
"lead": "",
"body": "",
"style": "plain",
"feed": {
"categories": [
"announcement",
"news",
"product"
],
"mode": "tabs",
"limit": 8
}
}
]
},
{
"slug": "contact",
"name": "联系来笙",
"title": "联系来笙 · 来笙 Laysense",
"heading": "联系来笙",
"accent": "",
"description": "联系上海来笙信息科技有限公司,咨询产品、技术支持或合作。",
"lead": "联系上海来笙信息科技有限公司,咨询产品、技术支持或合作。",
"image": "",
"alt": "",
"actions": [
[
"mailto:public@laysense.cn",
"发送邮件"
]
],
"quicklinks": [],
"sections": [
{
"key": "contact-information",
"title": "联系方式",
"lead": "",
"body": "<div class=\"studio-contact\"><div><h3>上海来笙信息科技有限公司</h3><p>上海自贸试验区世博村路231号2单元3层328室</p></div><dl class=\"studio-definitions\"><dt>电子邮件</dt><dd><a href=\"mailto:public@laysense.cn\">public@laysense.cn</a></dd><dt>全球号码</dt><dd><a href=\"tel:+16699004532\">+1 (669) 900 4532</a> / <a href=\"tel:+85257012856\">+852 5701 2856</a></dd></dl></div>",
"style": "plain"
}
]
} }
], ],
"articles": [ "articles": [
+61
View File
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Content\View;
$primary = 'https://example.com/product?a=1&b=2';
$cases = [
'configured-with-detail' => [['card' => ['url' => $primary], 'body' => '<p>有正文</p>'], $primary, true],
'configured-with-extra' => [['card' => ['url' => '/sc', 'extra_url' => '/pagepan#download', 'extra_label' => '下载'], 'summary' => '简介'], '/sc', true],
'configured-only' => [['card' => ['url' => '/pagepan']], '/pagepan', false],
'summary-only' => [['summary' => '仅摘要'], '/articles/summary-only', false],
'editor-placeholder' => [['body' => '<p><br></p><p>&nbsp;&#8203;</p>'], '', false],
'markdown-comment' => [['body' => '<!-- 草稿注释 -->', 'body_format' => 'markdown'], '', false],
'media-body' => [['body' => '<video controls><source src="/assets/demo.mp4"></video>'], '/articles/media-body', false],
'unconfigured' => [[], '', false],
];
$items = [];
foreach ($cases as $slug => [$fields]) {
$items[] = $fields + ['slug' => $slug, 'title' => $slug, 'card' => [], 'summary' => '', 'body' => '', 'body_format' => 'html'];
}
function parseFragment(string $html): DOMXPath
{
$document = new DOMDocument();
$document->loadHTML('<meta charset="utf-8">' . $html, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
return new DOMXPath($document);
}
function equal(mixed $actual, mixed $expected, string $message): void
{
if ($actual !== $expected) {
throw new RuntimeException($message . ' ' . json_encode([$expected, $actual], JSON_UNESCAPED_UNICODE));
}
}
$services = parseFragment(View::fragment('service-cards', ['products' => $items]));
$network = parseFragment(View::fragment('network-groups', [
'network' => ['partners' => ['name' => '合作伙伴', 'articles' => $items]], 'standalone' => true,
]));
foreach ($cases as $slug => [, $target, $detail]) {
$card = "//article[div/h3='$slug']";
equal($services->evaluate("count($card)"), 1.0, "$slug 服务卡片存在");
equal($services->evaluate("string($card/div/h3/a/@href)"), $target, "$slug 服务标题目标");
equal($services->evaluate("string($card/div/div/a[contains(@class, 'button-primary')]/@href)"), $target, "$slug 服务按钮目标");
equal($services->evaluate("boolean($card/div/div/a[@href='/articles/$slug'][not(contains(@class, 'button-primary'))])"), false, "$slug 不追加详情");
if ($slug === 'configured-with-extra') {
equal($services->evaluate("string($card/div/div/a[@href='/pagepan#download'])"), '下载', "$slug 保留附加链接");
equal($services->evaluate("count($card/div/div/a)"), 2.0, "$slug 只有主、附加链接");
}
$item = "//li[*[1]/span='$slug']";
equal($network->evaluate("count($item)"), 1.0, "$slug 伙伴卡片存在");
equal($network->evaluate("string($item/*[1]/@href)"), $target, "$slug 伙伴卡片目标");
equal($network->evaluate("boolean($item/a[@class='network-detail'][@href='/articles/$slug'])"), $detail, "$slug 伙伴独立详情");
}
printf("通过 %d 组目录卡片测试。\n", count($cases));
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
exec "${PHP_BIN:-php}" tests/directory-links.php
+332 -18
View File
@@ -33,7 +33,24 @@ async function run(browser) {
} }
await post('/admin/new-page', {slug, name: '画布测试页'}); await post('/admin/new-page', {slug, name: '画布测试页'});
await page.goto('/admin');
const dashboard = page.locator('[data-page-list]');
const settingsLinks = page.getByRole('region', {name: '站点编辑'}).locator('.dashboard-setting-buttons .button');
assert.deepEqual(await settingsLinks.evaluateAll((links) => links.map((link) => link.getAttribute('href'))), [
'/admin/settings/header', '/admin/settings/footer', '/admin/settings/cdn', '/admin/media',
]);
await dashboard.locator('[data-page-search]').fill(slug);
assert.equal(await dashboard.locator('[data-page-item]:visible').count(), 1);
const draft = dashboard.locator('[data-page-item]:visible');
assert.equal(await draft.getAttribute('data-page-item'), 'draft');
assert.equal(await draft.getByRole('link', {name: '预览'}).getAttribute('href'), '/admin/pages/' + slug + '/preview');
await dashboard.locator('[data-page-status]').selectOption('published');
await dashboard.locator('[data-page-empty]').waitFor({state: 'visible'});
await dashboard.locator('[data-page-status]').selectOption('draft');
assert.equal(await dashboard.locator('[data-page-item]:visible').count(), 1);
assert.equal(await page.getByRole('navigation', {name: '后台导航'}).getByRole('link', {name: '页面'}).getAttribute('aria-current'), 'page');
await post('/admin/page-blocks/' + slug, {operation: 'create', key: 'fixtures', preset: 'text'}); await post('/admin/page-blocks/' + slug, {operation: 'create', key: 'fixtures', preset: 'text'});
await post('/admin/page-blocks/' + slug, {operation: 'create', key: 'fee-sample', preset: 'existing-sc-pricing'});
await post('/admin/pages/' + slug + '/fixtures', { await post('/admin/pages/' + slug + '/fixtures', {
version: '0', title: '媒体和链接', lead: '', style: 'plain', version: '0', title: '媒体和链接', lead: '', style: 'plain',
body: '<p><img src="/assets/favicon.png" alt="示例图片" width="96"></p>' body: '<p><img src="/assets/favicon.png" alt="示例图片" width="96"></p>'
@@ -54,6 +71,8 @@ async function run(browser) {
const frame = page.frameLocator('iframe[title="可编辑页面画布"]'); const frame = page.frameLocator('iframe[title="可编辑页面画布"]');
const sizing = page.locator('[data-media-sizing]'); const sizing = page.locator('[data-media-sizing]');
const properties = page.locator('[data-canvas-properties]'); 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 closeProperties = () => properties.locator('[data-property-close]').click();
const image = frame.locator('#fixtures img'); const image = frame.locator('#fixtures img');
@@ -77,6 +96,18 @@ async function run(browser) {
await properties.locator('[name=url]').fill('/assets/original/home-hero.webp'); await properties.locator('[name=url]').fill('/assets/original/home-hero.webp');
await properties.locator('button[type=submit]').click(); await properties.locator('button[type=submit]').click();
assert.equal(await image.getAttribute('src'), '/assets/original/home-hero.webp'); 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]'); const hero = frame.locator('[data-studio-hero-image]');
await page.locator('iframe[title="可编辑页面画布"]').evaluate((iframe) => iframe.contentWindow.scrollTo(0, 0)); await page.locator('iframe[title="可编辑页面画布"]').evaluate((iframe) => iframe.contentWindow.scrollTo(0, 0));
@@ -88,8 +119,11 @@ async function run(browser) {
await sizing.locator('[data-replace-media]').click(); await sizing.locator('[data-replace-media]').click();
assert.equal(await properties.locator('h2').textContent(), '首屏图片'); assert.equal(await properties.locator('h2').textContent(), '首屏图片');
await closeProperties(); await closeProperties();
const heroTitle = frame.locator('[data-studio-field=heading]');
await heroTitle.click();
await align('居右');
assert.equal(await heroTitle.evaluate((node) => getComputedStyle(node.parentElement).textAlign), 'right');
const tools = page.getByRole('group', {name: '所选元素'});
await frame.locator('#fixtures a').click(); await frame.locator('#fixtures a').click();
await tools.getByRole('button', {name: '属性'}).click(); await tools.getByRole('button', {name: '属性'}).click();
await properties.waitFor({state: 'visible'}); await properties.waitFor({state: 'visible'});
@@ -108,6 +142,11 @@ async function run(browser) {
const copyText = frame.locator('#fixtures').getByText('待复制段落', {exact: true}); const copyText = frame.locator('#fixtures').getByText('待复制段落', {exact: true});
await copyText.click(); 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(); await tools.getByRole('button', {name: '复制'}).click();
assert.equal(await copyText.count(), 2); assert.equal(await copyText.count(), 2);
assert.equal(await frame.locator('#copy-fixture').count(), 1); assert.equal(await frame.locator('#copy-fixture').count(), 1);
@@ -119,17 +158,53 @@ async function run(browser) {
await tools.getByRole('button', {name: '删除'}).click(); await tools.getByRole('button', {name: '删除'}).click();
assert.equal(await page.locator('[name=lead]').inputValue(), ''); 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]'); const gallery = page.locator('[data-canvas-presets]');
assert.equal(await gallery.locator('[data-template-group]').count(), 6); const modules = gallery.locator('[data-library-panel=modules]');
assert.equal(await gallery.locator('[data-template-card]').count(), 14); const elements = gallery.locator('[data-library-panel=elements]');
const brokenPreviews = await gallery.locator('[data-template-card] img').evaluateAll(async (images) => { const moduleTab = gallery.getByRole('tab', {name: '组件'});
const elementTab = gallery.getByRole('tab', {name: '元素'});
const backToModules = () => modules.getByRole('button', {name: '返回分类'}).click();
const openModule = (key) => modules.locator('[data-library-category="' + key + '"]').click();
assert.equal(await modules.locator('[data-library-category]:visible').count(), 7);
assert.equal(await modules.locator('[data-template-card]:visible').count(), 0);
assert.equal(await modules.locator('[data-template-card]').count(), 59);
assert.equal(await modules.locator('[data-canvas-template^=existing-pagepan]').count(), 0);
assert.equal(await modules.locator('[data-canvas-template=existing-highspeaker-registration]').count(), 0);
assert.equal(await modules.locator('[data-canvas-template=existing-highspeaker-features]').getAttribute('data-template-title'), '特性组');
assert.equal(await modules.getByText('按锚点新建区块').count(), 1);
assert.equal(await gallery.locator('[data-library-panel=layers]').getByText(/首屏与目录|按锚点新建区块/).count(), 0);
assert.equal(await page.locator('#studio-page-settings').getByText('首屏与目录').count(), 1);
await copyText.first().click();
await moduleTab.press('ArrowRight');
assert.equal(await elementTab.getAttribute('aria-selected'), 'true');
assert.equal(await elements.locator('[data-library-category]:visible').count(), 4);
assert.equal(await elements.locator('[data-canvas-element]:visible').count(), 0);
const structural = elements.locator('[data-library-category=structure-elements]');
await structural.click();
assert.equal(await elements.locator('[data-library-category]:visible').count(), 0);
assert.equal(await elements.locator('[data-canvas-element]:visible').count(), 12);
await elements.getByRole('button', {name: '插入分割线'}).click();
await frame.locator('#fixtures .studio-divider').waitFor();
await elements.getByRole('button', {name: '插入留白'}).click();
await frame.locator('#fixtures .studio-spacer').waitFor();
await elements.getByRole('button', {name: '返回分类'}).click();
assert(await structural.evaluate((button) => button === document.activeElement));
await moduleTab.click();
const brokenPreviews = await modules.locator('[data-template-card] img').evaluateAll(async (images) => {
for (const image of images) image.loading = 'eager'; for (const image of images) image.loading = 'eager';
await Promise.all(images.map((image) => image.decode())); await Promise.all(images.map((image) => image.decode()));
return images.filter((image) => image.naturalWidth !== 768).length; return images.filter((image) => image.naturalWidth !== 768).length;
}); });
assert.equal(brokenPreviews, 0); assert.equal(brokenPreviews, 0);
await gallery.locator('[data-template-filter=cover]').click(); await openModule('cover');
assert.equal(await gallery.locator('[data-template-card]:visible').count(), 2); assert.equal(await modules.locator('[data-template-card]:visible').count(), 7);
const cover = gallery.locator('[data-template-preview=cover]'); const cover = gallery.locator('[data-template-preview=cover]');
await cover.hover(); await cover.hover();
const peek = gallery.locator('[data-template-peek]'); const peek = gallery.locator('[data-template-peek]');
@@ -143,14 +218,33 @@ async function run(browser) {
await dialog.locator('[data-template-use]').click(); await dialog.locator('[data-template-use]').click();
await frame.locator('section[id^=block-] h2').filter({hasText: '图文封面'}).waitFor(); await frame.locator('section[id^=block-] h2').filter({hasText: '图文封面'}).waitFor();
await gallery.locator('[data-template-filter=""]').click(); await backToModules();
const search = gallery.locator('[data-template-search]'); await openModule('layout');
const search = modules.locator('[data-template-search]');
await search.fill('does-not-exist'); await search.fill('does-not-exist');
await gallery.locator('[data-template-empty]').waitFor({state: 'visible'}); await modules.locator('[data-template-empty]').waitFor({state: 'visible'});
await search.fill('双栏'); await search.fill('双栏');
assert.equal(await gallery.locator('[data-template-card]:visible').count(), 1); assert.equal(await modules.locator('[data-template-card]:visible').count(), 1);
await search.fill('重点提示');
await modules.locator('[data-template-empty]').waitFor({state: 'visible'});
await backToModules();
await openModule('details');
await modules.locator('[data-canvas-template=pricing]').click();
await frame.locator('.studio-pricing').waitFor();
await modules.locator('[data-canvas-template=existing-sc-materials]').click();
await frame.locator('section[id^=block-]').filter({hasText: '申请软著需要哪些材料'}).waitFor();
await modules.locator('[data-canvas-template=existing-sc-pricing]').click();
const reused = frame.locator('section[id^=block-]').filter({hasText: '服务方案与价格'});
const reusedId = await reused.getAttribute('id');
assert.equal(await reused.locator('#' + reusedId + '-price1').count(), 1);
assert.equal(await frame.locator('#fee-sample-price1').count(), 1);
await backToModules();
await openModule('content');
await search.fill('重点提示');
await modules.locator('[data-canvas-template=notice]').click();
await frame.locator('.studio-notice').waitFor();
await search.fill('分类文章'); await search.fill('分类文章');
await gallery.locator('[data-canvas-template=articles]').click(); await modules.locator('[data-canvas-template=articles]').click();
await frame.locator('section[id^=block-] h2').filter({hasText: '分类文章'}).waitFor(); await frame.locator('section[id^=block-] h2').filter({hasText: '分类文章'}).waitFor();
await Promise.all([ await Promise.all([
@@ -161,7 +255,14 @@ async function run(browser) {
await frame.locator('section[id^=block-] .studio-cover').waitFor(); 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 a').getAttribute('href'), '/articles');
assert.equal(await frame.locator('#fixtures img').getAttribute('src'), '/assets/original/home-hero.webp'); assert.equal(await frame.locator('#fixtures img').getAttribute('src'), '/assets/original/home-hero.webp');
assert.equal(await frame.locator('#fixtures img').getAttribute('class'), imageSize); assert.deepEqual((await image.getAttribute('class')).split(/\s+/).sort(), [imageSize, 'studio-align-center'].sort());
assert.equal(await heroTitle.evaluate((node) => getComputedStyle(node.parentElement).textAlign), 'right');
assert.equal(await sectionTitle.evaluate((node) => getComputedStyle(node).textAlign), 'center');
assert.deepEqual(await copyText.evaluateAll((nodes) => nodes.map((node) => getComputedStyle(node).textAlign)), ['right', 'right']);
await frame.locator('.studio-notice').waitFor();
await frame.locator('#fixtures .studio-divider').waitFor();
await frame.locator('#fixtures .studio-spacer').waitFor();
await frame.locator('.studio-pricing').waitFor();
assert.match(await frame.locator('[data-visual]').getAttribute('class'), /studio-media-99/); assert.match(await frame.locator('[data-visual]').getAttribute('class'), /studio-media-99/);
assert.equal(await copyText.count(), 2); assert.equal(await copyText.count(), 2);
assert.equal(await frame.locator('#copy-fixture').count(), 1); assert.equal(await frame.locator('#copy-fixture').count(), 1);
@@ -179,18 +280,22 @@ async function run(browser) {
phonePage.on('pageerror', (error) => errors.push(error.message)); phonePage.on('pageerror', (error) => errors.push(error.message));
await phonePage.goto(editorPath); await phonePage.goto(editorPath);
const phoneGallery = phonePage.locator('[data-canvas-presets]'); const phoneGallery = phonePage.locator('[data-canvas-presets]');
await phoneGallery.locator('[data-template-filter=cover]').tap(); await phoneGallery.locator('[data-library-category=cover]').tap();
await phoneGallery.locator('[data-template-preview=banner]').tap(); await phoneGallery.locator('[data-template-preview=banner]').tap();
await phoneGallery.locator('[data-template-dialog]').waitFor({state: 'visible'}); await phoneGallery.locator('[data-template-dialog]').waitFor({state: 'visible'});
assert.equal(await phoneGallery.locator('[data-template-dialog] h2').textContent(), '横幅'); assert.equal(await phoneGallery.locator('[data-template-dialog] h2').textContent(), '横幅');
await phonePage.goto(editorPath + '#blocks');
assert.equal(await phoneGallery.getByRole('tab', {name: '图层'}).getAttribute('aria-selected'), 'true');
assert(await phoneGallery.locator('#blocks').evaluate((details) => details.open));
await phone.close(); await phone.close();
await verifyArticleLibrary(browser, context, page, post, slug, feedId); await verifyArticleLibrary(browser, context, page, post, slug, feedId);
await verifyHomeModules(context, page);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
await context.close(); await context.close();
} }
async function verifyArticleLibrary(browser, context, page, post, slug, feedId) { async function verifyArticleLibrary(browser, context, page, post, slug, feedId) {
const category = slug + '-category'; const category = String(Date.now());
await post('/admin/article-categories', {slug: category, name: '自定义测试分类'}); await post('/admin/article-categories', {slug: category, name: '自定义测试分类'});
const articleSlug = slug + '-article'; const articleSlug = slug + '-article';
await page.goto('/admin/articles/new'); await page.goto('/admin/articles/new');
@@ -202,6 +307,7 @@ async function verifyArticleLibrary(browser, context, page, post, slug, feedId)
await page.locator('[name=title]').fill('测试 Markdown 和富文本'); await page.locator('[name=title]').fill('测试 Markdown 和富文本');
await page.locator('[name=slug]').fill(articleSlug); await page.locator('[name=slug]').fill(articleSlug);
await page.locator('[name="categories[]"][value="' + category + '"]').check(); await page.locator('[name="categories[]"][value="' + category + '"]').check();
await page.locator('[name="categories[]"][value=product]').check();
await page.locator('[name=status]').selectOption('published'); await page.locator('[name=status]').selectOption('published');
await markdown.fill('**Markdown 分屏**'); await markdown.fill('**Markdown 分屏**');
await preview.locator('strong').getByText('Markdown 分屏').waitFor(); await preview.locator('strong').getByText('Markdown 分屏').waitFor();
@@ -211,7 +317,7 @@ async function verifyArticleLibrary(browser, context, page, post, slug, feedId)
const publishedPath = '/articles/' + articleSlug; const publishedPath = '/articles/' + articleSlug;
const sourcePage = await context.newPage(); const sourcePage = await context.newPage();
await sourcePage.goto(publishedPath); await sourcePage.goto(publishedPath);
assert.equal(await sourcePage.locator('[itemprop=articleSection]').count(), 2); assert.equal(await sourcePage.locator('[itemprop=articleSection]').count(), 3);
await sourcePage.locator('[itemprop=articleBody] strong').getByText('Markdown 分屏').waitFor(); await sourcePage.locator('[itemprop=articleBody] strong').getByText('Markdown 分屏').waitFor();
await page.goto(articleAdmin); await page.goto(articleAdmin);
await editor.locator('.toastui-editor-mode-switch').getByText('所见即所得', {exact: true}).click(); await editor.locator('.toastui-editor-mode-switch').getByText('所见即所得', {exact: true}).click();
@@ -241,6 +347,7 @@ async function verifyArticleLibrary(browser, context, page, post, slug, feedId)
await page.locator('[name="feed_categories[]"][value="' + category + '"]').check(); await page.locator('[name="feed_categories[]"][value="' + category + '"]').check();
await page.getByRole('button', {name: '保存区块'}).click(); await page.getByRole('button', {name: '保存区块'}).click();
await page.locator('[data-save-confirmation]').waitFor({state: 'visible'}); 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(); let contentVersion = await page.locator('[name=version]').inputValue();
assert.equal(contentVersion, '1'); assert.equal(contentVersion, '1');
const canvasPath = '/admin/pages/' + slug + '/preview'; const canvasPath = '/admin/pages/' + slug + '/preview';
@@ -268,18 +375,225 @@ async function verifyArticleLibrary(browser, context, page, post, slug, feedId)
assert.equal(await noJSPage.locator('#' + feedId + ' a[href="' + publishedPath + '"]:visible').count(), 2); assert.equal(await noJSPage.locator('#' + feedId + ' a[href="' + publishedPath + '"]:visible').count(), 2);
await noJS.close(); await noJS.close();
assert((await context.request.get('/articles/category/' + category)).ok()); assert((await context.request.get('/articles/category/' + category)).ok());
await sourcePage.goto('/services'); await verifyScopedArchive(context, page, sourcePage, post, slug, feedId, category, publishedPath);
await sourcePage.locator('.catalog-card').first().waitFor(); await verifyEditableLandingPages(page, sourcePage, category, publishedPath, slug);
await sourcePage.goto('/network'); await sourcePage.goto('/network');
assert.equal(await sourcePage.locator('.network-group').count(), 2); assert.equal(await sourcePage.locator('.network-group').count(), 2);
await sourcePage.close(); await sourcePage.close();
await page.goto(articleAdmin);
const deletePath = articleAdmin + '/delete';
const deleteForm = page.locator('form[action="' + deletePath + '"]');
const version = await deleteForm.locator('[name=version]').inputValue();
const csrf = await deleteForm.locator('[name=csrf]').inputValue();
const headers = {'X-Requested-With': 'XMLHttpRequest'};
assert.equal((await context.request.post(deletePath, {form: {version}, headers})).status(), 403);
assert.equal((await context.request.post(deletePath, {form: {csrf, version: String(Number(version) + 1)}, headers})).status(), 409);
assert.equal((await context.request.get(publishedPath)).status(), 200);
await page.getByText('删除文章', {exact: true}).click();
await deleteForm.getByRole('button', {name: '永久删除'}).click();
await page.waitForURL('**/admin/articles?deleted=1');
await page.getByText('文章已删除。', {exact: true}).waitFor();
assert.equal(await page.locator('a[href="' + articleAdmin + '"]').count(), 0);
assert.equal((await context.request.get(articleAdmin)).status(), 404);
assert.equal((await context.request.get(publishedPath)).status(), 404);
assert(!(await (await context.request.get('/sitemap.xml')).text()).includes(publishedPath + '</loc>'));
}
async function verifyEditableLandingPages(admin, publicPage, category, articlePath, slug) {
await publicPage.goto('/articles');
const defaultLinks = publicPage.locator('#updates .article-list a');
assert.equal(await defaultLinks.filter({hasText: 'LayFi'}).count(), 0);
assert.equal(await defaultLinks.filter({hasText: 'PAGEPAN 小飞页'}).count(), 0);
await admin.goto('/admin/pages/articles');
const frame = admin.frameLocator('iframe[title="可编辑页面画布"]');
await frame.locator('#updates h2').click();
const tools = admin.getByRole('group', {name: '所选元素'});
await tools.getByRole('button', {name: '模块设置'}).click();
const settings = admin.locator('[data-module-dialog]');
for (const option of await settings.locator('[name="feed_categories[]"]').all()) await option.uncheck();
await settings.locator('[name="feed_categories[]"][value="' + category + '"]').check();
await settings.locator('[name=feed_limit]').fill('30');
await settings.getByRole('button', {name: '应用'}).click();
await admin.getByRole('button', {name: '保存页面', exact: true}).first().click();
await admin.locator('[data-save-confirmation]').waitFor();
await publicPage.reload();
assert.equal(await publicPage.locator('#updates a[href="' + articlePath + '"]').count(), 1);
assert.equal(await publicPage.locator('#updates a[href="/articles/' + slug + '-excluded"]').count(), 0);
const allUpdates = publicPage.locator('#updates').getByRole('link', {name: '查看全部动态'});
assert.equal(await allUpdates.getAttribute('href'), '/articles/feed/articles/updates');
await allUpdates.click();
await publicPage.waitForURL('**/articles/feed/articles/updates');
const archiveLinks = publicPage.locator('.article-list a');
const excludedPath = '/articles/' + slug + '-excluded';
assert.equal(await archiveLinks.filter({hasText: '分类分页样例 20'}).count(), 1);
assert.equal(await publicPage.locator('.article-list a[href="' + excludedPath + '"]').count(), 0);
await publicPage.getByRole('link', {name: '下一页'}).click();
await publicPage.waitForURL('**/articles/feed/articles/updates?page=2');
assert.equal(await publicPage.locator('.article-list a[href="' + articlePath + '"]').count(), 1);
assert.equal(await publicPage.locator('.article-list a[href="' + excludedPath + '"]').count(), 0);
assert.equal((await publicPage.request.get('/articles/feed/articles/updates?category=announcement')).status(), 404);
await admin.goto('/admin/pages/services');
await frame.locator('#catalog h2').click();
await tools.getByRole('button', {name: '模块设置'}).click();
assert.equal(await settings.locator('[name=feed_mode]').inputValue(), 'catalog');
assert(await settings.locator('[name="feed_categories[]"][value=services]').isChecked());
await settings.locator('[name=module_title]').fill('产品目录验证');
await settings.getByRole('button', {name: '应用'}).click();
await admin.getByRole('button', {name: '保存页面', exact: true}).first().click();
await admin.locator('[data-save-confirmation]').waitFor();
await publicPage.goto('/services');
await publicPage.getByRole('heading', {name: '产品目录验证'}).waitFor();
const cards = publicPage.locator('#catalog .catalog-card');
assert(await cards.count() > 0);
assert.equal(await cards.getByRole('link', {name: '查看详情', exact: true}).count(), 0);
assert.equal(await cards.locator('a[href="/pagepan#download"]').count(), 1);
await admin.goto('/admin/pages/contact');
await frame.locator('#contact-information a[href="mailto:public@laysense.cn"]').waitFor();
await publicPage.goto('/contact');
await publicPage.getByRole('heading', {name: '联系来笙', exact: true}).waitFor();
assert.equal(await publicPage.locator('#contact-information a[href="mailto:public@laysense.cn"]').count(), 1);
}
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 function verifyHomeModules(context, page) {
await page.goto('/admin/pages/home');
const frame = page.frameLocator('iframe[title="可编辑页面画布"]');
const tools = page.getByRole('group', {name: '所选元素'});
const directory = frame.locator('#hero-directory .hero-directory');
const cards = directory.locator(':scope > a');
const card = cards.nth(1);
assert.equal(await cards.count(), 5);
await card.click();
const edit = tools.getByRole('button', {name: '属性'});
assert.equal((await edit.textContent()).trim(), '');
await edit.click();
const props = page.locator('[data-canvas-properties]');
await props.locator('[name=label]').fill('PAGEPAN 导航验证');
await props.locator('[name=note]').fill('编辑过的导航说明');
await props.locator('[name=url]').fill('/pagepan#download');
await props.getByRole('button', {name: '应用'}).click();
assert.equal(await card.locator('small').textContent(), '编辑过的导航说明');
await cards.last().click();
await tools.getByRole('button', {name: '删除'}).click();
assert.equal(await cards.count(), 4);
await verifyDirectoryWidth(directory);
await frame.locator('#network h2').click();
const moduleSettings = tools.getByRole('button', {name: '模块设置'});
await moduleSettings.waitFor();
assert.equal(await tools.getByRole('button').allTextContents().then((items) => items.map((text) => text.trim()).join('')), '');
assert.equal(await tools.getByRole('button').count(), 3);
assert.equal(await frame.locator('#network h2').getAttribute('contenteditable'), null);
const copyButton = tools.getByRole('button', {name: '复制'});
await copyButton.click();
const pending = frame.locator('[data-studio-dynamic][id^=block-]').filter({hasText: '模块副本将在保存页面后生效。'});
const id = await pending.getAttribute('id');
await moduleSettings.click();
const dialog = page.locator('[data-module-dialog]');
await dialog.locator('[name=module_title]').fill('复制的伙伴模块');
await dialog.locator('[name=feed_limit]').fill('1');
await dialog.locator('[name="feed_categories[]"][value=supported-projects]').uncheck();
assert(await dialog.locator('[name="feed_categories[]"][value=partners]').isChecked());
await dialog.getByRole('button', {name: '应用'}).click();
await page.getByRole('button', {name: '保存页面', exact: true}).first().click();
await page.locator('[data-save-confirmation]').waitFor();
await frame.locator('#' + id + ' h2').getByText('复制的伙伴模块').waitFor();
const publicPage = await context.newPage();
await publicPage.goto('/');
const module = publicPage.locator('#' + id);
assert.equal(await module.locator('.network-group').count(), 1);
assert.equal(await module.locator('.network-list li').count(), 1);
assert.equal(await module.getByRole('link', {name: '查看全部'}).getAttribute('href'), '/articles/feed/home/' + id);
assert.equal(await publicPage.locator('#hero-directory a').nth(1).getAttribute('href'), '/pagepan#download');
assert.equal(await publicPage.locator('#hero-directory a').nth(1).locator('small').textContent(), '编辑过的导航说明');
const publicDirectory = publicPage.locator('#hero-directory .hero-directory');
assert.equal(await publicDirectory.locator(':scope > a').count(), 4);
await verifyDirectoryWidth(publicDirectory);
await publicPage.setViewportSize({width: 390, height: 844});
await verifyDirectoryWidth(publicDirectory);
assert.equal(await publicPage.locator('#network #supported-projects').count(), 1);
await page.bringToFront();
await frame.locator('#' + id + ' h2').click();
page.once('dialog', (prompt) => prompt.accept());
await tools.getByRole('button', {name: '删除'}).click();
await frame.locator('#' + id).waitFor({state: 'detached'});
await page.getByRole('button', {name: '保存页面', exact: true}).first().click();
await page.locator('[data-save-confirmation]').waitFor();
await publicPage.reload();
assert.equal(await publicPage.locator('#' + id).count(), 0);
assert.equal(await publicPage.locator('#network').count(), 1);
assert.equal((await context.request.get('/articles/feed/home/' + id)).status(), 404);
await publicPage.close();
}
async function verifyDirectoryWidth(directory) {
assert(await directory.evaluate((node) => {
const rightEdge = node.getBoundingClientRect().right - node.clientLeft;
const lastLink = node.lastElementChild.getBoundingClientRect();
return Math.abs(rightEdge - lastLink.right) < 1;
}));
} }
(async () => { (async () => {
const browser = await chromium.launch({executablePath: process.env.CHROMIUM_EXECUTABLE || undefined}); const browser = await chromium.launch({executablePath: process.env.CHROMIUM_EXECUTABLE || undefined});
try { try {
await run(browser); await run(browser);
console.log('Passed Chromium canvas media/link interactions, template gallery, persistence, and the article library.'); console.log('Passed Chromium dashboard, template library, dynamic modules, homepage link reflow, scoped archives, and article deletion.');
} finally { } finally {
await browser.close(); await browser.close();
} }