60 changed files with 3097 additions and 163 deletions
+31 -5
View File
@@ -4,7 +4,7 @@ PHP Webman、原生 CSS 和 SQLite 实现的来笙官网。公开页面由服务
## 本地启动 ## 本地启动
需要 Linux、PHP 8.2+ CLI、Composer 2,以及启用 `pcntl`、`posix`、`pdo_sqlite`、`dom` 和 `mbstring` 的 PHP 环境。 需要 Linux、PHP 8.2+ CLI、Composer 2,以及启用 `pcntl`、`posix`、`pdo_sqlite`、`dom`、`fileinfo` 和 `mbstring` 的 PHP 环境。
```sh ```sh
composer install composer install
@@ -27,7 +27,10 @@ php bin/admin.php reset admin@example.com
## 后台编辑 ## 后台编辑
- **页面**可修改首屏标题、简介、图片、按钮,以及每页的 SEO 标题和描述。页面正文按区块编辑,支持受限 HTML 和预览。 - **页面设计**支持新建草稿、发布和撤回。首屏标题与简介可在桌面或手机画布中直接编辑。区块支持新增、排序、删除、可视化编辑、媒体插入和 HTML 源码。编辑器左侧可按分类和名称查找模板。悬停或键盘聚焦缩略图可放大,点击可打开预览。
- **媒体库**集中列出项目静态文件及上传文件,支持查找、选取、复制路径、改名和归档。归档资源的已有 URL 保持可访问。上传文件放在 `LAYSENSE_MEDIA_DIR`,由 `/assets/uploads/` 提供。
- **产品与服务**在 `/services` 显示独立的服务端 HTML 目录。后台支持添加、排序、修改和移除条目,并设置分类、封面、简介和按钮链接。
- **网站设置**分别编辑页头标志、导航及按钮,和页脚的公司信息、链接与备注。CDN 设置接受 HTTPS 源站地址。浏览器看到的公开 `/assets/…` 路径使用该源站。
- **文章与动态**使用 Markdown,支持正文预览、摘要、标签和公告、新闻、产品分类。状态选「草稿」可撤回公开文章。已发布文章改网址标识后,旧标识会自动跳转。 - **文章与动态**使用 Markdown,支持正文预览、摘要、标签和公告、新闻、产品分类。状态选「草稿」可撤回公开文章。已发布文章改网址标识后,旧标识会自动跳转。
- 首页动态、分类列表和站点地图随发布状态更新。源代码和 SQLite 数据分开管理。安装命令可重复执行,已编辑的内容会保留。 - 首页动态、分类列表和站点地图随发布状态更新。源代码和 SQLite 数据分开管理。安装命令可重复执行,已编辑的内容会保留。
@@ -40,13 +43,19 @@ php bin/admin.php reset admin@example.com
下面的 Nginx 片段可放入现有 HTTPS 虚拟主机。Nginx 会覆盖请求携带的 `X-Real-IP`,应用默认信任本机回环地址传来的该请求头。密码验证失败的请求按来源计数,超过阈值后返回 429。正确密码仍可登录。 下面的 Nginx 片段可放入现有 HTTPS 虚拟主机。Nginx 会覆盖请求携带的 `X-Real-IP`,应用默认信任本机回环地址传来的该请求头。密码验证失败的请求按来源计数,超过阈值后返回 429。正确密码仍可登录。
```nginx ```nginx
location / {
proxy_pass http://127.0.0.1:8787;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
location / {
proxy_pass http://127.0.0.1:8787;
client_max_body_size 2m; client_max_body_size 2m;
} }
location = /admin/media {
proxy_pass http://127.0.0.1:8787;
client_max_body_size 66m;
}
``` ```
| 环境变量 | 默认值与用途 | | 环境变量 | 默认值与用途 |
@@ -55,10 +64,15 @@ location / {
| `LAYSENSE_LISTEN` | `http://127.0.0.1:8787` · Webman 监听地址 | | `LAYSENSE_LISTEN` | `http://127.0.0.1:8787` · Webman 监听地址 |
| `LAYSENSE_WORKERS` | `2` · Webman worker 数量 | | `LAYSENSE_WORKERS` | `2` · Webman worker 数量 |
| `LAYSENSE_DB` | `storage/laysense.sqlite` · SQLite 文件路径。生产可指向独立的持久化目录 | | `LAYSENSE_DB` | `storage/laysense.sqlite` · SQLite 文件路径。生产可指向独立的持久化目录 |
| `LAYSENSE_MEDIA_DIR` | `storage/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。迁移服务器或做线上备份时,可用 `sqlite3 storage/laysense.sqlite ".backup 'laysense-backup.sqlite'"` 取得一致备份。更新代码时保留数据库文件及其存放目录,以同一 `LAYSENSE_DB` 执行 `php bin/install.php` 应用迁移,然后重启服务。已有数据库会补回 PAGEPAN 原始功能图标,保留已编辑的文案和已有图像。服务用户需要对 SQLite 目录和 `runtime/` 有写权限。 SQLite 已启用 WAL。迁移服务器或做线上备份时,可用 `sqlite3 storage/laysense.sqlite ".backup 'laysense-backup.sqlite'"` 取得一致备份。更新代码时保留数据库文件及其存放目录,以同一 `LAYSENSE_DB` 执行 `php bin/install.php` 应用迁移,然后重启服务。已有数据库会补回 PAGEPAN 原始功能图标,保留已编辑的文案和已有图像。服务用户需要对 SQLite 目录、媒体目录和 `runtime/` 有写权限。备份站点时一并保存 SQLite 和媒体目录。
### CDN
先让 CDN 的 `/assets/` 转发到 Webman 站点,再在「网站设置 → CDN」填写地址。CDN 需要保留静态资源的 CORS 响应头和视频 Range 请求。配置留空时,公开资源由站点直接提供。后台登录和编辑资源始终由站点提供。
## 迁移范围 ## 迁移范围
@@ -67,3 +81,15 @@ SQLite 已启用 WAL。迁移服务器或做线上备份时,可用 `sqlite3 st
- 旧站 2024 年 11 月 10 日关于减少全球服务器部署的公告返回空白正文。迁移保留标题、日期、标签和旧链接,正文补录前会标记为不索引。 - 旧站 2024 年 11 月 10 日关于减少全球服务器部署的公告返回空白正文。迁移保留标题、日期、标签和旧链接,正文补录前会标记为不索引。
- SHNU 旧页首屏写 ¥69,详细报价表与正文写 ¥66。新版保留报价表中的 ¥66,并保留旧页学生资格及学分说明。两处普通软著页面的咨询按钮现在直达该页既有的企业微信入口。 - SHNU 旧页首屏写 ¥69,详细报价表与正文写 ¥66。新版保留报价表中的 ¥66,并保留旧页学生资格及学分说明。两处普通软著页面的咨询按钮现在直达该页既有的企业微信入口。
- 中文公开页复用页头、页尾、首屏、内容区块、动态列表及同一套 CSS。历史迁移内容见 `resources/seed.json`,结构见 `resources/schema.sql`。 - 中文公开页复用页头、页尾、首屏、内容区块、动态列表及同一套 CSS。历史迁移内容见 `resources/seed.json`,结构见 `resources/schema.sql`。
## 画布浏览器回归
`tests/studio-browser.cjs` 用 Playwright 在真实 Chromium 内检查媒体及链接编辑、模板分类、搜索、预览、触屏操作和保存。使用已启动的测试实例、独立的 SQLite 数据库和管理员账户。测试会在该库创建一个草稿页面。
```sh
LAYSENSE_TEST_URL=http://127.0.0.1:8787 \
LAYSENSE_TEST_EMAIL=studio-test@example.com \
node tests/studio-browser.cjs
```
先安装 Playwright 和 Chromium,并在测试进程的环境里设置 `LAYSENSE_TEST_PASSWORD`。已安装在独立目录的 Playwright 可通过 `PLAYWRIGHT_MODULE` 指定模块路径。系统 Chromium 可通过 `CHROMIUM_EXECUTABLE` 指定。
+63
View File
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace App\Content;
use RuntimeException;
final class Assets
{
public static function cdn(string $value): string
{
$value = rtrim(trim($value), '/');
if ($value !== '' && (strlen($value) > 263 || !preg_match('~^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?::[0-9]{1,5})?$~iD', $value))) {
throw new RuntimeException('请填写 HTTPS CDN 源站地址,例如 https://cdn.laysense.cn。');
}
if (($port = parse_url($value, PHP_URL_PORT)) !== null && ($port === false || $port < 1)) {
throw new RuntimeException('CDN 端口无效。');
}
return $value;
}
public static function url(string $path, string $cdn): string
{
return str_starts_with($path, '/assets/') ? $cdn . $path : $path;
}
public static function rewrite(string $html, string $cdn): string
{
if ($cdn === '') {
return $html;
}
// Match opening tags separately from comments and text-only elements' contents.
$tags = <<<'REGEX'
~<!--.*?(?:-->|\z)|(?<opening><(?:(?<textTag>script|style|textarea|title)|[a-z][\w:-]*)(?=[\s/>])(?:[^<>"']++|"[^"]*"|'[^']*')*+>)(?(textTag)(?<tail>.*?(?:</\k<textTag>\s*>|\z)))~is
REGEX;
$attributes = <<<'REGEX'
~(\s+)([^\s/<>="']+)(?:(\s*=\s*)("[^"]*"|'[^']*'|[^\s<>"'=`]+))?~
REGEX;
return preg_replace_callback($tags, static function (array $tag) use ($attributes, $cdn): string {
if (!isset($tag['opening'])) {
return $tag[0];
}
$opening = preg_replace_callback($attributes, static function (array $attribute) use ($cdn): string {
if (!isset($attribute[4]) || !in_array(strtolower($attribute[2]), ['src', 'href', 'poster'], true)) {
return $attribute[0];
}
$value = $attribute[4];
$quote = str_starts_with($value, '"') || str_starts_with($value, "'") ? $value[0] : '';
$path = $quote === '' ? $value : substr($value, 1, -1);
return $attribute[1] . $attribute[2] . $attribute[3] . $quote . self::url($path, $cdn) . $quote;
}, $tag['opening']) ?? $tag['opening'];
return $opening . ($tag['tail'] ?? '');
}, $html) ?? $html;
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Content;
final class BlockTemplates
{
public const GROUPS = [
'content' => ['标题与正文', [
'headline' => ['标题与简介', '<div class="studio-intro"><h3>填写区块标题</h3><p>用一句话补充背景或说明。</p></div>'],
'text' => ['正文', '<p>在这里输入区块内容。</p>'],
'list' => ['步骤列表', '<ol><li>填写第一步</li><li>填写第二步</li><li>填写第三步</li></ol>'],
]],
'cover' => ['封面与横幅', [
'cover' => ['图文封面', '<div class="studio-cover"><img src="/assets/original/pagepan-example.webp" alt="" loading="lazy"><div><h3>用一句话介绍你的产品</h3><p>在首段说明访客能获得什么。</p><a class="button button-primary" href="/services">查看服务</a></div></div>'],
'banner' => ['横幅', '<div class="studio-banner"><h3>用一句话介绍你的项目</h3><p>简要说明项目能为访客做什么。</p><a class="button button-primary" href="/services">了解更多</a></div>'],
]],
'layout' => ['图文与布局', [
'image' => ['图文', '<div class="studio-split"><img src="/assets/original/home-hero.webp" alt="" loading="lazy"><div><h3>介绍主题</h3><p>在这里说明图片或产品。</p></div></div>'],
'grid' => ['双栏网格', '<div class="studio-two-column"><article class="content-card"><h3>第一栏</h3><p>填写主要内容。</p></article><article class="content-card"><h3>第二栏</h3><p>补充相关信息。</p></article></div>'],
]],
'features' => ['特性与口碑', [
'features' => ['特性卡片', '<div class="card-grid feature-grid"><article class="content-card feature-card"><h3>特点一</h3><p>介绍这个特点。</p></article><article class="content-card feature-card"><h3>特点二</h3><p>介绍这个特点。</p></article><article class="content-card feature-card"><h3>特点三</h3><p>介绍这个特点。</p></article></div>'],
'quote' => ['引文', '<blockquote><p>在这里填写引用或用户反馈。</p></blockquote>'],
]],
'details' => ['表格与问答', [
'table' => ['对比表格', '<table><thead><tr><th scope="col">项目</th><th scope="col">说明</th></tr></thead><tbody><tr><td>项目一</td><td>填写说明</td></tr><tr><td>项目二</td><td>填写说明</td></tr></tbody></table>'],
'faq' => ['常见问题', '<div class="faq"><details><summary>请输入问题</summary><div><p>请输入答案。</p></div></details></div>'],
]],
'actions' => ['导航与引导', [
'navigation' => ['快速导航', '<ul class="studio-quick-nav"><li><a href="/services">产品与服务</a></li><li><a href="/articles">动态与文章</a></li><li><a href="/#contact">联系来笙</a></li></ul>'],
'cta' => ['行动按钮', '<p>说明下一步。</p><p><a class="button button-primary" href="#contact">联系来笙</a></p>'],
]],
];
public static function find(string $key): ?array
{
foreach (self::GROUPS as [, $templates]) {
if (isset($templates[$key])) {
return $templates[$key];
}
}
return null;
}
}
+15
View File
@@ -40,6 +40,13 @@ final class Database
self::write(function (PDO $pdo) use ($root, $seed): void { self::write(function (PDO $pdo) use ($root, $seed): void {
$pdo->exec(file_get_contents($root . '/resources/schema.sql')); $pdo->exec(file_get_contents($root . '/resources/schema.sql'));
$pageColumns = array_column($pdo->query('PRAGMA table_info(pages)')->fetchAll(), 'name');
if (!in_array('status', $pageColumns, true)) {
$pdo->exec("ALTER TABLE pages ADD COLUMN status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('draft', 'published'))");
}
if (!in_array('image_scale', $pageColumns, true)) {
$pdo->exec('ALTER TABLE pages ADD COLUMN image_scale INTEGER NOT NULL DEFAULT 0');
}
$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'])]);
@@ -85,6 +92,14 @@ final class Database
if ($migration->rowCount() === 1) { if ($migration->rowCount() === 1) {
PagepanFeatureIcons::migrate($pdo); PagepanFeatureIcons::migrate($pdo);
} }
$migration->execute(['product_directory_and_service_icons']);
if ($migration->rowCount() === 1) {
DesignMigration::apply($pdo);
}
$migration->execute(['restore_home_featured_products']);
if ($migration->rowCount() === 1) {
DesignMigration::restoreFeaturedProducts($pdo, $seed);
}
}); });
} }
+83
View File
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMElement;
use DOMXPath;
use PDO;
final class DesignMigration
{
private const DIRECTORY_SUMMARY = '<p>浏览来笙的建站工具、智能 DNS 和软件著作权服务。</p><a class="button button-primary" href="/services">查看产品与服务</a>';
public static function apply(PDO $pdo): void
{
$stock = json_decode(file_get_contents(dirname(__DIR__, 2) . '/resources/seed.json'), true, flags: JSON_THROW_ON_ERROR);
$home = array_column($stock['pages'], null, 'slug')['home'];
$stockBody = Html::sanitize(array_column($home['sections'], 'body', 'key')['product']);
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->loadHTML('<meta charset="UTF-8">' . $stockBody, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
$xpath = new DOMXPath($doc);
$insert = $pdo->prepare('INSERT INTO catalog (name, category, body, image, alt, url, label, extra_url, extra_label, position)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
foreach ($xpath->query('//article[contains(concat(" ", @class, " "), " project ")]') as $position => $card) {
$image = $xpath->query('.//img', $card)->item(0);
$links = $xpath->query('.//a', $card);
$body = '';
foreach ($xpath->query('.//p', $card) as $paragraph) {
$body .= $doc->saveHTML($paragraph);
}
$insert->execute([
trim($xpath->evaluate('string(.//h3)', $card)), trim($xpath->evaluate('string(.//span)', $card)),
Html::sanitize($body), $image->getAttribute('src'), $image->getAttribute('alt'),
$links->item(0)->getAttribute('href'), trim($links->item(0)->textContent),
$links->item(1)?->getAttribute('href') ?? '', trim($links->item(1)?->textContent ?? ''), $position * 10,
]);
}
$pdo->prepare('INSERT INTO catalog (name, category, body, image, alt, url, label, position) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
->execute(['SHNU 学生软著服务', '校园服务', '<p>面向 SHNU 学生的软件著作权申请服务。</p>',
'/assets/original/shnu-hero.webp', '', '/shnu-sc', '查看学生方案', 30]);
$pdo->prepare("UPDATE sections SET body = ?, version = version + 1
WHERE page_slug = 'home' AND key = 'product' AND version = 0 AND body = ?")
->execute([self::DIRECTORY_SUMMARY, $stockBody]);
$choices = $pdo->query("SELECT page_slug, body FROM sections WHERE key = 'why' AND page_slug IN ('sc', 'shnu-sc')");
$updateChoice = $pdo->prepare("UPDATE sections SET body = ?, version = version + 1 WHERE page_slug = ? AND key = 'why'");
foreach ($choices->fetchAll() as $section) {
$body = preg_replace('~(<article\b[^>]*class="[^"]*\bfeature-card)("(?:[^>]*>)\s*<h[2-4]>选择来笙</h[2-4]>)~u',
'$1 choice-card$2', $section['body']);
if ($body !== null && $body !== $section['body']) {
$updateChoice->execute([$body, $section['page_slug']]);
}
}
$icons = ['/assets/original/10-1.png' => '/assets/service/project.svg',
'/assets/original/10-2.png' => '/assets/service/code.svg', '/assets/original/10-3.png' => '/assets/service/support.svg'];
$sections = $pdo->query("SELECT page_slug, body FROM sections WHERE key = 'options' AND page_slug IN ('sc', 'shnu-sc')");
$update = $pdo->prepare("UPDATE sections SET body = ?, version = version + 1 WHERE page_slug = ? AND key = 'options'");
foreach ($sections->fetchAll() as $section) {
$body = strtr($section['body'], $icons);
$body = preg_replace('/(<article\b[^>]*>)\s*<li\b[^>]*>(.*?)<\/li>\s*(<\/article>)/s', '$1$2$3', $body);
if ($body !== $section['body']) {
$update->execute([$body, $section['page_slug']]);
}
}
}
public static function restoreFeaturedProducts(PDO $pdo, array $seed): void
{
$home = array_column($seed['pages'], null, 'slug')['home'];
$stockBody = Html::sanitize(array_column($home['sections'], 'body', 'key')['product']);
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->loadHTML('<meta charset="UTF-8">' . $stockBody, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
$projects = $doc->getElementsByTagName('article');
$body = '<div class="project-stack">' . $doc->saveHTML($projects->item(0))
. $doc->saveHTML($projects->item(1)) . '</div>';
$pdo->prepare("UPDATE sections SET body = ?, version = version + 1
WHERE page_slug = 'home' AND key = 'product' AND body = ?")
->execute([Html::sanitize($body), self::DIRECTORY_SUMMARY]);
}
}
+34 -2
View File
@@ -8,11 +8,12 @@ use DOMDocument;
use DOMElement; use DOMElement;
use DOMNode; use DOMNode;
use League\CommonMark\CommonMarkConverter; use League\CommonMark\CommonMarkConverter;
use RuntimeException;
final class Html final class Html
{ {
private const TAGS = [ private const TAGS = [
'a' => ['href'], 'article' => [], 'b' => [], 'blockquote' => [], 'br' => [], 'a' => ['href'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [],
'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'], 'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
'dl' => [], 'dt' => [], 'em' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [], 'dl' => [], 'dt' => [], 'em' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [],
'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'], 'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'],
@@ -20,7 +21,7 @@ final class Html
'small' => [], 'source' => ['src', 'type'], 'span' => [], 'strong' => [], 'summary' => [], 'small' => [], 'source' => ['src', 'type'], 'span' => [], 'strong' => [], 'summary' => [],
'table' => [], 'tbody' => [], 'td' => ['colspan', 'rowspan'], 'tfoot' => [], 'table' => [], 'tbody' => [], 'td' => ['colspan', 'rowspan'], 'tfoot' => [],
'th' => ['scope', 'colspan', 'rowspan'], 'thead' => [], 'tr' => [], 'ul' => [], 'th' => ['scope', 'colspan', 'rowspan'], 'thead' => [], 'tr' => [], 'ul' => [],
'video' => ['controls', 'muted', 'playsinline', 'poster', 'preload'], 'video' => ['src', 'controls', 'muted', 'playsinline', 'poster', 'preload'],
]; ];
public static function url(string $value, bool $media = false): bool public static function url(string $value, bool $media = false): bool
@@ -49,6 +50,37 @@ final class Html
return str_replace(['<h1>', '</h1>'], ['<h2>', '</h2>'], $html); return str_replace(['<h1>', '</h1>'], ['<h2>', '</h2>'], $html);
} }
public static function applyCanvasEdits(string $body, array $edits): string
{
if (!array_is_list($edits) || count($edits) > 512) {
throw new RuntimeException('正文增量无效。');
}
$size = strlen($body);
$cursor = 0;
$result = '';
foreach ($edits as $edit) {
if (!is_array($edit) || !array_is_list($edit) || count($edit) !== 3) {
throw new RuntimeException('正文增量无效。');
}
[$offset, $remove, $insert] = $edit;
if (!is_int($offset) || !is_int($remove) || !is_string($insert)
|| $offset < $cursor || $offset > $size || $remove < 0 || $remove > $size - $offset) {
throw new RuntimeException('正文增量无效。');
}
$result .= substr($body, $cursor, $offset - $cursor) . $insert;
$cursor = $offset + $remove;
if (strlen($result) > 300000) {
throw new RuntimeException('正文太长。');
}
}
$result .= substr($body, $cursor);
if (strlen($result) > 300000 || !mb_check_encoding($result, 'UTF-8')) {
throw new RuntimeException('正文太长或编码无效。');
}
return $result;
}
public static function sanitize(string $html): string public static function sanitize(string $html): string
{ {
$document = new DOMDocument('1.0', 'UTF-8'); $document = new DOMDocument('1.0', 'UTF-8');
+135
View File
@@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMElement;
use DOMXPath;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RuntimeException;
use Throwable;
use Webman\Http\UploadFile;
final class Media
{
public const MAX_BYTES = 64 * 1024 * 1024;
private const EXTENSIONS = [
'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp',
'image/avif' => 'avif', 'image/x-icon' => 'ico', 'image/vnd.microsoft.icon' => 'ico', 'image/svg+xml' => 'svg',
'video/mp4' => 'mp4', 'video/webm' => 'webm', 'video/quicktime' => 'mov',
'audio/mpeg' => 'mp3', 'audio/ogg' => 'ogg', 'audio/wav' => 'wav',
'application/pdf' => 'pdf', 'font/woff' => 'woff', 'font/woff2' => 'woff2',
];
public static function all(bool $includeArchived = false): array
{
$query = 'SELECT name, label, mime, size, created_at, archived FROM media' . ($includeArchived ? '' : ' WHERE archived = 0');
$files = Database::connect()->query($query . ' ORDER BY created_at DESC, name')->fetchAll();
foreach ($files as &$file) {
$file['url'] = '/assets/uploads/' . $file['name'];
}
unset($file);
$root = dirname(__DIR__, 2) . '/public/assets';
$builtIn = [];
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root)) as $file) {
if (!$file->isFile() || $file->isLink() || str_starts_with($file->getFilename(), '.')) {
continue;
}
$path = str_replace(DIRECTORY_SEPARATOR, '/', substr($file->getPathname(), strlen($root) + 1));
$label = $file->getFilename();
$type = array_search(strtolower($file->getExtension()), self::EXTENSIONS, true) ?: 'application/octet-stream';
$builtIn[] = ['label' => $label, 'name' => '', 'mime' => $type, 'size' => $file->getSize(),
'url' => '/assets/' . $path, 'archived' => 0];
}
usort($builtIn, static fn (array $left, array $right): int => strnatcasecmp($left['url'], $right['url']));
return [...$files, ...$builtIn];
}
public static function upload(UploadFile $file, string $label): void
{
if (!$file->isValid() || ($size = $file->getSize()) < 1 || $size > self::MAX_BYTES) {
throw new RuntimeException('请选择大小不超过 64 MB 的有效文件。');
}
$source = $file->getPathname();
$mime = (new \finfo(FILEINFO_MIME_TYPE))->file($source);
$extension = self::EXTENSIONS[$mime] ?? null;
if ($extension === null) {
throw new RuntimeException('文件类型不受支持。');
}
$content = $mime === 'image/svg+xml' ? self::safeSvg($source, $size) : null;
$name = bin2hex(random_bytes(16)) . '.' . $extension;
$directory = self::directory();
if (!is_dir($directory) && !mkdir($directory, 0750, true) && !is_dir($directory)) {
throw new RuntimeException('资源目录无法创建。');
}
$path = $directory . '/' . $name;
try {
$written = $content === null ? copy($source, $path) : file_put_contents($path, $content) === strlen($content);
if (!$written) {
throw new RuntimeException('文件写入失败。');
}
$query = Database::connect()->prepare('INSERT INTO media (name, label, mime, size, created_at) VALUES (?, ?, ?, ?, ?)');
$query->execute([$name, $label, $mime, $content === null ? $size : strlen($content), gmdate('c')]);
} catch (Throwable $error) {
if (is_file($path)) {
unlink($path);
}
throw $error;
}
}
public static function find(string $name): ?array
{
$query = Database::connect()->prepare('SELECT * FROM media WHERE name = ?');
$query->execute([$name]);
return $query->fetch() ?: null;
}
public static function update(string $name, string $label, bool $archived): void
{
Database::connect()->prepare('UPDATE media SET label = ?, archived = ? WHERE name = ?')
->execute([$label, (int) $archived, $name]);
}
public static function directory(): string
{
return rtrim(getenv('LAYSENSE_MEDIA_DIR') ?: dirname(__DIR__, 2) . '/storage/media', '/');
}
private static function safeSvg(string $source, int $size): string
{
if ($size > 512 * 1024) {
throw new RuntimeException('SVG 图标最大支持 512 KB。');
}
$svg = new DOMDocument();
if (!$svg->loadXML(file_get_contents($source), LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) || $svg->doctype
|| $svg->documentElement?->namespaceURI !== 'http://www.w3.org/2000/svg' || $svg->documentElement->localName !== 'svg') {
throw new RuntimeException('SVG 图标格式无效。');
}
$tags = ['svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'title', 'desc'];
$attributes = ['viewBox', 'width', 'height', 'fill', 'fill-rule', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-linecap',
'stroke-linejoin', 'stroke-dasharray', 'stroke-opacity', 'curve', 'clip-rule', 'opacity', 'd', 'x', 'y',
'rx', 'ry', 'cx', 'cy', 'r', 'x1', 'x2', 'y1', 'y2', 'points', 'transform'];
foreach ((new DOMXPath($svg))->query('//*') as $element) {
if (!$element instanceof DOMElement || $element->namespaceURI !== 'http://www.w3.org/2000/svg'
|| !in_array($element->localName, $tags, true)) {
throw new RuntimeException('SVG 仅支持基础矢量元素。');
}
foreach ($element->attributes as $attribute) {
if ($attribute->namespaceURI !== null || !in_array($attribute->localName, $attributes, true)
|| !preg_match('/^[a-z0-9#.,%\s()+-]*$/iD', $attribute->value) || preg_match('/url\s*\(/i', $attribute->value)) {
throw new RuntimeException('SVG 包含不支持的属性或外部引用。');
}
}
}
return $svg->saveXML($svg->documentElement);
}
}
+101 -13
View File
@@ -22,9 +22,22 @@ final class Repository
return json_decode((string) $this->pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR); return json_decode((string) $this->pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
} }
public function pages(): array public function pages(bool $publishedOnly = false): array
{ {
return $this->pdo->query('SELECT slug, name, title, updated_at FROM pages ORDER BY rowid')->fetchAll(); $where = $publishedOnly ? " WHERE status = 'published'" : '';
return $this->pdo->query('SELECT slug, name, title, updated_at, status FROM pages' . $where . ' ORDER BY rowid')->fetchAll();
}
public function createPage(string $slug, string $name): void
{
$query = $this->pdo->prepare("INSERT OR IGNORE INTO pages (slug, name, title, description, heading, accent,
lead, image, alt, actions, quicklinks, partners, status, updated_at)
VALUES (?, ?, ?, '', ?, '', '', '', '', '[]', '[]', '[]', 'draft', ?)");
$query->execute([$slug, $name, $name . ' · 来笙', $name, self::now()]);
if ($query->rowCount() !== 1) {
throw new RuntimeException('此页面地址已存在。');
}
} }
public function page(string $slug): ?array public function page(string $slug): ?array
@@ -48,29 +61,104 @@ 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 savePage(string $slug, array $data, int $version): void public function savePage(string $slug, array $data, int $version, array $sections = []): void
{ {
$query = $this->pdo->prepare('UPDATE pages SET title = ?, description = ?, heading = ?, accent = ?, lead = ?, Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections): void {
image = ?, alt = ?, actions = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?'); $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 = ?');
$query->execute([ $query->execute([
$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'], Database::json($data['actions']), self::now(), $slug, $version, $data['image'], $data['alt'], $data['image_scale'], Database::json($data['actions']), Database::json($data['quicklinks']),
$data['status'], self::now(), $slug, $version,
]); ]);
self::checkVersion($query->rowCount()); self::checkVersion($query->rowCount());
foreach ($sections as $section) {
if ($section['version'] === null) {
self::insertSection($pdo, $slug, $section['key'], $section);
} else {
self::updateSection($pdo, $slug, $section['key'], $section, $section['version']);
}
}
});
} }
public function saveSection(string $page, string $key, array $data, int $version): void public function saveSection(string $page, string $key, array $data, int $version): void
{ {
Database::write(function (PDO $pdo) use ($page, $key, $data, $version): void { Database::write(function (PDO $pdo) use ($page, $key, $data, $version): void {
$query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, version = version + 1 self::updateSection($pdo, $page, $key, $data, $version);
WHERE page_slug = ? AND key = ? AND version = ?'); self::touchPage($pdo, $page);
$query->execute([$data['title'], $data['lead'], $data['body'], $page, $key, $version]);
self::checkVersion($query->rowCount());
$query = $pdo->prepare('UPDATE pages SET updated_at = ? WHERE slug = ?');
$query->execute([self::now(), $page]);
}); });
} }
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 = ?, version = version + 1
WHERE page_slug = ? AND key = ? AND version = ?');
$query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $page, $key, $version]);
self::checkVersion($query->rowCount());
}
public function createSection(string $page, string $key, string $title, string $style, string $body): void
{
Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body): void {
self::insertSection($pdo, $page, $key, compact('title', 'style', 'body') + ['lead' => '']);
self::touchPage($pdo, $page, structureChanged: true);
});
}
private static function insertSection(PDO $pdo, string $page, string $key, array $data): void
{
$query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, position)
SELECT ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?');
$query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $page]);
if ($query->rowCount() !== 1) {
throw new RuntimeException('此区块锚点已被使用。');
}
}
public function arrangeSection(string $page, string $key, string $operation, int $version, int $pageVersion): void
{
Database::write(function (PDO $pdo) use ($page, $key, $operation, $version, $pageVersion): void {
$current = $pdo->prepare('SELECT version FROM pages WHERE slug = ?');
$current->execute([$page]);
$revision = $current->fetchColumn();
self::checkVersion($revision !== false && (int) $revision === $pageVersion ? 1 : 0);
if ($operation === 'delete') {
$query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?');
$query->execute([$page, $key, $version]);
self::checkVersion($query->rowCount());
self::touchPage($pdo, $page, structureChanged: true);
return;
}
$query = $pdo->prepare('SELECT key, version FROM sections WHERE page_slug = ? ORDER BY position, key');
$query->execute([$page]);
$revisions = $query->fetchAll(PDO::FETCH_KEY_PAIR);
if (!array_key_exists($key, $revisions)) {
throw new RuntimeException('找不到该区块。');
}
self::checkVersion((int) $revisions[$key] === $version ? 1 : 0);
$keys = array_map('strval', array_keys($revisions));
$index = array_search($key, $keys, true);
$other = $index + ($operation === 'up' ? -1 : 1);
if (!isset($keys[$other])) {
return;
}
[$keys[$index], $keys[$other]] = [$keys[$other], $keys[$index]];
$query = $pdo->prepare('UPDATE sections SET position = ? WHERE page_slug = ? AND key = ?');
foreach ($keys as $position => $section) {
$query->execute([$position, $page, $section]);
}
self::touchPage($pdo, $page, structureChanged: true);
});
}
private static function touchPage(PDO $pdo, string $slug, bool $structureChanged = false): void
{
$revision = $structureChanged ? ', version = version + 1' : '';
$pdo->prepare('UPDATE pages SET updated_at = ?' . $revision . ' WHERE slug = ?')->execute([self::now(), $slug]);
}
public function articles(?string $category = null, ?string $tag = null, bool $public = true, int $limit = 30, int $offset = 0): array public function articles(?string $category = null, ?string $tag = null, bool $public = true, int $limit = 30, int $offset = 0): array
{ {
$sql = 'SELECT * FROM articles WHERE 1 = 1'; $sql = 'SELECT * FROM articles WHERE 1 = 1';
+107
View File
@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use RuntimeException;
final class SiteDesign
{
public const DEFAULT_HEADER = [
'logo' => '/assets/wordmark.webp', 'alt' => 'Laysense 来笙',
'links' => [['/', '首页'], ['/services', '产品与服务'], ['/articles', '动态'], ['/#about', '关于来笙']],
'button' => ['#contact', '联系来笙'],
];
public const DEFAULT_FOOTER = [
'logo' => '/assets/wordmark.webp', 'alt' => '来笙 Laysense',
'products_title' => '产品与服务',
'products' => [['/pagepan', 'PAGEPAN 小飞页'], ['/highspeaker', 'HighSpeaker DNS'], ['/sc', '软著代理服务'], ['/shnu-sc', 'SHNU 学生软著服务']],
'company_title' => '公司',
'company' => [['/#about', '关于来笙'], ['/articles', '来笙动态'], ['https://git.laysense.com', 'Laysense Git'], ['https://www.layso.de', 'LaySo']],
'phones' => [['tel:+16699004532', '+1 (669) 900 4532'], ['tel:+85257012856', '+852 5701 2856']],
];
public static function parseLinks(string $value): array
{
$links = [];
foreach (preg_split('/\R/u', $value, -1, PREG_SPLIT_NO_EMPTY) as $line) {
if (trim($line) === '') {
continue;
}
[$label, $url] = array_map('trim', array_pad(explode('|', $line, 2), 2, ''));
if ($label === '' || mb_strlen($label) > 70 || strlen($url) > 1000 || !Html::url($url) || count($links) >= 20) {
throw new RuntimeException('每行填写「文案 | 链接」,最多 20 条。');
}
$links[] = [$url, $label];
}
return $links;
}
public static function linkText(array $links): string
{
return implode("\n", array_map(static fn (array $link): string => $link[1] . ' | ' . $link[0], $links));
}
public static function saveSettings(string $part, array $data, int $version): void
{
Database::write(function (PDO $pdo) use ($part, $data, $version): void {
$site = json_decode((string) $pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
if (($site['revisions'][$part] ?? 0) !== $version) {
throw new RuntimeException('设置已在另一页面更新。请复制本次修改后重新打开。');
}
$site[$part] = $data;
$site['revisions'][$part] = $version + 1;
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
});
}
public static function catalog(): array
{
return Database::connect()->query('SELECT * FROM catalog ORDER BY position, id')->fetchAll();
}
public static function product(int $id): ?array
{
$query = Database::connect()->prepare('SELECT * FROM catalog WHERE id = ?');
$query->execute([$id]);
return $query->fetch() ?: null;
}
public static function saveProduct(?int $id, array $product, int $version): int
{
$pdo = Database::connect();
$fields = ['name', 'category', 'body', 'image', 'alt', 'url', 'label', 'extra_url', 'extra_label', 'position'];
$values = array_map(static fn (string $field) => $product[$field], $fields);
if ($id === null) {
$pdo->prepare('INSERT INTO catalog (' . implode(', ', $fields) . ') VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
->execute($values);
return (int) $pdo->lastInsertId();
}
$query = $pdo->prepare('UPDATE catalog SET ' . implode(' = ?, ', $fields) . ' = ?, version = version + 1 WHERE id = ? AND version = ?');
$query->execute([...$values, $id, $version]);
self::checkProduct($query->rowCount());
return $id;
}
public static function deleteProduct(int $id, int $version): void
{
$query = Database::connect()->prepare('DELETE FROM catalog WHERE id = ? AND version = ?');
$query->execute([$id, $version]);
self::checkProduct($query->rowCount());
}
private static function checkProduct(int $count): void
{
if ($count !== 1) {
throw new RuntimeException('此项目已在另一页面更新,请重新打开。');
}
}
}
+8 -4
View File
@@ -10,17 +10,21 @@ final class View
{ {
public static function render(string $template, array $data, int $status = 200, bool $admin = false): Response public static function render(string $template, array $data, int $status = 200, bool $admin = false): Response
{ {
$cdn = $admin || !empty($data['previewMode']) ? '' : ($data['site']['cdn']['origin'] ?? '');
$data['cdn'] = $cdn;
$html = self::fragment($template, $data); $html = self::fragment($template, $data);
$page = self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]); $page = Assets::rewrite(self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]), $cdn);
$assetSources = $cdn === '' ? "'self'" : "'self' " . $cdn;
$headers = [ $headers = [
'Content-Type' => 'text/html; charset=utf-8', 'Content-Type' => 'text/html; charset=utf-8',
'X-Content-Type-Options' => 'nosniff', 'X-Content-Type-Options' => 'nosniff',
'Referrer-Policy' => 'strict-origin-when-cross-origin', 'Referrer-Policy' => 'strict-origin-when-cross-origin',
'X-Frame-Options' => 'DENY', 'X-Frame-Options' => !empty($data['previewMode']) ? 'SAMEORIGIN' : 'DENY',
'Content-Security-Policy' => "default-src 'self'; img-src 'self' https:; media-src 'self' https:; " 'Content-Security-Policy' => "default-src 'self'; img-src 'self' https:; media-src 'self' https:; "
. "style-src 'self'; script-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'; object-src 'none'", . "style-src $assetSources; script-src $assetSources; font-src $assetSources; frame-src 'self'; frame-ancestors "
. (!empty($data['previewMode']) ? "'self'" : "'none'") . "; form-action 'self'; base-uri 'none'; object-src 'none'",
]; ];
if ($admin) { if ($admin || !empty($data['previewMode'])) {
$headers['Cache-Control'] = 'no-store'; $headers['Cache-Control'] = 'no-store';
$headers['X-Robots-Tag'] = 'noindex, nofollow'; $headers['X-Robots-Tag'] = 'noindex, nofollow';
} elseif (($data['noindex'] ?? false) || $status >= 400) { } elseif (($data['noindex'] ?? false) || $status >= 400) {
+80 -17
View File
@@ -8,12 +8,13 @@ use App\Content\Database;
use App\Content\Html; use App\Content\Html;
use App\Content\Passwords; use App\Content\Passwords;
use App\Content\Repository; use App\Content\Repository;
use App\Content\SiteDesign;
use App\Content\View; use App\Content\View;
use App\Http\Request; use App\Http\Request;
use RuntimeException; use RuntimeException;
use support\Response; use support\Response;
final class AdminController class AdminController
{ {
private ?array $user = null; private ?array $user = null;
@@ -189,6 +190,11 @@ final class AdminController
foreach (['title', 'description', 'heading', 'accent', 'lead', 'image', 'alt'] as $field) { foreach (['title', 'description', 'heading', 'accent', 'lead', 'image', 'alt'] as $field) {
$data[$field] = $this->input($request, $field); $data[$field] = $this->input($request, $field);
} }
$data['name'] = $request->post('name') === null ? $page['name'] : $this->input($request, 'name');
$data['status'] = $request->post('status') === null || $slug === 'home' ? $page['status'] : $this->input($request, 'status');
$scale = $this->input($request, 'image_scale');
$data['image_scale'] = $request->post('image_scale') === null ? (int) $page['image_scale']
: (ctype_digit($scale) ? (int) $scale : -1);
$data['actions'] = []; $data['actions'] = [];
$validButtons = true; $validButtons = true;
foreach ([1, 2] as $index) { foreach ([1, 2] as $index) {
@@ -202,14 +208,18 @@ final class AdminController
} }
$page = array_replace($page, $data, ['version' => $this->version($request)]); $page = array_replace($page, $data, ['version' => $this->version($request)]);
try { try {
if ($data['title'] === '' || mb_strlen($data['title']) > 160 || $data['quicklinks'] = $request->post('quicklinks') === null ? $page['quicklinks'] : SiteDesign::parseLinks($this->input($request, 'quicklinks'));
$data['description'] === '' || mb_strlen($data['description']) > 300 || if ($data['name'] === '' || mb_strlen($data['name']) > 100 || !in_array($data['status'], ['draft', 'published'], true)
|| $data['title'] === '' || mb_strlen($data['title']) > 160 ||
($data['status'] === 'published' && $data['description'] === '') || mb_strlen($data['description']) > 300 ||
$data['heading'] === '' || mb_strlen($data['heading'] . $data['accent']) > 110 || $data['heading'] === '' || mb_strlen($data['heading'] . $data['accent']) > 110 ||
mb_strlen($data['lead']) > 600 || mb_strlen($data['alt']) > 200 || mb_strlen($data['lead']) > 600 || mb_strlen($data['alt']) > 200 ||
!in_array($data['image_scale'], [0, 25, 40, 50, 60, 75, 85, 100], true) ||
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('请检查页面标题、说明、图片地址和按钮链接。');
} }
$repo->savePage($slug, $data, $this->version($request)); $sections = $this->canvasSections($request->post('canvas_sections', ''), $page['sections']);
$repo->savePage($slug, $data, $this->version($request), $sections);
return $this->success($request, '/admin/pages/' . $slug . '?saved=1'); return $this->success($request, '/admin/pages/' . $slug . '?saved=1');
} catch (RuntimeException $exception) { } catch (RuntimeException $exception) {
@@ -218,7 +228,7 @@ final class AdminController
} }
return $this->render($request, 'admin-page', [ return $this->render($request, 'admin-page', [
'title' => '编辑 ' . $page['name'], 'page' => $page, 'error' => $error, 'saved' => $request->get('saved') === '1', 'title' => '编辑 ' . $page['name'], 'page' => $page, 'wideAdmin' => true, 'error' => $error, 'saved' => $request->get('saved') === '1',
], $error !== '' ? 422 : 200); ], $error !== '' ? 422 : 200);
} }
@@ -232,17 +242,17 @@ final class AdminController
if (!$section) { if (!$section) {
return $this->error($request, '找不到此区块。', 404); return $this->error($request, '找不到此区块。', 404);
} }
$savedStyle = $section['style'];
$error = ''; $error = '';
if ($request->method() === 'POST') { if ($request->method() === 'POST') {
$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'),
]; ];
$section = array_replace($section, $data, ['version' => $this->version($request)]); $section = array_replace($section, $data, ['version' => $this->version($request)]);
try { try {
if ($data['title'] === '' || mb_strlen($data['title']) > 100 || mb_strlen($data['lead']) > 500 || strlen($data['body']) > 300000) { $this->checkSection($data, $savedStyle);
throw new RuntimeException('请填写区块标题,并检查说明及正文长度。');
}
$data['body'] = Html::sanitize($data['body']); $data['body'] = Html::sanitize($data['body']);
$repo->saveSection($slug, $key, $data, $this->version($request)); $repo->saveSection($slug, $key, $data, $this->version($request));
@@ -253,10 +263,63 @@ final class AdminController
} }
return $this->render($request, 'admin-section', [ return $this->render($request, 'admin-section', [
'title' => '编辑区块', 'section' => $section, 'error' => $error, 'saved' => $request->get('saved') === '1', 'title' => '编辑区块', 'section' => $section, 'savedStyle' => $savedStyle, 'error' => $error, 'saved' => $request->get('saved') === '1',
], $error !== '' ? 422 : 200); ], $error !== '' ? 422 : 200);
} }
private function canvasSections(mixed $payload, array $sections): array
{
if ($payload === '') {
return [];
}
$changes = is_string($payload) ? json_decode($payload, true) : null;
if (!is_array($changes) || !array_is_list($changes) || count($changes) > count($sections) + 50) {
throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。');
}
$available = array_column($sections, null, 'key');
$updates = [];
foreach ($changes as $change) {
$key = $change['key'] ?? null;
$version = $change['version'] ?? null;
$fields = $change['fields'] ?? null;
$isNew = is_array($change) && array_key_exists('version', $change) && $version === null;
if (!is_string($key) || isset($updates[$key]) || !is_array($fields) || $fields === []
|| ($isNew ? (isset($available[$key]) || !preg_match('/^block-[a-f0-9]{32}$/D', $key))
: (!isset($available[$key]) || !is_int($version) || $version !== (int) $available[$key]['version']))) {
throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。');
}
$section = $available[$key] ?? ['key' => $key, 'title' => '', 'lead' => '', 'body' => '', 'style' => 'plain'];
foreach ($fields as $field => $value) {
if (!in_array($field, ['title', 'lead', 'body'], true)) {
throw new RuntimeException('画布内容无效。');
}
if ($field === 'body' && is_array($value)) {
$value = Html::applyCanvasEdits($section['body'], $value);
}
if (!is_string($value)) {
throw new RuntimeException('画布内容无效。');
}
$section[$field] = trim($value);
}
$this->checkSection($section, $section['style']);
if (isset($fields['body'])) {
$section['body'] = Html::sanitize($section['body']);
}
$section['version'] = $version;
$updates[$key] = $section;
}
return $updates;
}
private function checkSection(array $section, string $savedStyle): void
{
if ($section['title'] === '' || mb_strlen($section['title']) > 100 || mb_strlen($section['lead']) > 500
|| strlen($section['body']) > 300000 || !in_array($section['style'], [$savedStyle, 'plain', 'tinted'], true)) {
throw new RuntimeException('请填写区块标题,并检查说明及正文长度。');
}
}
public function preview(Request $request): Response public function preview(Request $request): Response
{ {
if ($failure = $this->guard($request)) { if ($failure = $this->guard($request)) {
@@ -274,7 +337,7 @@ final class AdminController
], $html); ], $html);
} }
private function guard(Request $request): ?Response protected function guard(Request $request): ?Response
{ {
if (!$this->signedIn($request)) { if (!$this->signedIn($request)) {
return $request->isAjax() return $request->isAjax()
@@ -340,7 +403,7 @@ final class AdminController
return is_string($token) && hash_equals($token, $this->input($request, 'csrf')); return is_string($token) && hash_equals($token, $this->input($request, 'csrf'));
} }
private function input(Request $request, string $key, bool $trimValue = true): string protected function input(Request $request, string $key, bool $trimValue = true): string
{ {
$value = $request->post($key, ''); $value = $request->post($key, '');
if (!is_string($value) || !mb_check_encoding($value, 'UTF-8')) { if (!is_string($value) || !mb_check_encoding($value, 'UTF-8')) {
@@ -350,7 +413,7 @@ final class AdminController
return $trimValue ? trim($value) : $value; return $trimValue ? trim($value) : $value;
} }
private function version(Request $request): int protected function version(Request $request): int
{ {
$version = $this->input($request, 'version'); $version = $this->input($request, 'version');
@@ -372,7 +435,7 @@ final class AdminController
return $data; return $data;
} }
private function validationMessage(RuntimeException $exception): string protected function validationMessage(RuntimeException $exception): string
{ {
if ($exception instanceof \PDOException) { if ($exception instanceof \PDOException) {
error_log($exception->getMessage()); error_log($exception->getMessage());
@@ -383,12 +446,12 @@ final class AdminController
return $exception->getMessage(); return $exception->getMessage();
} }
private function success(Request $request, string $path): Response protected function success(Request $request, string $path): Response
{ {
return $request->isAjax() ? $this->json(['redirect' => $path]) : View::redirect($path); return $request->isAjax() ? $this->json(['redirect' => $path]) : View::redirect($path);
} }
private function json(array $payload, int $status = 200): Response protected function json(array $payload, int $status = 200): Response
{ {
return new Response($status, [ return new Response($status, [
'Content-Type' => 'application/json; charset=utf-8', 'Content-Type' => 'application/json; charset=utf-8',
@@ -398,7 +461,7 @@ final class AdminController
], Database::json($payload)); ], Database::json($payload));
} }
private function render(Request $request, string $view, array $data, int $status = 200): Response protected function render(Request $request, string $view, array $data, int $status = 200): Response
{ {
$token = $this->token($request); $token = $this->token($request);
if ($request->isAjax() && $status >= 400) { if ($request->isAjax() && $status >= 400) {
@@ -411,7 +474,7 @@ final class AdminController
return View::render($view, $data + ['token' => $token, 'user' => $this->user], $status, true); return View::render($view, $data + ['token' => $token, 'user' => $this->user], $status, true);
} }
private function error(Request $request, string $message, int $status): Response protected function error(Request $request, string $message, int $status): Response
{ {
return $this->render($request, 'admin-error', ['title' => $message], $status); return $this->render($request, 'admin-error', ['title' => $message], $status);
} }
+45
View File
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\Media;
use support\Request;
use support\Response;
final class MediaController
{
public function file(Request $request, string $name): Response
{
$media = Media::find($name);
$path = Media::directory() . '/' . $name;
if (!$media || !is_file($path)) {
return new Response(404);
}
$length = (int) $media['size'];
$headers = [
'Content-Type' => $media['mime'], 'X-Content-Type-Options' => 'nosniff',
'Content-Security-Policy' => "default-src 'none'; sandbox",
'Cache-Control' => 'public, max-age=31536000, immutable',
'Access-Control-Allow-Origin' => '*', 'Accept-Ranges' => 'bytes',
];
$range = $request->header('range');
if ($range === null) {
return (new Response(200, $headers + ['Content-Length' => (string) $length]))->withFile($path);
}
if (!preg_match('/^bytes=(\d*)-(\d*)$/D', $range, $parts) || $parts[1] === '' && $parts[2] === '') {
return new Response(416, $headers + ['Content-Range' => "bytes */$length"]);
}
$start = $parts[1] === '' ? max(0, $length - (int) $parts[2]) : (int) $parts[1];
$end = $parts[1] === '' || $parts[2] === '' ? $length - 1 : min($length - 1, (int) $parts[2]);
if ($end < $start) {
return new Response(416, $headers + ['Content-Range' => "bytes */$length"]);
}
$count = $end - $start + 1;
return (new Response(206, $headers + ['Content-Length' => (string) $count, 'Content-Range' => "bytes $start-$end/$length"]))
->withFile($path, $start, $count);
}
}
+24 -3
View File
@@ -6,6 +6,7 @@ namespace App\Controller;
use App\Content\Html; use App\Content\Html;
use App\Content\Repository; use App\Content\Repository;
use App\Content\SiteDesign;
use App\Content\View; use App\Content\View;
use support\Request; use support\Request;
use support\Response; use support\Response;
@@ -21,9 +22,15 @@ final class SiteController
{ {
$repo = new Repository(); $repo = new Repository();
$page = $repo->page($slug); $page = $repo->page($slug);
if (!$page) { if (!$page || $page['status'] !== 'published' || $slug === 'home' && $request->path() !== '/') {
return $this->missing($request); return $this->missing($request);
} }
return $this->renderPage($repo, $page);
}
public function renderPage(Repository $repo, array $page, bool $preview = false, bool $canvas = false): Response
{
$slug = $page['slug'];
$isHome = $slug === 'home'; $isHome = $slug === 'home';
return View::render('page', [ return View::render('page', [
@@ -35,6 +42,17 @@ final class SiteController
'socialImage' => $page['image'], 'socialImage' => $page['image'],
'socialAlt' => $page['alt'], 'socialAlt' => $page['alt'],
'articles' => $isHome ? $repo->articles(limit: 3) : [], 'articles' => $isHome ? $repo->articles(limit: 3) : [],
'previewMode' => $preview, 'canvas' => $preview && $canvas, 'noindex' => $preview,
]);
}
public function services(Request $request): Response
{
return View::render('services', [
'site' => (new Repository())->site(), 'path' => '/services',
'title' => '产品与服务 · 来笙 Laysense',
'description' => '浏览来笙的建站工具、智能 DNS 和软件著作权服务。',
'products' => SiteDesign::catalog(),
]); ]);
} }
@@ -118,7 +136,8 @@ 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(); $pages = $repo->pages(publishedOnly: true);
$pages[] = ['slug' => 'services', 'updated_at' => null];
if ($repo->articles(limit: 1)) { if ($repo->articles(limit: 1)) {
$pages[] = ['slug' => 'articles', 'updated_at' => null]; $pages[] = ['slug' => 'articles', 'updated_at' => null];
} }
@@ -144,7 +163,9 @@ final class SiteController
$path = $request->path(); $path = $request->path();
if ($request->method() === 'GET' && strlen($path) > 1 && str_ends_with($path, '/')) { if ($request->method() === 'GET' && strlen($path) > 1 && str_ends_with($path, '/')) {
$normal = rtrim($path, '/'); $normal = rtrim($path, '/');
if (preg_match('~^/(?:pagepan|highspeaker|sc|shnu-sc|articles(?:/[a-z0-9-]+){0,2})$~D', $normal)) { $single = preg_match('~^/[a-z0-9-]+$~D', $normal);
$known = $single && ((new Repository())->page(substr($normal, 1))['status'] ?? null) === 'published' && $normal !== '/home';
if ($known || $normal === '/services' || preg_match('~^/articles(?:/[a-z0-9-]+){0,2}$~D', $normal)) {
$query = $request->queryString(); $query = $request->queryString();
return View::redirect($normal . ($query !== '' ? '?' . $query : ''), 301); return View::redirect($normal . ($query !== '' ? '?' . $query : ''), 301);
+280
View File
@@ -0,0 +1,280 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\Assets;
use App\Content\BlockTemplates;
use App\Content\Html;
use App\Content\Media;
use App\Content\Repository;
use App\Content\SiteDesign;
use App\Http\Request;
use RuntimeException;
use support\Response;
use Webman\Http\UploadFile;
final class StudioController extends AdminController
{
public function newPage(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$data = ['title' => '新建页面', 'name' => '', 'slug' => '', 'error' => ''];
if ($request->method() === 'POST') {
$data['name'] = $this->input($request, 'name');
$data['slug'] = $this->input($request, 'slug');
try {
if (!$this->slug($data['slug']) || in_array($data['slug'], ['admin', 'assets', 'articles', 'home', 'services', 'news', 'main', 'favicon'], true)
|| $data['name'] === '' || mb_strlen($data['name']) > 100) {
throw new RuntimeException('请填写页面名称及可用的网址标识。');
}
(new Repository())->createPage($data['slug'], $data['name']);
return $this->success($request, '/admin/pages/' . $data['slug']);
} catch (RuntimeException $error) {
$data['error'] = $this->validationMessage($error);
}
}
return $this->render($request, 'studio-new-page', $data, $data['error'] === '' ? 200 : 422);
}
public function previewPage(Request $request, string $slug): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$repo = new Repository();
$page = $repo->page($slug);
return $page ? (new SiteController())->renderPage($repo, $page, true, $request->get('canvas') === '1') : $this->error($request, '找不到此页面。', 404);
}
public function blocks(Request $request, string $slug): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$repo = new Repository();
if (!$repo->page($slug)) {
return $this->error($request, '找不到此页面。', 404);
}
$action = $this->input($request, 'operation');
$key = $this->input($request, 'key');
try {
if (!$this->slug($key) || in_array($key, ['preview', 'home', 'contact', 'main-content', 'blog', 'partners', 'supported-projects'], true)) {
throw new RuntimeException('区块锚点不可用。');
}
if ($action === 'create') {
$preset = BlockTemplates::find($this->input($request, 'preset'));
if ($preset === null) {
throw new RuntimeException('请选择区块类型。');
}
$repo->createSection($slug, $key, $preset[0], 'plain', $preset[1]);
return $this->success($request, "/admin/pages/$slug/$key");
}
if (!in_array($action, ['up', 'down', 'delete'], true)) {
throw new RuntimeException('操作不可用。');
}
$pageVersion = $this->input($request, 'page_version');
$repo->arrangeSection($slug, $key, $action, $this->version($request), ctype_digit($pageVersion) ? (int) $pageVersion : -1);
return $this->success($request, "/admin/pages/$slug#blocks");
} catch (RuntimeException $error) {
return $this->error($request, $this->validationMessage($error), 422);
}
}
public function settings(Request $request, string $part): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$site = (new Repository())->site();
$defaults = match ($part) {
'header' => SiteDesign::DEFAULT_HEADER,
'footer' => SiteDesign::DEFAULT_FOOTER + array_intersect_key($site, array_flip(['name', 'address', 'email', 'copyright', 'registration', 'terms'])),
'cdn' => ['origin' => ''],
};
$config = ($site[$part] ?? []) + $defaults;
$version = $site['revisions'][$part] ?? 0;
$error = '';
if ($request->method() === 'POST') {
try {
$config = $this->settingsInput($request, $part, $defaults);
SiteDesign::saveSettings($part, $config, $this->version($request));
return $this->success($request, '/admin/settings/' . $part . '?saved=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
$version = $this->version($request);
}
}
return $this->render($request, 'studio-settings', [
'part' => $part, 'config' => $config, 'revision' => $version, 'error' => $error, 'saved' => $request->get('saved') === '1',
'title' => ['header' => '页头', 'footer' => '页脚', 'cdn' => '静态资源 CDN'][$part],
], $error === '' ? 200 : 422);
}
public function catalog(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
return $this->render($request, 'studio-catalog', ['title' => '产品与服务', 'products' => SiteDesign::catalog()]);
}
public function product(Request $request, ?string $id = null): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$fields = ['name', 'category', 'body', 'image', 'alt', 'url', 'label', 'extra_url', 'extra_label', 'position'];
$product = $id !== null ? SiteDesign::product((int) $id) : array_fill_keys($fields, '') + ['version' => 0];
if (!$product) {
return $this->error($request, '找不到此产品或服务。', 404);
}
$error = '';
if ($request->method() === 'POST') {
try {
if ($id !== null && $this->input($request, 'operation') === 'delete') {
SiteDesign::deleteProduct((int) $id, $this->version($request));
return $this->success($request, '/admin/catalog');
}
foreach ($fields as $field) {
$product[$field] = $this->input($request, $field);
}
$product['version'] = $this->version($request);
$this->checkProduct($product);
$product['body'] = Html::sanitize($product['body']);
$savedId = SiteDesign::saveProduct($id === null ? null : (int) $id, $product, $product['version']);
return $this->success($request, '/admin/catalog/' . $savedId . '?saved=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
}
}
return $this->render($request, 'studio-product', [
'title' => $id === null ? '添加产品或服务' : '编辑产品或服务', 'product' => $product,
'id' => $id, 'error' => $error, 'saved' => $request->get('saved') === '1',
], $error === '' ? 200 : 422);
}
public function media(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$error = '';
if ($request->method() === 'POST') {
try {
$file = $request->file('file');
if (!$file instanceof UploadFile || !$file->isValid()) {
throw new RuntimeException('请选择要上传的文件。');
}
$label = $this->input($request, 'label') ?: mb_substr((string) $file->getUploadName(), 0, 160);
if (mb_strlen($label) > 160) {
throw new RuntimeException('资源名称最多 160 个字符。');
}
Media::upload($file, $label);
return $this->success($request, '/admin/media?uploaded=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
}
}
return $this->render($request, 'studio-media', [
'title' => '媒体库', 'files' => Media::all(true), 'error' => $error, 'saved' => $request->get('uploaded') === '1',
], $error === '' ? 200 : 422);
}
public function mediaOptions(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
return $this->json(['files' => Media::all()]);
}
public function mediaMeta(Request $request, string $name): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$label = $this->input($request, 'label');
if (!Media::find($name)) {
return $this->error($request, '找不到此资源。', 404);
}
if ($label === '' || mb_strlen($label) > 160) {
return $this->error($request, '请输入资源名称,最多 160 个字符。', 422);
}
Media::update($name, $label, $this->input($request, 'archived') === '1');
return $this->success($request, '/admin/media');
}
private function settingsInput(Request $request, string $part, array $defaults): array
{
if ($part === 'cdn') {
return ['origin' => Assets::cdn($this->input($request, 'origin'))];
}
$result = [];
foreach ($defaults as $key => $default) {
$input = $this->input($request, $key);
if (is_array($default)) {
$result[$key] = SiteDesign::parseLinks($input);
if ($key === 'button') {
if (count($result[$key]) > 1) {
throw new RuntimeException('页头按钮只接受一条链接。');
}
$result[$key] = $result[$key][0] ?? [];
}
} else {
if (mb_strlen($input) > 1000) {
throw new RuntimeException('设置字段过长。');
}
$result[$key] = $input;
}
}
if ($result['logo'] !== '' && !Html::url($result['logo'], true)) {
throw new RuntimeException('请输入有效的标志图片地址。');
}
if ($part === 'footer' && ($result['name'] === '' || ($result['email'] !== '' && !filter_var($result['email'], FILTER_VALIDATE_EMAIL)))) {
throw new RuntimeException('请填写公司名称及有效的联系邮箱。');
}
return $result;
}
private function checkProduct(array $item): void
{
if ($item['name'] === '' || mb_strlen($item['name']) > 100 || $item['category'] === '' || mb_strlen($item['category']) > 70
|| strlen($item['body']) > 300000 || strlen($item['image']) > 1000 || mb_strlen($item['alt']) > 200
|| ($item['image'] !== '' && !Html::url($item['image'], true)) || !preg_match('/^-?\d{1,6}$/D', $item['position'])) {
throw new RuntimeException('请检查名称、分类、简介、封面及排序字段。');
}
foreach ([['url', 'label'], ['extra_url', 'extra_label']] as [$href, $label]) {
if ($href === 'extra_url' && $item[$href] === '' && $item[$label] === '') {
continue;
}
if (strlen($item[$href]) > 1000 || !Html::url($item[$href]) || $item[$label] === '' || mb_strlen($item[$label]) > 70) {
throw new RuntimeException('请填写按钮文案和有效链接。');
}
}
}
private function slug(string $value): bool
{
return strlen($value) <= 70 && preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/D', $value) === 1;
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Middleware;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
final class PublicAssets implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
$response = $handler($request);
$path = $request->path();
if (str_starts_with($path, '/assets/')) {
$response->withHeader('Access-Control-Allow-Origin', '*');
if ($path === '/assets/jquery-4.0.0.min.js') {
$response->withHeader('Cache-Control', 'public, max-age=31536000, immutable');
}
}
return $response;
}
}
+3 -2
View File
@@ -5,14 +5,15 @@ $e = View::escape(...);
?> ?>
<header class="admin-heading"> <header class="admin-heading">
<div><h1>内容管理</h1><p>管理网站页面、文章、公告和产品动态。</p></div> <div><h1>内容管理</h1><p>管理网站页面、文章、公告和产品动态。</p></div>
<a class="button button-primary" href="/admin/articles/new">新建文章</a> <div class="actions"><a class="button button-primary" href="/admin/new-page">新建页面</a>
<a class="button button-outline" href="/admin/articles/new">新建文章</a></div>
</header> </header>
<section class="admin-panel" aria-labelledby="pages-title"> <section class="admin-panel" aria-labelledby="pages-title">
<h2 id="pages-title">网站页面</h2> <h2 id="pages-title">网站页面</h2>
<ul class="admin-list"> <ul class="admin-list">
<?php foreach ($pages as $page): ?> <?php foreach ($pages as $page): ?>
<li> <li>
<div><strong><?= $e($page['name']) ?></strong><small><?= $e($page['slug'] === 'home' ? '/' : '/' . $page['slug']) ?></small></div> <div><strong><?= $e($page['name']) ?></strong><small><?= $e($page['slug'] === 'home' ? '/' : '/' . $page['slug']) ?> · <?= $page['status'] === 'draft' ? '草稿' : '已发布' ?></small></div>
<a class="button button-outline" href="/admin/pages/<?= $e($page['slug']) ?>">编辑页面</a> <a class="button button-outline" href="/admin/pages/<?= $e($page['slug']) ?>">编辑页面</a>
</li> </li>
<?php endforeach ?> <?php endforeach ?>
+11 -1
View File
@@ -1,5 +1,6 @@
<?php <?php
use App\Content\View; use App\Content\View;
use App\Content\Html;
$e = View::escape(...); $e = View::escape(...);
?> ?>
@@ -12,11 +13,20 @@ $e = View::escape(...);
<button type="button" data-insert="list">列表</button> <button type="button" data-insert="list">列表</button>
<button type="button" data-insert="link">链接</button> <button type="button" data-insert="link">链接</button>
</div> </div>
<?php if ($format === 'html'): ?>
<button type="button" data-rich-media>插入媒体</button>
<button type="button" data-source-toggle aria-pressed="false">HTML 源码</button>
<?php else: ?>
<button data-preview-button type="button" aria-controls="editor-preview" aria-expanded="false">预览正文</button> <button data-preview-button type="button" aria-controls="editor-preview" aria-expanded="false">预览正文</button>
<?php endif ?>
</div> </div>
<?php if ($format === 'html'): ?>
<div class="rich studio-rich" contenteditable="true" role="textbox" aria-multiline="true" aria-label="可视化正文" data-rich-canvas hidden><?= Html::sanitize($body) ?></div>
<p class="field-note" data-rich-status role="status" hidden></p>
<?php endif ?>
<textarea id="editor-text" name="body" rows="15" spellcheck="false"><?= $e($body) ?></textarea> <textarea id="editor-text" name="body" rows="15" spellcheck="false"><?= $e($body) ?></textarea>
<?php if ($format === 'html'): ?> <?php if ($format === 'html'): ?>
<p class="field-note">支持段落、标题、链接、图片、列表、表格和折叠问答。保存时会清理脚本、内联样式等标签或属性。</p> <p class="field-note">可以直接编辑文字,插入链接、图片、音视频。复杂区块可切换到 HTML 源码调整。</p>
<?php endif ?> <?php endif ?>
<div class="editor-preview rich prose" id="editor-preview" aria-live="polite" hidden></div> <div class="editor-preview rich prose" id="editor-preview" aria-live="polite" hidden></div>
</div> </div>
+1 -1
View File
@@ -1,3 +1,3 @@
<?php use App\Content\View; ?> <?php use App\Content\View; ?>
<?php if ($error): ?><p class="feedback error" role="alert"><?= View::escape($error) ?></p><?php endif ?> <?php if ($error): ?><p class="feedback error" role="alert"><?= View::escape($error) ?></p><?php endif ?>
<?php if ($saved && !$error): ?><p class="feedback success" role="status">已保存。</p><?php endif ?> <?php if ($saved && !$error): ?><p class="feedback success" data-save-confirmation role="status">已保存。</p><?php endif ?>
+14 -1
View File
@@ -15,6 +15,7 @@ $e = View::escape(...);
<link rel="stylesheet" href="/assets/admin.css"> <link rel="stylesheet" href="/assets/admin.css">
<script src="/assets/jquery-4.0.0.min.js" defer></script> <script src="/assets/jquery-4.0.0.min.js" defer></script>
<script src="/assets/admin.js" defer></script> <script src="/assets/admin.js" defer></script>
<script src="/assets/studio.js" defer></script>
</head> </head>
<body class="admin-body"> <body class="admin-body">
<a class="skip-link" href="#admin-content">跳到内容</a> <a class="skip-link" href="#admin-content">跳到内容</a>
@@ -25,6 +26,9 @@ $e = View::escape(...);
<nav aria-label="后台导航"> <nav aria-label="后台导航">
<a href="/admin">页面</a> <a href="/admin">页面</a>
<a href="/admin/articles">文章</a> <a href="/admin/articles">文章</a>
<a href="/admin/media">媒体库</a>
<a href="/admin/catalog">产品与服务</a>
<a href="/admin/settings/header">网站设置</a>
<a href="/admin/password">修改密码</a> <a href="/admin/password">修改密码</a>
<a href="/">访问网站</a> <a href="/">访问网站</a>
<form method="post" action="/admin/logout"> <form method="post" action="/admin/logout">
@@ -37,6 +41,15 @@ $e = View::escape(...);
<?php endif ?> <?php endif ?>
</div> </div>
</header> </header>
<main class="admin-wrap admin-main" id="admin-content"><?= $content ?></main> <main class="admin-wrap admin-main<?= !empty($wideAdmin) ? ' admin-wide' : '' ?>" id="admin-content"><?= $content ?></main>
<?php if ($user): ?>
<dialog class="media-picker" id="media-picker" aria-labelledby="picker-heading">
<header class="admin-heading compact"><h2 id="picker-heading">从媒体库选择</h2><button class="button button-outline" type="button" data-close-picker>关闭</button></header>
<label>查找资源<input type="search" data-media-query placeholder="搜索文件名或资源路径"></label>
<p data-picker-status role="status"></p>
<div class="picker-grid" data-picker-items></div>
<a class="back-link" href="/admin/media" target="_blank" rel="noopener">打开媒体库上传</a>
</dialog>
<?php endif ?>
</body> </body>
</html> </html>
+142 -28
View File
@@ -1,46 +1,160 @@
<?php <?php
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'];
$path = $slug === 'home' ? '/' : '/' . $slug;
$previewUrl = '/admin/pages/' . $slug . '/preview';
?> ?>
<a class="back-link" href="/admin">返回内容管理</a> <a class="back-link" href="/admin">返回页面</a>
<header class="admin-heading"> <header class="admin-heading">
<h1><?= $e($title) ?></h1> <div><h1><?= $e($title) ?></h1><p><?= $e($path) ?> · <?= $page['status'] === 'draft' ? '草稿' : '已发布' ?></p></div>
<a class="button button-outline" href="<?= $e($slug === 'home' ? '/' : '/' . $slug) ?>">查看公开页面</a> <div class="actions">
<?php if ($page['status'] === 'published'): ?><a class="button button-outline" href="<?= $e($path) ?>">公开页面</a><?php endif ?>
<a class="button button-outline" href="<?= $e($previewUrl) ?>" target="_blank" rel="noopener">打开预览</a>
</div>
</header> </header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?> <?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/pages/<?= $e($slug) ?>"> <div class="studio-layout">
<h2>首屏与 SEO</h2> <aside class="admin-panel studio-library" aria-labelledby="studio-library-title">
<h2 id="studio-library-title">区块模板</h2>
<?= View::fragment('studio-templates') ?>
<details class="studio-layers">
<summary>首屏与目录</summary>
<button type="button" disabled data-hero-control="image">首屏图片</button>
<button type="button" disabled data-hero-control="1">首屏按钮 1</button>
<button type="button" disabled data-hero-control="2">首屏按钮 2</button>
<button type="button" disabled data-hero-control="navigation">本页目录</button>
</details>
<details class="studio-layers">
<summary>按锚点新建区块</summary>
<form class="admin-form" method="post" action="/admin/page-blocks/<?= $e($slug) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>"> <input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($page['version']) ?>"> <input type="hidden" name="operation" value="create">
<label>SEO 标题<input name="title" value="<?= $e($page['title']) ?>" required maxlength="160"></label> <label>锚点<input name="key" pattern="[a-z0-9]+(-[a-z0-9]+)*" maxlength="70" placeholder="overview" required></label>
<label>SEO 描述<textarea name="description" rows="3" required maxlength="300"><?= $e($page['description']) ?></textarea></label> <label>模板<select name="preset">
<div class="form-grid"> <?php foreach (BlockTemplates::GROUPS as [$category, $templates]): ?>
<label>首屏标题<input name="heading" value="<?= $e($page['heading']) ?>" required maxlength="110"></label> <optgroup label="<?= $e($category) ?>">
<label>标题第二行<input name="accent" value="<?= $e($page['accent']) ?>" maxlength="110"></label> <?php foreach ($templates as $preset => [$label]): ?>
</div> <option value="<?= $e($preset) ?>"><?= $e($label) ?></option>
<label>首屏简介<textarea name="lead" rows="3" maxlength="600"><?= $e($page['lead']) ?></textarea></label>
<div class="form-grid">
<label>首屏图片地址<input name="image" value="<?= $e($page['image']) ?>" maxlength="1000"></label>
<label>图片替代文本<input name="alt" value="<?= $e($page['alt']) ?>" maxlength="200"></label>
</div>
<?php foreach ([1, 2] as $index): ?>
<div class="form-grid">
<label>按钮 <?= $index ?> 文案<input name="label<?= $index ?>" value="<?= $e($page['actions'][$index - 1][1] ?? '') ?>" maxlength="50"></label>
<label>按钮 <?= $index ?> 链接<input name="url<?= $index ?>" value="<?= $e($page['actions'][$index - 1][0] ?? '') ?>" maxlength="1000"></label>
</div>
<?php endforeach ?> <?php endforeach ?>
<div class="form-submit"><button class="button button-primary" type="submit">保存页面</button></div> </optgroup>
<?php endforeach ?>
</select></label>
<button type="submit" class="button button-outline">新建</button>
</form> </form>
<section class="admin-panel"> </details>
<h2>内容区块</h2> <details class="studio-layers" id="blocks">
<ul class="admin-list"> <summary>区块顺序</summary>
<?php foreach ($page['sections'] as $item): ?> <ul class="admin-list studio-blocks">
<?php foreach ($page['sections'] as $index => $item): ?>
<li> <li>
<div><strong><?= $e($item['title']) ?></strong><small>#<?= $e($item['key']) ?></small></div> <div><strong><?= $e($item['title']) ?></strong><small>#<?= $e($item['key']) ?></small></div>
<a class="button button-outline" href="/admin/pages/<?= $e($slug) ?>/<?= $e($item['key']) ?>">编辑区块</a> <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> </li>
<?php endforeach ?> <?php endforeach ?>
</ul> </ul>
</details>
</aside>
<div class="studio-workspace">
<section class="admin-panel studio-preview" data-preview-studio aria-labelledby="studio-preview-title">
<div class="admin-heading compact">
<h2 id="studio-preview-title">页面画布</h2>
<div class="preview-selector" aria-label="预览尺寸">
<button type="button" class="button button-outline" data-preview-size="desktop" aria-pressed="true">桌面</button>
<button type="button" class="button button-outline" data-preview-size="phone" aria-pressed="false">手机</button>
</div>
</div>
<div class="editor-toolbar studio-canvas-toolbar" data-canvas-toolbar hidden aria-label="正文工具">
<div>
<button type="button" data-canvas-command="heading">小标题</button>
<button type="button" data-canvas-command="bold">粗体</button>
<button type="button" data-canvas-command="list">列表</button>
<button type="button" data-canvas-command="link">插入链接</button>
<button type="button" data-canvas-command="media">插入媒体</button>
</div>
<button class="button button-primary" form="studio-page-settings" type="submit">保存页面</button>
</div>
<div class="studio-frame-window">
<iframe title="可编辑页面画布" src="<?= $e($previewUrl) ?>?canvas=1" sandbox="allow-same-origin"></iframe>
<div class="studio-media-sizing" data-media-sizing hidden>
<label>媒体宽度
<select data-media-width>
<option value="0">原始尺寸</option>
<?php foreach ([25, 40, 50, 60, 75, 85, 100] as $scale): ?>
<option value="<?= $scale ?>"><?= $scale ?>%</option>
<?php endforeach ?>
</select>
</label>
<button class="button button-outline" type="button" data-replace-media>替换媒体</button>
</div>
</div>
<p class="field-note">直接编辑画布文字。单击媒体调整宽度,双击替换。</p>
<dialog class="media-picker canvas-properties" data-canvas-properties aria-labelledby="canvas-properties-heading">
<div class="admin-heading compact"><h2 id="canvas-properties-heading" data-property-heading>编辑属性</h2></div>
<form class="admin-form" method="dialog">
<label data-property-row="label">文案<input name="label"></label>
<label data-property-row="url">地址<input name="url" maxlength="1000"></label>
<label data-property-row="alt">图片替代文本<input name="alt" maxlength="200"></label>
<label data-property-row="quicklinks">目录链接<textarea name="quicklinks" rows="5" placeholder="概览 | #overview"></textarea><small>每行填写「文案 | 链接」。</small></label>
<label data-property-row="poster">视频封面<input name="poster" maxlength="1000"></label>
<p class="feedback error" role="alert" data-property-error hidden></p>
<div class="actions">
<button type="button" class="button button-outline" data-property-pick="url">从媒体库选择</button>
<button type="button" class="button button-outline" data-property-pick="poster">选择视频封面</button>
</div>
<div class="actions">
<button type="submit" class="button button-primary">应用</button>
<button type="button" class="button button-outline" data-property-close>取消</button>
</div>
</form>
</dialog>
</section> </section>
</div>
<form id="studio-page-settings" class="admin-form admin-panel studio-inspector" method="post" action="/admin/pages/<?= $e($slug) ?>">
<h2>页面设置</h2>
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($page['version']) ?>">
<input type="hidden" name="canvas_sections" value="">
<label>页面名称<input name="name" value="<?= $e($page['name']) ?>" required maxlength="100"></label>
<label>SEO 标题<input name="title" value="<?= $e($page['title']) ?>" required maxlength="160"></label>
<label>SEO 描述<textarea name="description" rows="2" maxlength="300"><?= $e($page['description']) ?></textarea></label>
<?php
$contentFields = [
'heading' => $page['heading'], 'accent' => $page['accent'], 'lead' => $page['lead'],
'image' => $page['image'], 'alt' => $page['alt'], 'image_scale' => $page['image_scale'],
'quicklinks' => SiteDesign::linkText($page['quicklinks']),
];
foreach ([1, 2] as $index) {
$contentFields['label' . $index] = $page['actions'][$index - 1][1] ?? '';
$contentFields['url' . $index] = $page['actions'][$index - 1][0] ?? '';
}
?>
<?php foreach ($contentFields as $field => $value): ?>
<?php if ($field === 'quicklinks'): ?>
<textarea name="quicklinks" hidden><?= $e($value) ?></textarea>
<?php else: ?>
<input type="hidden" name="<?= $e($field) ?>" value="<?= $e($value) ?>">
<?php endif ?>
<?php endforeach ?>
<?php if ($slug !== 'home'): ?>
<label>发布状态<select name="status"><option value="draft" <?= $page['status'] === 'draft' ? 'selected' : '' ?>>草稿</option>
<option value="published" <?= $page['status'] === 'published' ? 'selected' : '' ?>>已发布</option></select></label>
<?php endif ?>
<div class="form-submit"><button class="button button-primary" type="submit">保存页面</button></div>
</form>
</div>
+6 -1
View File
@@ -8,7 +8,7 @@ $key = $section['key'];
<a class="back-link" href="/admin/pages/<?= $e($slug) ?>">返回页面编辑</a> <a class="back-link" href="/admin/pages/<?= $e($slug) ?>">返回页面编辑</a>
<header class="admin-heading"> <header class="admin-heading">
<div><h1><?= $e($title) ?></h1><p><?= $e($slug) ?> · #<?= $e($key) ?></p></div> <div><h1><?= $e($title) ?></h1><p><?= $e($slug) ?> · #<?= $e($key) ?></p></div>
<a class="button button-outline" href="<?= $e(($slug === 'home' ? '/' : '/' . $slug) . '#' . $key) ?>">查看公开区块</a> <a class="button button-outline" href="/admin/pages/<?= $e($slug) ?>/preview#<?= $e($key) ?>" target="_blank" rel="noopener">预览区块</a>
</header> </header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?> <?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/pages/<?= $e($slug) ?>/<?= $e($key) ?>"> <form class="admin-form admin-panel" method="post" action="/admin/pages/<?= $e($slug) ?>/<?= $e($key) ?>">
@@ -16,6 +16,11 @@ $key = $section['key'];
<input type="hidden" name="version" value="<?= $e($section['version']) ?>"> <input type="hidden" name="version" value="<?= $e($section['version']) ?>">
<label>区块标题<input name="title" value="<?= $e($section['title']) ?>" required maxlength="100"></label> <label>区块标题<input name="title" value="<?= $e($section['title']) ?>" required maxlength="100"></label>
<label>区块简介<textarea name="lead" rows="2" maxlength="500"><?= $e($section['lead']) ?></textarea></label> <label>区块简介<textarea name="lead" rows="2" maxlength="500"><?= $e($section['lead']) ?></textarea></label>
<label>区块背景<select name="style">
<?php foreach (array_unique([$savedStyle, 'plain', 'tinted']) as $style): ?>
<option value="<?= $e($style) ?>" <?= $style === $section['style'] ? 'selected' : '' ?>><?= $e(['plain' => '默认', 'tinted' => '浅色背景'][$style] ?? '保留原布局') ?></option>
<?php endforeach ?>
</select></label>
<?= 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>
+47
View File
@@ -0,0 +1,47 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<footer class="site-footer" id="contact">
<div class="wrap">
<div class="footer-grid">
<div class="footer-company" itemscope itemtype="https://schema.org/Organization">
<?php if ($footer['logo'] !== ''): ?>
<a href="/" itemprop="url" aria-label="来笙 Laysense 首页">
<img src="<?= $e($footer['logo']) ?>" alt="<?= $e($footer['alt']) ?>" width="130" height="33" itemprop="logo" loading="lazy">
</a>
<?php endif ?>
<p itemprop="name"><?= $e($footer['name']) ?></p>
<?php if ($footer['address']): ?><address itemprop="address"><?= $e($footer['address']) ?></address><?php endif ?>
<?php if ($footer['email']): ?>
<a itemprop="email" href="mailto:<?= $e($footer['email']) ?>"><?= $e($footer['email']) ?></a>
<?php endif ?>
<div class="payment-methods" aria-label="支持的付款方式">
<img src="/assets/original/payment-taobao.png" alt="淘宝" width="26" height="26" loading="lazy">
<img src="/assets/original/payment-alipay.png" alt="支付宝" width="26" height="26" loading="lazy">
<img src="/assets/original/payment-wechat.png" alt="微信支付" width="26" height="26" loading="lazy">
</div>
</div>
<?php foreach (['products', 'company'] as $group): ?>
<?php if (!$footer[$group] && $footer[$group . '_title'] === '') { continue; } ?>
<div>
<?php if ($footer[$group . '_title'] !== ''): ?><p class="footer-label"><?= $e($footer[$group . '_title']) ?></p><?php endif ?>
<?php foreach ($footer[$group] as [$url, $label]): ?><a href="<?= $e($url) ?>"><?= $e($label) ?></a><?php endforeach ?>
</div>
<?php endforeach ?>
</div>
<div class="footer-meta">
<?php if ($footer['copyright']): ?><p><?= $e($footer['copyright']) ?> 2024–<?= $e(date('Y')) ?></p><?php endif ?>
<?php if ($footer['phones']): ?>
<p>全球号码
<?php foreach ($footer['phones'] as $index => [$url, $label]): ?>
<?= $index ? ' / ' : '' ?><a href="<?= $e($url) ?>"><?= $e($label) ?></a>
<?php endforeach ?>
</p>
<?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 ?>
</div>
</div>
</footer>
+18 -46
View File
@@ -1,17 +1,21 @@
<?php <?php
use App\Content\View; use App\Content\View;
use App\Content\Assets;
use App\Content\SiteDesign;
$e = View::escape(...); $e = View::escape(...);
$canonical = $path !== null ? View::absolute($path) : null; $canonical = $path !== null ? View::absolute($path) : null;
$imageUrl = !empty($socialImage) ? $socialImage : '/assets/original/home-hero.webp'; $imageUrl = !empty($socialImage) ? $socialImage : '/assets/original/home-hero.webp';
$imageUrl = Assets::url($imageUrl, $cdn);
if (str_starts_with($imageUrl, '/')) { if (str_starts_with($imageUrl, '/')) {
$imageUrl = View::absolute($imageUrl); $imageUrl = View::absolute($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';
$nav = [ $header = ($site['header'] ?? []) + SiteDesign::DEFAULT_HEADER;
['/', '首页'], ['/#product', '产品与服务'], ['/articles', '动态'], ['/#about', '关于来笙'], $footer = ($site['footer'] ?? []) + SiteDesign::DEFAULT_FOOTER + $site;
]; $nav = $header['links'];
$contact = $header['button'];
?> ?>
<!doctype html> <!doctype html>
<html lang="zh-CN" data-type="<?= $e($kind) ?>" data-buttons="solid" data-motion="on"> <html lang="zh-CN" data-type="<?= $e($kind) ?>" data-buttons="solid" data-motion="on">
@@ -45,12 +49,14 @@ $nav = [
<script src="/assets/jquery-4.0.0.min.js" defer></script> <script src="/assets/jquery-4.0.0.min.js" defer></script>
<script src="/assets/site.js" defer></script> <script src="/assets/site.js" defer></script>
</head> </head>
<body> <body<?= $kind === 'service' ? ' class="copyright-service"' : '' ?>>
<a class="skip-link" href="#main-content">跳到内容</a> <a class="skip-link" href="#main-content">跳到内容</a>
<header class="masthead"> <header class="masthead">
<div class="wrap masthead-inner"> <div class="wrap masthead-inner">
<a class="wordmark" href="/" aria-label="来笙 Laysense 首页"> <a class="wordmark" href="/" aria-label="来笙 Laysense 首页">
<img src="/assets/wordmark.webp" alt="Laysense 来笙" width="130" height="33"> <?php if ($header['logo'] !== ''): ?>
<img src="<?= $e($header['logo']) ?>" alt="<?= $e($header['alt']) ?>" width="130" height="33">
<?php else: ?>来笙 Laysense<?php endif ?>
</a> </a>
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="primary-navigation" hidden> <button class="menu-toggle" type="button" aria-expanded="false" aria-controls="primary-navigation" hidden>
<span></span><span></span><span class="sr-only">菜单</span> <span></span><span></span><span class="sr-only">菜单</span>
@@ -60,50 +66,16 @@ $nav = [
<?php $current = $url === $path || ($url === '/articles' && str_starts_with($path ?? '', '/articles')); ?> <?php $current = $url === $path || ($url === '/articles' && str_starts_with($path ?? '', '/articles')); ?>
<a href="<?= $e($url) ?>" <?= $current ? 'aria-current="page"' : '' ?>><?= $e($label) ?></a> <a href="<?= $e($url) ?>" <?= $current ? 'aria-current="page"' : '' ?>><?= $e($label) ?></a>
<?php endforeach ?> <?php endforeach ?>
<a class="mobile-contact" href="#contact">联系来笙</a> <?php if ($contact): ?>
<a class="mobile-contact" href="<?= $e($contact[0]) ?>"><?= $e($contact[1]) ?></a>
<?php endif ?>
</nav> </nav>
<a class="button button-outline masthead-action" href="#contact">联系来笙</a> <?php if ($contact): ?>
<a class="button button-outline masthead-action" href="<?= $e($contact[0]) ?>"><?= $e($contact[1]) ?></a>
<?php endif ?>
</div> </div>
</header> </header>
<main id="main-content" tabindex="-1"><?= $content ?></main> <main id="main-content" tabindex="-1"><?= $content ?></main>
<footer class="site-footer" id="contact"> <?= View::fragment('footer', ['footer' => $footer]) ?>
<div class="wrap">
<div class="footer-grid">
<div class="footer-company" itemscope itemtype="https://schema.org/Organization">
<a href="/" itemprop="url" aria-label="来笙 Laysense 首页">
<img src="/assets/wordmark.webp" alt="来笙 Laysense" width="130" height="33" itemprop="logo" loading="lazy">
</a>
<p itemprop="name"><?= $e($site['name']) ?></p>
<address itemprop="address"><?= $e($site['address']) ?></address>
<a itemprop="email" href="mailto:<?= $e($site['email']) ?>"><?= $e($site['email']) ?></a>
<div class="payment-methods" aria-label="支持的付款方式">
<img src="/assets/original/payment-taobao.png" alt="淘宝" width="26" height="26" loading="lazy">
<img src="/assets/original/payment-alipay.png" alt="支付宝" width="26" height="26" loading="lazy">
<img src="/assets/original/payment-wechat.png" alt="微信支付" width="26" height="26" loading="lazy">
</div>
</div>
<div>
<p class="footer-label">产品与服务</p>
<a href="/pagepan">PAGEPAN 小飞页</a>
<a href="/highspeaker">HighSpeaker DNS</a>
<a href="/sc">软著代理服务</a>
<a href="/shnu-sc">SHNU 学生软著服务</a>
</div>
<div>
<p class="footer-label">公司</p>
<a href="/#about">关于来笙</a>
<a href="/articles">来笙动态</a>
<a href="https://git.laysense.com">Laysense Git</a>
<a href="https://www.layso.de">LaySo</a>
</div>
</div>
<div class="footer-meta">
<p><?= $e($site['copyright']) ?> 2024–<?= $e(date('Y')) ?></p>
<p>全球号码 <a href="tel:+16699004532">+1 (669) 900 4532</a> / <a href="tel:+85257012856">+852 5701 2856</a></p>
<a href="https://beian.miit.gov.cn/"><?= $e($site['registration']) ?></a>
<p class="footer-terms"><?= $e($site['terms']) ?></p>
</div>
</div>
</footer>
</body> </body>
</html> </html>
+24 -14
View File
@@ -5,9 +5,10 @@ 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);
$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>
<div class="wrap hero-inner"> <div class="wrap hero-inner<?= $page['image'] === '' ? ' hero-text-only' : '' ?>">
<div class="hero-copy"> <div class="hero-copy">
<?php if (!$home): ?> <?php if (!$home): ?>
<nav class="breadcrumbs" aria-label="面包屑" itemscope itemtype="https://schema.org/BreadcrumbList"> <nav class="breadcrumbs" aria-label="面包屑" itemscope itemtype="https://schema.org/BreadcrumbList">
@@ -17,30 +18,33 @@ $service = in_array($page['slug'], ['sc', 'shnu-sc'], true);
</span> </span>
<span class="crumb-divider" aria-hidden="true">/</span> <span class="crumb-divider" aria-hidden="true">/</span>
<span itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem"> <span itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
<a itemprop="item" href="/<?= $e($page['slug']) ?>" aria-current="page"><span itemprop="name"><?= $e($page['name']) ?></span></a> <a itemprop="item" href="/<?= $e($page['slug']) ?>" aria-current="page"><span itemprop="name"<?= $field('name') ?>><?= $e($page['name']) ?></span></a>
<meta itemprop="position" content="2"> <meta itemprop="position" content="2">
</span> </span>
</nav> </nav>
<?php else: ?> <?php else: ?>
<p class="overline hero-label">上海来笙信息科技有限公司</p> <p class="overline hero-label"><?= $e($site['footer']['name'] ?? $site['name']) ?></p>
<?php endif ?> <?php endif ?>
<h1><?= $e($page['heading']) ?><?php if ($page['accent'] !== ''): ?><br><span><?= $e($page['accent']) ?></span><?php endif ?></h1> <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>
<p class="hero-lead"><?= $e($page['lead']) ?></p> <p class="hero-lead"<?= $field('lead') ?>><?= $e($page['lead']) ?></p>
<div class="actions hero-actions"> <div class="actions hero-actions">
<?php foreach ($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) ?>"><?= $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 ($page['image'] !== ''): ?> <?php if ($canvas || $page['image'] !== ''): ?>
<div class="hero-visual <?= $home ? 'hero-illustration' : ($service ? 'hero-service-art' : 'app-frame') ?>" data-visual> <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' : '' ?>>
<img src="<?= $e($page['image']) ?>" alt="<?= $e($page['alt']) ?>" width="1448" height="1086" fetchpriority="high"> <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' && !$page['image_scale']): ?>
<div class="home-pipe-flow" aria-hidden="true"><span></span><span></span><span></span><span></span></div>
<?php endif ?>
</div> </div>
<?php endif ?> <?php endif ?>
</div> </div>
<?php if ($home): ?> <?php if ($home): ?>
<div class="wrap hero-directory"> <div class="wrap hero-directory">
<span class="overline">产品与服务</span> <a class="overline directory-label" href="/services">产品与服务</a>
<a href="/pagepan"><span>PAGEPAN</span><small>可视化建站</small></a> <a href="/pagepan"><span>PAGEPAN</span><small>可视化建站</small></a>
<a href="/highspeaker"><span>HighSpeaker DNS</span><small>开源智能解析</small></a> <a href="/highspeaker"><span>HighSpeaker DNS</span><small>开源智能解析</small></a>
<a href="/sc"><span>软著代理</span><small>登记申请与材料服务</small></a> <a href="/sc"><span>软著代理</span><small>登记申请与材料服务</small></a>
@@ -48,8 +52,8 @@ $service = in_array($page['slug'], ['sc', 'shnu-sc'], true);
</div> </div>
<?php endif ?> <?php endif ?>
</section> </section>
<?php if ($page['quicklinks']): ?> <?php if ($canvas || $page['quicklinks']): ?>
<nav class="section-nav" aria-label="本页目录"> <nav class="section-nav" aria-label="本页目录"<?= $canvas ? ' data-studio-navigation' : '' ?><?= !$page['quicklinks'] ? ' hidden' : '' ?>>
<div class="wrap section-nav-inner"> <div class="wrap section-nav-inner">
<?php foreach ($page['quicklinks'] as [$url, $label]): ?> <?php foreach ($page['quicklinks'] as [$url, $label]): ?>
<a href="<?= $e($url) ?>"><?= $e($label) ?></a> <a href="<?= $e($url) ?>"><?= $e($label) ?></a>
@@ -58,8 +62,14 @@ $service = in_array($page['slug'], ['sc', 'shnu-sc'], true);
</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']) ?> <?= View::fragment('section', ['section' => $section, 'moment' => $home && $section['key'] === 'about', 'canvas' => $canvas]) ?>
<?php endforeach ?> <?php endforeach ?>
<?php if ($canvas): ?>
<template data-studio-section-end><?= View::fragment('section', [
'section' => ['style' => 'plain', 'key' => 'new', 'version' => null, 'title' => '', 'lead' => '', 'body' => ''],
'moment' => false, 'canvas' => true,
]) ?></template>
<?php endif ?>
<?php if ($home): ?> <?php if ($home): ?>
<section class="section home-news" id="blog" aria-labelledby="updates-heading"> <section class="section home-news" id="blog" aria-labelledby="updates-heading">
<div class="wrap"> <div class="wrap">
+5 -4
View File
@@ -2,13 +2,14 @@
use App\Content\View; use App\Content\View;
$e = View::escape(...); $e = View::escape(...);
$canvas ??= false;
?> ?>
<section class="section section-<?= $e($section['style']) ?>" id="<?= $e($section['key']) ?>" aria-labelledby="heading-<?= $e($section['key']) ?>" <?= $moment ? 'data-moment="iris-opens"' : '' ?>> <section class="section section-<?= $e($section['style']) ?>" id="<?= $e($section['key']) ?>" aria-labelledby="heading-<?= $e($section['key']) ?>" <?= $moment ? 'data-moment="iris-opens"' : '' ?><?= $canvas ? ' data-studio-section="' . $e($section['version']) . '" data-studio-source="' . $e(base64_encode($section['body'])) . '"' : '' ?>>
<div class="wrap"> <div class="wrap">
<div class="section-heading"> <div class="section-heading">
<h2 id="heading-<?= $e($section['key']) ?>"><?= $e($section['title']) ?></h2> <h2 id="heading-<?= $e($section['key']) ?>"<?= $canvas ? ' data-studio-part="title"' : '' ?>><?= $e($section['title']) ?></h2>
<?php if ($section['lead']): ?><p><?= $e($section['lead']) ?></p><?php endif ?> <?php if ($canvas || $section['lead']): ?><p<?= $canvas ? ' data-studio-part="lead"' : '' ?>><?= $e($section['lead']) ?></p><?php endif ?>
</div> </div>
<div class="rich"><?= $section['body'] ?></div> <div class="rich"<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $section['body'] ?></div>
</div> </div>
</section> </section>
+35
View File
@@ -0,0 +1,35 @@
<?php
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): ?>
<article class="catalog-card">
<?php if ($product['image']): ?>
<div class="catalog-image"><img src="<?= $e($product['image']) ?>" alt="<?= $e($product['alt']) ?>" loading="lazy"></div>
<?php endif ?>
<div class="catalog-content">
<p class="overline"><?= $e($product['category']) ?></p>
<h2><?= $e($product['name']) ?></h2>
<div class="rich"><?= $product['body'] ?></div>
<div class="actions">
<a class="button button-primary" href="<?= $e($product['url']) ?>"><?= $e($product['label']) ?></a>
<?php if ($product['extra_url']): ?><a href="<?= $e($product['extra_url']) ?>"><?= $e($product['extra_label']) ?></a><?php endif ?>
</div>
</div>
</article>
<?php endforeach ?>
</div>
</div>
</section>
+9
View File
@@ -0,0 +1,9 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<div class="asset-field">
<label><?= $e($label) ?><input name="<?= $e($name) ?>" value="<?= $e($value) ?>" maxlength="1000"></label>
<button type="button" class="button button-outline" data-asset-pick="<?= $e($name) ?>" data-asset-type="image/">媒体库</button>
</div>
+19
View File
@@ -0,0 +1,19 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<header class="admin-heading">
<div><h1>产品与服务</h1><p>管理公开目录中的条目、分类和按钮链接。</p></div>
<div class="actions"><a class="button button-outline" href="/services">查看目录</a><a class="button button-primary" href="/admin/catalog/new">添加条目</a></div>
</header>
<section class="admin-panel">
<?php if (!$products): ?><p class="empty-state">暂无产品或服务。</p><?php endif ?>
<ul class="admin-list">
<?php foreach ($products as $item): ?>
<li><div><strong><?= $e($item['name']) ?></strong><small><?= $e($item['category']) ?> · <?= $e($item['url']) ?></small></div>
<a class="button button-outline" href="/admin/catalog/<?= $e($item['id']) ?>">编辑</a>
</li>
<?php endforeach ?>
</ul>
</section>
+50
View File
@@ -0,0 +1,50 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<header class="admin-heading"><div><h1>媒体库</h1><p>统一查找并引用静态文件、图片、图标和音视频。</p></div></header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/media" enctype="multipart/form-data">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<div class="form-grid">
<label>文件<input type="file" name="file" accept="image/*,video/*,audio/*,.pdf,.woff,.woff2" required>
<small>支持常见图片、SVG 图标、音视频、PDF、WOFF/WOFF2,单文件最大 64 MB。</small>
</label>
<label>资源名称<input name="label" maxlength="160" placeholder="默认使用文件名"></label>
</div>
<div class="form-submit"><button type="submit" class="button button-primary">上传文件</button></div>
</form>
<section class="admin-panel media-library" data-media-library aria-labelledby="library-heading">
<h2 id="library-heading">资源列表</h2>
<div class="form-grid">
<label>搜索<input type="search" data-library-query placeholder="搜索名称或路径"></label>
<label>类型<select data-library-type><option value="">全部资源</option><option value="image/">图片与图标</option><option value="video/">视频</option><option value="audio/">音频</option><option value="other">其他文件</option></select></label>
</div>
<p data-library-count role="status"></p>
<div class="media-grid">
<?php foreach ($files as $file): ?>
<article class="media-card" data-library-card data-mime="<?= $e($file['mime']) ?>" data-search="<?= $e($file['label'] . ' ' . $file['url']) ?>">
<?php if (str_starts_with($file['mime'], 'image/')): ?>
<img src="<?= $e($file['url']) ?>" alt="" loading="lazy">
<?php else: ?>
<p class="media-file-type"><?= $e(strtolower(pathinfo($file['url'], PATHINFO_EXTENSION))) ?></p>
<?php endif ?>
<h3><?= $e($file['label']) ?></h3>
<small><?= $e((string) max(1, ceil($file['size'] / 1024))) ?> KB · <?= $file['name'] === '' ? '项目文件' : ($file['archived'] ? '已归档' : '上传文件') ?></small>
<div class="actions"><a href="<?= $e($file['url']) ?>" target="_blank" rel="noopener">打开</a><button type="button" class="button button-outline" data-copy-asset="<?= $e($file['url']) ?>">复制路径</button></div>
<?php if ($file['name'] !== ''): ?>
<details><summary>管理文件</summary>
<form class="admin-form" method="post" action="/admin/media/<?= $e($file['name']) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<label>名称<input name="label" value="<?= $e($file['label']) ?>" maxlength="160" required></label>
<label class="media-archive"><input type="checkbox" name="archived" value="1" <?= $file['archived'] ? 'checked' : '' ?>>归档</label>
<small>归档从选取器隐藏文件,已有链接仍可访问。</small>
<button type="submit" class="button button-outline">保存</button>
</form>
</details>
<?php endif ?>
</article>
<?php endforeach ?>
</div>
</section>
+16
View File
@@ -0,0 +1,16 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<a class="back-link" href="/admin">返回页面</a>
<header class="admin-heading"><h1>新建页面</h1></header>
<?= View::fragment('admin-feedback', ['error' => $error, 'saved' => false]) ?>
<form class="admin-form admin-panel" method="post" action="/admin/new-page">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<label>页面名称<input name="name" maxlength="100" value="<?= $e($name) ?>" required></label>
<label>网址标识<input name="slug" maxlength="70" value="<?= $e($slug) ?>" pattern="[a-z0-9]+(-[a-z0-9]+)*" placeholder="my-page" required>
<small>创建后为草稿。可在编辑画布中预览,并自行发布。</small>
</label>
<div class="form-submit"><button type="submit" class="button button-primary">创建草稿</button></div>
</form>
+36
View File
@@ -0,0 +1,36 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<a class="back-link" href="/admin/catalog">返回目录管理</a>
<header class="admin-heading"><h1><?= $e($title) ?></h1></header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/catalog/<?= $e($id ?? 'new') ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($product['version']) ?>">
<div class="form-grid">
<label>名称<input name="name" value="<?= $e($product['name']) ?>" required maxlength="100"></label>
<label>分类<input name="category" value="<?= $e($product['category']) ?>" required maxlength="70"></label>
</div>
<div class="form-grid">
<?= View::fragment('studio-asset-field', ['label' => '封面', 'name' => 'image', 'value' => $product['image']]) ?>
<label>封面替代文本<input name="alt" value="<?= $e($product['alt']) ?>" maxlength="200"></label>
</div>
<div class="form-grid">
<label>按钮文案<input name="label" value="<?= $e($product['label']) ?>" required maxlength="70"></label>
<label>按钮链接<input name="url" value="<?= $e($product['url']) ?>" required maxlength="1000"></label>
<label>次要链接文案<input name="extra_label" value="<?= $e($product['extra_label']) ?>" maxlength="70"></label>
<label>次要链接<input name="extra_url" value="<?= $e($product['extra_url']) ?>" maxlength="1000"></label>
</div>
<label>排序<input type="number" name="position" min="-999999" max="999999" value="<?= $e($product['position'] === '' ? 100 : $product['position']) ?>" required><small>数值越小越靠前。</small></label>
<?= View::fragment('admin-editor', ['format' => 'html', 'body' => $product['body']]) ?>
<div class="form-submit"><button class="button button-primary" type="submit">保存条目</button></div>
</form>
<?php if ($id !== null): ?>
<form class="admin-form" method="post" action="/admin/catalog/<?= $e($id) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($product['version']) ?>">
<div class="form-submit"><button class="button button-outline" type="submit" name="operation" value="delete" data-confirm="从公开目录删除此条目?">删除条目</button></div>
</form>
<?php endif ?>
+52
View File
@@ -0,0 +1,52 @@
<?php
use App\Content\SiteDesign;
use App\Content\View;
$e = View::escape(...);
?>
<header class="admin-heading"><h1><?= $e($title) ?></h1><a class="button button-outline" href="/" target="_blank" rel="noopener">查看公开网站</a></header>
<nav class="filter-nav" aria-label="网站设置">
<?php foreach (['header' => '页头', 'footer' => '页脚', 'cdn' => 'CDN'] as $key => $text): ?>
<a href="/admin/settings/<?= $key ?>" <?= $key === $part ? 'aria-current="page"' : '' ?>><?= $text ?></a>
<?php endforeach ?>
</nav>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel settings-form" method="post" action="/admin/settings/<?= $e($part) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($revision) ?>">
<?php if ($part === 'cdn'): ?>
<label>CDN 源站地址<input name="origin" type="url" value="<?= $e($config['origin']) ?>" placeholder="https://cdn.laysense.cn">
<small>留空时直接从站点提供资源。配置后,公开页面中的 /assets/ 路径会改用此域名。</small>
</label>
<?php else: ?>
<?= View::fragment('studio-asset-field', ['label' => '站点标志', 'name' => 'logo', 'value' => $config['logo']]) ?>
<label>标志替代文本<input name="alt" value="<?= $e($config['alt']) ?>" maxlength="200"></label>
<?php if ($part === 'header'): ?>
<label>主导航<textarea name="links" rows="6" placeholder="产品与服务 | /services"><?= $e(SiteDesign::linkText($config['links'])) ?></textarea>
<small>每行填写「文案 | 链接」,按输入顺序展示。</small>
</label>
<label>右侧按钮<input name="button" value="<?= $e($config['button'] ? SiteDesign::linkText([$config['button']]) : '') ?>" placeholder="联系来笙 | #contact"></label>
<?php else: ?>
<div class="form-grid">
<?php foreach (['name' => '公司名称', 'address' => '联系地址', 'email' => '邮箱', 'registration' => '备案号', 'copyright' => '版权信息'] as $key => $text): ?>
<label><?= $text ?><input name="<?= $key ?>" value="<?= $e($config[$key] ?? '') ?>" <?= $key === 'name' ? 'required' : '' ?>></label>
<?php endforeach ?>
</div>
<label>联系号码<textarea name="phones" rows="3"><?= $e(SiteDesign::linkText($config['phones'])) ?></textarea>
<small>每行填写「显示号码 | tel:号码」。</small>
</label>
<div class="form-grid">
<?php foreach (['products' => '第一列', 'company' => '第二列'] as $key => $text): ?>
<div class="admin-form">
<label><?= $text ?>标题<input name="<?= $key ?>_title" value="<?= $e($config[$key . '_title']) ?>"></label>
<label><?= $text ?>链接<textarea name="<?= $key ?>" rows="6"><?= $e(SiteDesign::linkText($config[$key])) ?></textarea>
<small>每行填写「文案 | 链接」。</small>
</label>
</div>
<?php endforeach ?>
</div>
<label>页脚备注<textarea name="terms" rows="2"><?= $e($config['terms'] ?? '') ?></textarea></label>
<?php endif ?>
<?php endif ?>
<div class="form-submit"><button class="button button-primary" type="submit">保存设置</button></div>
</form>
+55
View File
@@ -0,0 +1,55 @@
<?php
use App\Content\BlockTemplates;
use App\Content\View;
$e = View::escape(...);
?>
<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-template-filters" role="group" aria-label="模板分类">
<button type="button" data-template-filter="" aria-pressed="true">全部</button>
<?php foreach (BlockTemplates::GROUPS as $group => [$category]): ?>
<button type="button" data-template-filter="<?= $e($group) ?>" aria-pressed="false"><?= $e($category) ?></button>
<?php endforeach ?>
</div>
<label class="studio-insert-mode"><input type="checkbox" data-template-inline> 插入当前正文</label>
<p class="field-note" data-template-status role="status"></p>
<ul class="studio-pending" data-template-pending hidden></ul>
<p class="field-note" data-template-empty hidden role="status">没有找到匹配的模板。</p>
<div class="studio-template-groups">
<?php foreach (BlockTemplates::GROUPS as $group => [$category, $templates]): ?>
<section class="studio-template-group" data-template-group="<?= $e($group) ?>" aria-labelledby="studio-template-<?= $e($group) ?>">
<h3 id="studio-template-<?= $e($group) ?>"><?= $e($category) ?></h3>
<div class="studio-template-cards">
<?php foreach ($templates as $preset => [$label, $markup]): ?>
<article class="studio-template-card" data-template-card data-template-search-text="<?= $e($label . ' ' . $category . ' ' . $preset) ?>">
<button type="button" class="studio-template-image" data-template-preview="<?= $e($preset) ?>" data-template-title="<?= $e($label) ?>"
aria-label="预览<?= $e($label) ?>模板">
<img src="/assets/template-previews/<?= $e($preset) ?>.webp" alt="" width="768" height="480" loading="lazy">
</button>
<div class="studio-template-meta">
<span><?= $e($label) ?></span>
<button type="button" class="button button-outline" disabled data-canvas-template="<?= $e($preset) ?>"
data-template-title="<?= $e($label) ?>" aria-label="添加<?= $e($label) ?>模板">添加</button>
</div>
<template data-preset="<?= $e($preset) ?>"><?= $markup ?></template>
</article>
<?php endforeach ?>
</div>
</section>
<?php endforeach ?>
</div>
<div class="studio-template-peek" data-template-peek aria-hidden="true" hidden>
<img alt="">
<p></p>
</div>
<dialog class="media-picker studio-template-dialog" data-template-dialog aria-labelledby="studio-template-preview-title">
<header class="admin-heading compact">
<h2 id="studio-template-preview-title"></h2>
<button type="button" class="button button-outline" data-template-close>关闭</button>
</header>
<img alt="" width="768" height="480">
<div class="actions"><button type="button" class="button button-primary" data-template-use>添加到画布</button></div>
</dialog>
</div>
+1
View File
@@ -5,6 +5,7 @@
"require": { "require": {
"php": "^8.2", "php": "^8.2",
"ext-dom": "*", "ext-dom": "*",
"ext-fileinfo": "*",
"ext-mbstring": "*", "ext-mbstring": "*",
"ext-pdo_sqlite": "*", "ext-pdo_sqlite": "*",
"league/commonmark": "^2.8", "league/commonmark": "^2.8",
Generated
+2 -1
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "c9d25a83ed6ca15405ef7765391c2f0d", "content-hash": "b550e1c39f23f72dcd3480e7d01e9b56",
"packages": [ "packages": [
{ {
"name": "dflydev/dot-access-data", "name": "dflydev/dot-access-data",
@@ -1098,6 +1098,7 @@
"platform": { "platform": {
"php": "^8.2", "php": "^8.2",
"ext-dom": "*", "ext-dom": "*",
"ext-fileinfo": "*",
"ext-mbstring": "*", "ext-mbstring": "*",
"ext-pdo_sqlite": "*" "ext-pdo_sqlite": "*"
}, },
+16 -1
View File
@@ -2,13 +2,16 @@
use App\Controller\AdminController; use App\Controller\AdminController;
use App\Controller\SiteController; use App\Controller\SiteController;
use App\Controller\StudioController;
use App\Controller\MediaController;
use App\Content\View; use App\Content\View;
use support\Request; use support\Request;
use Webman\Route; use Webman\Route;
Route::disableDefaultRoute(); Route::disableDefaultRoute();
Route::get('/', [SiteController::class, 'home']); Route::get('/', [SiteController::class, 'home']);
Route::get('/{slug:pagepan|highspeaker|sc|shnu-sc}', [SiteController::class, 'page']); Route::get('/services', [SiteController::class, 'services']);
Route::get('/assets/uploads/{name:[a-f0-9]{32}\.[a-z0-9]+}', [MediaController::class, 'file']);
Route::get('/articles', [SiteController::class, 'archive']); Route::get('/articles', [SiteController::class, 'archive']);
Route::get('/articles/category/{category:announcement|news|product}', [SiteController::class, 'archive']); Route::get('/articles/category/{category:announcement|news|product}', [SiteController::class, 'archive']);
Route::get('/articles/tag/{tag:[^/]+}', [SiteController::class, 'tagged']); Route::get('/articles/tag/{tag:[^/]+}', [SiteController::class, 'tagged']);
@@ -27,8 +30,20 @@ Route::get('/admin', [AdminController::class, 'dashboard']);
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::add(['GET', 'POST'], '/admin/new-page', [StudioController::class, 'newPage']);
Route::get('/admin/pages/{slug:[a-z0-9-]+}/preview', [StudioController::class, 'previewPage']);
Route::post('/admin/page-blocks/{slug:[a-z0-9-]+}', [StudioController::class, 'blocks']);
Route::add(['GET', 'POST'], '/admin/settings/{part:header|footer|cdn}', [StudioController::class, 'settings']);
Route::get('/admin/catalog', [StudioController::class, 'catalog']);
Route::add(['GET', 'POST'], '/admin/catalog/new', [StudioController::class, 'product']);
Route::add(['GET', 'POST'], '/admin/catalog/{id:[0-9]+}', [StudioController::class, 'product']);
Route::add(['GET', 'POST'], '/admin/media', [StudioController::class, 'media']);
Route::get('/admin/media/options', [StudioController::class, 'mediaOptions']);
Route::post('/admin/media/{name:[a-f0-9]{32}\.[a-z0-9]+}', [StudioController::class, 'mediaMeta']);
Route::add(['GET', 'POST'], '/admin/pages/{slug:[a-z0-9-]+}', [AdminController::class, 'page']); Route::add(['GET', 'POST'], '/admin/pages/{slug:[a-z0-9-]+}', [AdminController::class, 'page']);
Route::add(['GET', 'POST'], '/admin/pages/{slug:[a-z0-9-]+}/{key:[a-z0-9-]+}', [AdminController::class, 'section']); Route::add(['GET', 'POST'], '/admin/pages/{slug:[a-z0-9-]+}/{key:[a-z0-9-]+}', [AdminController::class, 'section']);
Route::post('/admin/preview', [AdminController::class, 'preview']); Route::post('/admin/preview', [AdminController::class, 'preview']);
Route::get('/{slug:[a-z0-9-]+}', [SiteController::class, 'page']);
Route::fallback(static fn (Request $request) => (new SiteController())->missing($request)); Route::fallback(static fn (Request $request) => (new SiteController())->missing($request));
+1 -1
View File
@@ -6,5 +6,5 @@ return [
'stdout_file' => runtime_path() . '/logs/stdout.log', 'stdout_file' => runtime_path() . '/logs/stdout.log',
'log_file' => runtime_path() . '/logs/workerman.log', 'log_file' => runtime_path() . '/logs/workerman.log',
'stop_timeout' => 4, 'stop_timeout' => 4,
'max_package_size' => 2 * 1024 * 1024, 'max_package_size' => 66 * 1024 * 1024,
]; ];
+1 -1
View File
@@ -1,3 +1,3 @@
<?php <?php
return ['enable' => true, 'middleware' => []]; return ['enable' => true, 'middleware' => [App\Middleware\PublicAssets::class]];
+150
View File
@@ -53,3 +53,153 @@
.password-form { max-width: 37rem; } .password-form { max-width: 37rem; }
.admin-form button:disabled, .admin-bar button:disabled { cursor: progress; opacity: .65; } .admin-form button:disabled, .admin-bar button:disabled { cursor: progress; opacity: .65; }
.admin-form .ajax-feedback { margin: 0; } .admin-form .ajax-feedback { margin: 0; }
.studio-frame-window { position: relative; height: min(67vh, 39rem); overflow: hidden; margin-bottom: .8rem; border: 1px solid var(--line); border-radius: .55rem; background: var(--paper); }
.studio-frame-window iframe { display: block; width: 100%; height: 100%; border: 0; background: white; }
.studio-frame-window.has-scaled-preview iframe { position: absolute; top: 0; transform-origin: 0 0; }
.studio-canvas-toolbar { margin-bottom: .55rem; }
.studio-canvas-toolbar button:disabled { opacity: .5; cursor: default; }
.preview-selector { display: flex; gap: .35rem; flex-wrap: wrap; }
.preview-selector [aria-pressed="true"] { background: var(--accent-light); color: var(--accent-deep); }
.studio-inspector details label { margin-top: .7rem; }
.studio-blocks form, .studio-block-actions { display: flex; align-items: center; flex-wrap: wrap; gap: .32rem; }
.studio-blocks .button { padding-inline: .65rem; }
.studio-block-add { margin-top: 1.25rem; }
.studio-rich { min-height: 15rem; max-width: 100%; overflow-x: auto; padding: 1rem; background: #fff; border: 1px solid var(--line); border-radius: .55rem; }
.studio-rich:focus { outline: 2px solid var(--accent); outline-offset: 2px; }
.studio-rich details { margin-bottom: .5rem; }
.studio-rich img, .studio-rich video { max-width: 100%; height: auto; }
.asset-field { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: end; gap: .55rem; }
.settings-form { max-width: 54rem; }
.media-grid, .picker-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr)); gap: .8rem; }
.media-card, .picker-item { min-width: 0; border: 1px solid var(--line); border-radius: .65rem; background: white; padding: .75rem; overflow-wrap: anywhere; }
.media-card > img, .picker-item img, .media-file-type { height: 6rem; width: 100%; object-fit: contain; background: var(--paper); border-radius: .45rem; margin-bottom: .7rem; }
.media-card .media-file-type { display: grid; place-items: center; font-size: 1.1rem; text-transform: uppercase; }
.media-card h3 { font-size: 1rem; margin-bottom: 0; }
.media-card small { color: var(--muted); }
.media-card .actions { margin: .45rem 0; }
.media-card .button { padding-inline: .55rem; }
.media-card .media-archive { display: flex; align-items: center; }
.media-card .media-archive input { width: auto; min-height: 0; }
.media-picker { max-width: min(92vw, 52rem); max-height: 86vh; width: 100%; padding: 1.25rem; border: 1px solid var(--line); border-radius: var(--radius); color: var(--ink); }
.media-picker.canvas-properties { max-width: min(92vw, 32rem); }
.media-picker::backdrop { background: #101c3488; }
.media-picker label { display: grid; gap: .35rem; }
.media-picker input { padding: .55rem .75rem; border: 1px solid var(--line); border-radius: .4rem; }
.picker-grid { max-height: 50vh; overflow: auto; padding: .25rem; }
.picker-item { text-align: left; min-height: 44px; }
.picker-item:hover { border-color: var(--accent); }
@media (max-width: 65rem) {
}
.admin-wrap.admin-wide { width: calc(100% - clamp(1rem, 3vw, 3rem)); }
.studio-layout {
display: grid;
align-items: start;
grid-template-columns: minmax(12rem, 15rem) minmax(0, 1fr);
grid-template-areas: "library workspace" "library settings";
gap: .9rem;
}
.studio-library { grid-area: library; position: sticky; z-index: 3; top: .75rem; max-height: calc(100vh - 1.5rem); overflow: auto; }
.studio-library h2 { font-size: 1.05rem; margin-bottom: .7rem; }
.studio-workspace { grid-area: workspace; min-width: 0; }
.studio-inspector { grid-area: settings; }
.studio-workspace .studio-preview { padding: clamp(.55rem, 1.25vw, 1rem); }
.studio-workspace .studio-frame-window { height: max(34rem, calc(100dvh - 16rem)); }
.studio-workspace .studio-preview h2 { font-size: 1.2rem; }
.studio-presets { display: grid; gap: .4rem; }
.studio-library .studio-layers button:not(.button), .studio-pending button {
width: 100%;
min-height: 2.75rem;
padding: .55rem .75rem;
margin: 0;
border: 1px solid var(--line);
border-radius: .45rem;
background: var(--white);
color: var(--ink);
text-align: left;
}
.studio-library button:not(.button):hover { border-color: var(--accent); color: var(--accent); }
.studio-insert-mode { margin-block: .45rem .15rem; font-size: .875rem; }
.studio-pending { padding: 0; margin: 0; list-style: none; }
.studio-pending li + li { margin-top: .3rem; }
.studio-presets [role="status"]:empty { margin: 0; }
.studio-layers { border-top: 1px solid var(--line); margin-top: .85rem; padding-top: .55rem; }
.studio-layers summary { cursor: pointer; font-weight: 620; }
.studio-layers[open] > summary { margin-bottom: .55rem; }
.studio-library .studio-layers > button + button { margin-top: .3rem; }
.studio-layers .studio-blocks li { display: grid; gap: .4rem; }
.studio-layers .studio-block-actions .button { min-height: 2.25rem; padding: .25rem .5rem; font-size: .8rem; }
.studio-media-sizing { position: absolute; z-index: 1; inset: auto .6rem .6rem auto; display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; padding: .45rem .6rem; max-width: calc(100% - 1.2rem); background: var(--accent-light); border: 1px solid var(--line); border-radius: .45rem; }
.studio-media-sizing select { margin-inline-start: .3rem; }
.studio-media-sizing .button { min-height: 2.2rem; padding: .25rem .7rem; }
@media (max-width: 54rem) {
.studio-layout { grid-template-columns: minmax(0, 1fr); grid-template-areas: "library" "workspace" "settings"; }
.studio-library { position: static; max-height: none; }
.studio-workspace .studio-frame-window { height: max(25rem, 64dvh); }
}
.studio-template-search { display: grid; gap: .3rem; font-size: .9rem; font-weight: 600; }
.studio-template-search input {
width: 100%;
min-height: 42px;
padding: .45rem .6rem;
color: var(--ink);
background: var(--white);
border: 1px solid var(--line);
border-radius: .5rem;
}
.studio-template-filters { display: flex; gap: .3rem; flex-wrap: wrap; margin-block: .25rem; }
.studio-template-filters button {
min-height: 36px;
padding: .2rem .5rem;
color: var(--muted);
font-size: .825rem;
border: 1px solid var(--line);
border-radius: .35rem;
background: var(--white);
}
.studio-template-filters button[aria-pressed="true"] { border-color: #9bb5fa; color: var(--accent-deep); background: var(--accent-light); }
.studio-template-group + .studio-template-group { margin-top: .9rem; }
.studio-template-group h3 { margin: 0 0 .4rem; font-size: .9rem; font-weight: 650; }
.studio-template-cards { display: grid; gap: .48rem; }
.studio-template-card { min-width: 0; border: 1px solid var(--line); border-radius: .55rem; background: var(--white); }
.studio-template-card:focus-within { border-color: var(--accent); }
.studio-template-image {
display: block;
width: 100%;
padding: 0;
overflow: hidden;
border: 0;
border-radius: .5rem .5rem 0 0;
background: var(--paper);
}
.studio-template-image img { display: block; width: 100%; height: auto; aspect-ratio: 8 / 5; transition: transform .16s ease; }
.studio-template-image:hover img, .studio-template-image:focus-visible img { transform: scale(1.07); }
.studio-template-meta { display: flex; align-items: center; justify-content: space-between; gap: .3rem; padding: .3rem .38rem .3rem .55rem; font-size: .875rem; }
.studio-template-meta .button { min-height: 33px; font-size: .8rem; flex: 0 0 auto; padding: .2rem .45rem; }
.studio-template-peek {
position: fixed;
z-index: 2;
overflow: hidden;
pointer-events: none;
background: var(--white);
border: 1px solid #adbfdf;
border-radius: .65rem;
box-shadow: 0 14px 35px #142e5626;
}
.studio-template-peek img, .studio-template-dialog img { width: 100%; height: auto; aspect-ratio: 8 / 5; display: block; }
.studio-template-peek p { padding: .5rem .8rem; margin: 0; font-size: .9rem; color: var(--ink); }
.studio-template-dialog { width: min(90vw, 49rem); }
.studio-template-dialog > img { border: 1px solid var(--line); border-radius: .55rem; }
.studio-template-dialog > .actions { justify-content: flex-end; margin-top: .75rem; }
@media (max-width: 54rem) {
.studio-template-groups { max-height: 44dvh; overflow-y: auto; padding: .2rem; }
.studio-template-cards { grid-template-columns: repeat(auto-fill, minmax(8.5rem, 1fr)); }
.studio-template-meta { flex-wrap: wrap; }
.studio-template-peek { display: none; }
}
@media (prefers-reduced-motion: reduce) {
.studio-template-image img { transition: none; }
}
+37 -5
View File
@@ -16,6 +16,18 @@ jQuery(function ($) {
} }
}; };
function clearSavedStatus() {
$('[data-save-confirmation]').prop('hidden', true);
}
if (document.querySelector('[data-save-confirmation]')) {
const url = new URL(window.location.href);
if (url.searchParams.get('saved') === '1') {
url.searchParams.delete('saved');
window.history.replaceState(window.history.state, '', url.href);
}
}
function refreshToken(response) { function refreshToken(response) {
if (response?.csrf) { if (response?.csrf) {
$('input[name="csrf"]').val(response.csrf); $('input[name="csrf"]').val(response.csrf);
@@ -37,34 +49,53 @@ jQuery(function ($) {
$feedback.prop('hidden', false).trigger('focus'); $feedback.prop('hidden', false).trigger('focus');
} }
document.addEventListener('invalid', (event) => {
if (event.target.form?.method.toLowerCase() === 'post') clearSavedStatus();
}, true);
$('form[method="post"]').on('submit', function (event) { $('form[method="post"]').on('submit', function (event) {
event.preventDefault(); event.preventDefault();
const $form = $(this); const $form = $(this);
if ($form.attr('aria-busy') === 'true') return; if ($form.attr('aria-busy') === 'true') return;
const submitter = event.originalEvent?.submitter;
if (submitter?.dataset.confirm && !window.confirm(submitter.dataset.confirm)) return;
clearSavedStatus();
const action = $form.attr('action'); const action = $form.attr('action');
const isLogin = action === '/admin/login'; const isLogin = action === '/admin/login';
const $submit = $form.find(':submit'); const $submit = $form.find(':submit:enabled');
const multipart = $form.attr('enctype') === 'multipart/form-data';
$form.attr('aria-busy', 'true').children('.ajax-feedback').prop('hidden', true); $form.attr('aria-busy', 'true').children('.ajax-feedback').prop('hidden', true);
$submit.prop('disabled', true); $submit.prop('disabled', true);
$form.triggerHandler('studio:busy', [true]);
function finish() { function finish() {
$form.removeAttr('aria-busy'); $form.removeAttr('aria-busy');
$submit.prop('disabled', false); $submit.prop('disabled', false);
$form.triggerHandler('studio:busy', [false]);
} }
function submit(canRetryLogin) { function submit(canRetryLogin) {
$form.triggerHandler('studio:sync');
const fields = multipart ? new FormData($form.get(0)) : $form.serializeArray();
if (submitter?.name) {
if (multipart) fields.append(submitter.name, submitter.value);
else fields.push({name: submitter.name, value: submitter.value});
}
$.ajax({ $.ajax({
url: action, url: action,
method: 'POST', method: 'POST',
data: $form.serialize(), data: fields,
processData: !multipart,
contentType: multipart ? false : 'application/x-www-form-urlencoded; charset=UTF-8',
dataType: 'json' dataType: 'json'
}).done(function (response) { }).done(function (response) {
if (response.redirect) { if (response.redirect) {
$form.triggerHandler('studio:saved');
window.location.assign(response.redirect); window.location.assign(response.redirect);
return; return;
} }
formError($form, '未收到保存结果,请刷新页面确认。');
finish(); finish();
formError($form, '未收到保存结果,请刷新页面确认。');
}).fail(function (request) { }).fail(function (request) {
const response = request.responseJSON; const response = request.responseJSON;
refreshToken(response); refreshToken(response);
@@ -72,8 +103,8 @@ jQuery(function ($) {
submit(false); submit(false);
return; return;
} }
formError($form, response?.message || '请求未完成,请稍后重试。', request.status);
finish(); finish();
formError($form, response?.message || '请求未完成,请稍后重试。', request.status);
}); });
} }
@@ -82,6 +113,7 @@ jQuery(function ($) {
$('[data-editor]').each(function () { $('[data-editor]').each(function () {
const $editor = $(this); const $editor = $(this);
if ($editor.find('[data-rich-canvas]').length) return;
const area = $editor.find('textarea').get(0); const area = $editor.find('textarea').get(0);
const format = $editor.data('format'); const format = $editor.data('format');
const $preview = $editor.find('.editor-preview'); const $preview = $editor.find('.editor-preview');
@@ -116,7 +148,7 @@ jQuery(function ($) {
if (status === 'abort') return; if (status === 'abort') return;
let feedback = request.responseJSON; let feedback = request.responseJSON;
if (!feedback && request.getResponseHeader('Content-Type')?.startsWith('application/json')) { if (!feedback && request.getResponseHeader('Content-Type')?.startsWith('application/json')) {
feedback = JSON.parse(request.responseText); try { feedback = JSON.parse(request.responseText); } catch { /* Use the fallback feedback. */ }
} }
refreshToken(feedback); refreshToken(feedback);
$preview.text(feedback?.message || '预览无法加载,请重试。'); $preview.text(feedback?.message || '预览无法加载,请重试。');
+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 72" width="72" height="72">
<rect width="72" height="72" rx="19" fill="#e6f5f1"/>
<rect x="16.5" y="20.5" width="39" height="31" rx="5" fill="#bfe4da" stroke="#0c775f" stroke-width="2.5"/>
<path d="m30 31-6 5 6 5m12-10 6 5-6 5m-4-12-4 14" fill="none" stroke="#0c775f" stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5"/>
</svg>

After

Width:  |  Height:  |  Size: 405 B

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

After

Width:  |  Height:  |  Size: 440 B

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

After

Width:  |  Height:  |  Size: 432 B

+195
View File
@@ -371,3 +371,198 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
.payment-methods { display: flex; gap: .65rem; align-items: center; margin-block: .5rem; } .payment-methods { display: flex; gap: .65rem; align-items: center; margin-block: .5rem; }
.payment-methods img { width: 1.625rem; height: 1.625rem; object-fit: contain; } .payment-methods img { width: 1.625rem; height: 1.625rem; object-fit: contain; }
.hero-inner.hero-text-only { grid-template-columns: minmax(0, 1fr); min-height: 28rem; }
.hero-directory > .directory-label { border-inline-start: 0; }
.catalog-hero { background: var(--paper); padding-block: clamp(3rem, 6vw, 6rem); }
.catalog-hero h1 { margin-bottom: .85rem; }
.catalog-hero p { margin: 0; font-size: 1.15rem; }
.catalog-listing { padding-block: clamp(3rem, 6vw, 6rem); }
.catalog-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: clamp(1rem, 3vw, 2rem); }
.catalog-card { min-width: 0; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; display: flex; flex-direction: column; }
.catalog-image { aspect-ratio: 16 / 8; padding: clamp(.8rem, 3vw, 1.8rem); background: var(--paper); display: grid; place-items: center; }
.catalog-image img { max-height: 100%; width: 100%; height: 100%; object-fit: contain; }
.catalog-content { padding: clamp(1.25rem, 3vw, 2rem); flex: 1; display: flex; flex-direction: column; }
.catalog-content h2 { font-size: clamp(1.45rem, 3vw, 2.6rem); margin-bottom: .7rem; }
.catalog-content .overline { margin-bottom: .4rem; }
.catalog-content .actions { margin-top: auto; padding-top: 1rem; }
.hero-shnu-sc ~ #benefits { background: #f7f9fe; padding-block: clamp(3.25rem, 6vw, 6rem); }
.hero-shnu-sc ~ #benefits .section-heading { margin-bottom: 1.25rem; }
.hero-shnu-sc ~ #benefits h2 { font-size: clamp(1.85rem, 3.35vw, 3rem); }
.hero-shnu-sc ~ #benefits .rich > p { margin-bottom: .85rem; }
.hero-shnu-sc ~ #benefits .rich > ul { padding-left: 1.35rem; }
.hero-shnu-sc ~ #benefits .rich > ul li + li { margin-top: .35rem; }
.hero-shnu-sc ~ #benefits .rich > ul li::marker { color: var(--accent); }
.hero-shnu-sc ~ #benefits .rich > img {
width: var(--studio-media-width, 100%);
max-width: 100%;
border-radius: var(--radius);
box-shadow: 0 .75rem 2.25rem #101c341a;
}
@media (min-width: 52rem) {
.hero-shnu-sc ~ #benefits > .wrap:has(> .rich > p:first-child + ul + img:last-child) {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1.2fr);
gap: .8rem clamp(2rem, 5vw, 5.5rem);
align-content: center;
}
.hero-shnu-sc ~ #benefits > .wrap:has(> .rich > p:first-child + ul + img:last-child) > .rich { display: contents; }
.hero-shnu-sc ~ #benefits > .wrap:has(> .rich > p:first-child + ul + img:last-child) :is(.section-heading, .rich > p, .rich > ul) {
grid-column: 1;
margin-bottom: 0;
}
.hero-shnu-sc ~ #benefits > .wrap:has(> .rich > p:first-child + ul + img:last-child) .rich > img {
grid-column: 2;
grid-row: 1 / span 3;
align-self: center;
}
}
.copyright-service #materials .feature-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.copyright-service #why .choice-card { background: #e9f0ff; border-color: #7599ec; box-shadow: inset 0 3px var(--accent); }
.copyright-service #why .choice-card h3 { color: var(--accent-deep); }
.copyright-service #options .feature-card { display: flex; flex-direction: column; align-items: flex-start; }
.copyright-service #options .feature-card > img { width: 3.6rem; height: 3.6rem; margin-bottom: .95rem; }
.copyright-service #options .feature-card > a { margin-top: auto; }
.copyright-service #faq .faq { max-width: none; }
.copyright-service #faq summary { font-size: clamp(1.05rem, 1.35vw, 1.2rem); min-height: 3.75rem; }
.copyright-service #faq details > div { max-width: 75ch; }
.copyright-service #go { padding-block: clamp(2rem, 5vw, 4rem); background: var(--white); }
.copyright-service #go > .wrap {
position: relative;
padding: clamp(1.5rem, 5vw, 4.5rem);
padding-right: clamp(11rem, 29vw, 23rem);
border-radius: var(--radius);
background: radial-gradient(ellipse at 88% 110%, #264b9a 0, transparent 59%), #132443;
color: var(--white);
min-height: 16rem;
display: flex;
flex-direction: column;
justify-content: center;
}
.copyright-service #go .section-heading { margin-bottom: .8rem; }
.copyright-service #go h2 { font-size: clamp(1.8rem, 4vw, 3.5rem); }
.copyright-service #go .contact-panel { display: block; }
.copyright-service #go .contact-panel p { color: #d9e8ff; max-width: 40ch; }
.copyright-service #go .contact-panel img {
position: absolute;
top: 50%;
right: clamp(1.5rem, 6vw, 6rem);
transform: translateY(-50%);
width: clamp(8rem, 13vw, 12rem);
padding: .5rem;
border: 0;
border-radius: .85rem;
background: white;
}
.copyright-service #go .button { color: #142956; background: #eef4ff; border-color: #eef4ff; }
.copyright-service #terms { padding-block: 1.4rem 2.5rem; border-top: 0; }
.copyright-service #terms .section-heading { margin-bottom: .35rem; }
.copyright-service #terms h2 { font-size: .95rem; letter-spacing: 0; }
.copyright-service #terms .rich { font-size: .875rem; color: var(--muted); }
@media (max-width: 62rem) {
.copyright-service #materials .feature-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (max-width: 44rem) {
.catalog-grid, .copyright-service #materials .feature-grid { grid-template-columns: 1fr; }
.hero-directory > .directory-label { grid-column: 1 / -1; border-top: 0; }
.copyright-service #go > .wrap { padding: 1.55rem; min-height: 0; }
.copyright-service #go .contact-panel { display: flex; gap: 1rem; }
.copyright-service #go .contact-panel img { position: static; transform: none; width: 7rem; }
}
.hero h1 .hero-heading-primary { color: inherit; }
.studio-accent { display: block; }
[data-studio-editing] [contenteditable], [data-studio-editing] [data-studio-action],
[data-studio-editing] [data-studio-navigation] a, [data-studio-editing] [data-studio-hero-image] {
outline: 1px dashed #7896d5;
outline-offset: 3px;
}
[data-studio-editing] [contenteditable]:focus { outline: 2px solid #4477f9; }
[data-studio-editing] :is([data-studio-action], [data-studio-navigation] a, [data-studio-hero-image], .rich :is(img, video, audio)) { cursor: pointer; }
[data-studio-editing] [data-studio-placeholder]:empty::before {
content: attr(data-studio-placeholder);
color: var(--muted);
font: 400 1rem / 1.5 var(--sans);
}
.home-cursor {
display: inline-block;
width: .52em;
margin-inline-start: .08em;
font-family: var(--mono);
font-size: .7em;
animation: home-cursor-blink 1.1s steps(1, end) 5;
}
@keyframes home-cursor-blink { 50% { opacity: 0; } }
.home-pipe-flow {
position: absolute;
inset: clamp(.45rem, 1.8vw, 1.7rem);
pointer-events: none;
}
.home-pipe-flow span {
position: absolute;
width: clamp(.3rem, .68vw, .63rem);
aspect-ratio: 1;
border-radius: 50%;
background: #e3fbff;
box-shadow: 0 0 .4rem .1rem #78d7ff, 0 0 .8rem .16rem #3882ff;
translate: -50% -50%;
animation: home-pipe-pulse 2.8s linear 2 both;
}
.home-pipe-flow span:nth-child(1) {
--pipe-start: 72% auto auto 27.4%; --pipe-turn: 64% auto auto 38.3%; --pipe-end: 59.1% auto auto 42.1%;
}
.home-pipe-flow span:nth-child(2) {
--pipe-start: 59.2% auto auto 64%; --pipe-turn: 64.2% auto auto 67.1%; --pipe-end: 70% auto auto 78.2%;
animation-delay: .35s;
}
.home-pipe-flow span:nth-child(3) {
--pipe-start: 42% auto auto 18.7%; --pipe-turn: 46.9% auto auto 23.4%; --pipe-end: 51% auto auto 29.8%;
animation-delay: .65s;
}
.home-pipe-flow span:nth-child(4) {
--pipe-start: 37% auto auto 77%; --pipe-turn: 42.5% auto auto 77%; --pipe-end: 47.7% auto auto 68.3%;
animation-delay: .9s;
}
@keyframes home-pipe-pulse {
0%, 16% { inset: var(--pipe-start); opacity: 0; }
21%, 67% { opacity: 1; }
40% { inset: var(--pipe-turn); }
72%, 100% { inset: var(--pipe-end); opacity: 0; }
}
@media (prefers-reduced-motion: reduce) {
.home-cursor { animation: none; }
.home-pipe-flow { display: none; }
}
.studio-split { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1.5rem; align-items: center; }
.studio-split > img { width: 100%; }
.studio-banner { padding: clamp(1.25rem, 4vw, 3.25rem); border-radius: var(--radius); background: var(--accent-light); }
@media (max-width: 44rem) { .studio-split { grid-template-columns: 1fr; } }
:where(img, video, audio, .hero-visual)[class*="studio-media-"] { max-width: 100%; }
:is(.rich, .hero-inner, .editor-preview) .studio-media-25 { --studio-media-width: 25%; width: var(--studio-media-width); }
:is(.rich, .hero-inner, .editor-preview) .studio-media-40 { --studio-media-width: 40%; width: var(--studio-media-width); }
:is(.rich, .hero-inner, .editor-preview) .studio-media-50 { --studio-media-width: 50%; width: var(--studio-media-width); }
:is(.rich, .hero-inner, .editor-preview) .studio-media-60 { --studio-media-width: 60%; width: var(--studio-media-width); }
:is(.rich, .hero-inner, .editor-preview) .studio-media-75 { --studio-media-width: 75%; width: var(--studio-media-width); }
:is(.rich, .hero-inner, .editor-preview) .studio-media-85 { --studio-media-width: 85%; width: var(--studio-media-width); }
:is(.rich, .hero-inner, .editor-preview) .studio-media-100 { --studio-media-width: 100%; width: var(--studio-media-width); }
.rich :is(img, video)[class*="studio-media-"] { height: auto; max-width: 100%; }
.hero-visual[class*="studio-media-"] { justify-self: center; }
[data-studio-editing] [data-studio-selected] { outline: 2px solid #4477f9; outline-offset: 3px; }
.rich .studio-intro { max-width: 47rem; }
.rich .studio-intro h3, .rich .studio-cover h3 { font-size: clamp(1.75rem, 4vw, 2.8rem); }
.rich .studio-cover { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.05fr); align-items: center; gap: clamp(1rem, 4vw, 3rem); background: var(--paper); padding: clamp(.8rem, 3vw, 2rem); border-radius: var(--radius); }
.rich .studio-cover img { width: 100%; }
.rich .studio-cover p { margin-bottom: .85rem; }
.rich .studio-two-column { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; }
.rich .studio-quick-nav { display: flex; flex-wrap: wrap; gap: .55rem 1rem; list-style: none; padding: .75rem; border: 1px solid var(--line); border-radius: .6rem; }
.rich .studio-quick-nav a { display: inline-flex; align-items: center; min-height: 44px; padding-inline: .4rem; font-weight: 600; }
@media (max-width: 44rem) {
.rich .studio-cover, .rich .studio-two-column { grid-template-columns: minmax(0, 1fr); }
}
+855
View File
@@ -0,0 +1,855 @@
'use strict';
jQuery(function ($) {
const $picker = $('#media-picker');
const $pickerItems = $picker.find('[data-picker-items]');
const $pickerStatus = $picker.find('[data-picker-status]');
let pick = null;
let files = [];
let mediaType = '';
let pickerRequest;
function safeLink(value, media = false) {
return value !== '' && !/[\u0000-\u0020\u007f\\]/.test(value)
&& (/^\/(?!\/)/.test(value) || (media ? /^https:\/\//i : /^(https?:\/\/|mailto:|tel:|#\S)/i).test(value));
}
function mediaMarkup(file) {
let $node;
if (file.mime.startsWith('image/')) {
const alt = window.prompt('图片替代文本(装饰图可留空)', file.label);
if (alt === null) return '';
$node = $('<img>', {src: file.url, alt, loading: 'lazy'});
} else if (file.mime.startsWith('video/') || file.mime.startsWith('audio/')) {
const tag = file.mime.startsWith('video/') ? '<video>' : '<audio>';
$node = $(tag, {src: file.url, controls: true, preload: 'metadata'});
} else {
$node = $('<a>', {href: file.url}).text(file.label);
}
return $node.prop('outerHTML');
}
function renderPicker() {
const query = String($picker.find('[data-media-query]').val() || '').trim().toLowerCase();
const results = files.filter((file) => file.mime.startsWith(mediaType)
&& (file.label + ' ' + file.url).toLowerCase().includes(query));
$pickerStatus.text(results.length ? results.length + ' 个资源' : '没有匹配资源。');
$pickerItems.empty();
for (const file of results) {
const $item = $('<button>', {type: 'button', class: 'picker-item'}).data('file', file);
if (file.mime.startsWith('image/')) {
$item.append($('<img>', {src: file.url, alt: '', loading: 'lazy'}));
}
$item.append($('<span>').text(file.label));
$pickerItems.append($item);
}
}
function openPicker(type, callback) {
if (!$picker.length || typeof $picker.get(0).showModal !== 'function') return;
pick = callback;
mediaType = type;
$picker.find('[data-media-query]').val('');
$pickerItems.empty();
$pickerStatus.text('加载资源…');
$picker.get(0).showModal();
pickerRequest?.abort();
pickerRequest = $.getJSON('/admin/media/options').done(function (response) {
files = response.files;
renderPicker();
}).fail(function (_request, status) {
if (status !== 'abort') $pickerStatus.text('媒体库暂时无法打开。');
});
}
$picker.on('input', '[data-media-query]', renderPicker);
$picker.on('click', '[data-close-picker]', () => $picker.get(0).close());
$picker.on('click', '.picker-item', function () {
const file = $(this).data('file');
$picker.get(0).close();
pick?.(file);
});
$('[data-asset-pick]').on('click', function () {
const $button = $(this);
const name = $button.data('asset-pick');
const $input = $button.closest('form').find('input').filter((_, field) => field.name === name);
openPicker($button.data('asset-type') || '', (file) => $input.val(file.url).trigger('input').trigger('focus'));
});
$('[data-copy-asset]').on('click', function () {
const $button = $(this);
const url = $button.data('copy-asset');
if (!navigator.clipboard) {
window.prompt('复制资源路径', url);
return;
}
navigator.clipboard.writeText(url).then(() => $button.text('已复制')).catch(() => window.prompt('复制资源路径', url));
});
$('[data-media-library]').each(function () {
const $library = $(this);
const $cards = $library.find('[data-library-card]');
function filter() {
const query = String($library.find('[data-library-query]').val()).trim().toLowerCase();
const category = $library.find('[data-library-type]').val();
let count = 0;
$cards.each(function () {
const $card = $(this);
const mime = $card.data('mime');
const matchesType = category === 'other' ? !/^(image|audio|video)\//.test(mime) : mime.startsWith(category);
const visible = matchesType && $card.data('search').toLowerCase().includes(query);
$card.prop('hidden', !visible);
if (visible) count++;
});
$library.find('[data-library-count]').text(count + ' 个资源');
}
$library.on('input change', '[data-library-query], [data-library-type]', filter);
filter();
});
function bodyEdits(original, edited) {
// Work in Unicode code points, then encode offsets in UTF-8 for PHP.
const before = Array.from(original);
const after = Array.from(edited);
const encoder = new TextEncoder();
const anchorSize = 32;
let start = 0;
let beforeEnd = before.length;
let afterEnd = after.length;
while (start < beforeEnd && start < afterEnd && before[start] === after[start]) start++;
while (beforeEnd > start && afterEnd > start && before[beforeEnd - 1] === after[afterEnd - 1]) {
beforeEnd--;
afterEnd--;
}
if (beforeEnd === start && afterEnd === start) return [];
const anchors = new Map();
for (let index = start; index + anchorSize <= beforeEnd; index += anchorSize) {
const key = before.slice(index, index + anchorSize).join('');
if (!anchors.has(key)) anchors.set(key, []);
anchors.get(key).push(index);
}
const edits = [];
let oldIndex = start;
let newIndex = start;
let byteOffset = encoder.encode(before.slice(0, start).join('')).length;
function copy() {
const first = oldIndex;
while (oldIndex < beforeEnd && newIndex < afterEnd && before[oldIndex] === after[newIndex]) {
oldIndex++;
newIndex++;
}
byteOffset += encoder.encode(before.slice(first, oldIndex).join('')).length;
}
function replace(oldEnd, newEnd) {
if (oldEnd === oldIndex && newEnd === newIndex) return;
const removed = encoder.encode(before.slice(oldIndex, oldEnd).join('')).length;
edits.push([byteOffset, removed, after.slice(newIndex, newEnd).join('')]);
byteOffset += removed;
oldIndex = oldEnd;
newIndex = newEnd;
}
for (let scan = start; scan + anchorSize <= afterEnd && edits.length < 511; scan++) {
const matches = anchors.get(after.slice(scan, scan + anchorSize).join(''));
if (!matches) continue;
let low = 0;
let high = matches.length;
while (low < high) {
const middle = Math.floor((low + high) / 2);
if (matches[middle] < oldIndex) low = middle + 1;
else high = middle;
}
if (low === matches.length) continue;
let nextOld = matches[low];
let nextNew = scan;
while (nextOld > oldIndex && nextNew > newIndex && before[nextOld - 1] === after[nextNew - 1]) {
nextOld--;
nextNew--;
}
replace(nextOld, nextNew);
copy();
scan = newIndex - 1;
}
replace(beforeEnd, afterEnd);
return edits;
}
$('[data-canvas-presets]').each(function () {
const $gallery = $(this);
const $search = $gallery.find('[data-template-search]');
const $groups = $gallery.find('[data-template-group]');
const $filters = $gallery.find('[data-template-filter]');
const $peek = $gallery.find('[data-template-peek]');
const $dialog = $gallery.find('[data-template-dialog]');
const $use = $dialog.find('[data-template-use]');
let category = '';
let $selection;
function hidePeek() {
$peek.prop('hidden', true);
}
function filter() {
const query = String($search.val()).trim().toLowerCase();
let count = 0;
$groups.each(function () {
const $group = $(this);
const allowed = !category || this.dataset.templateGroup === category;
let groupCount = 0;
$group.find('[data-template-card]').each(function () {
const visible = allowed && this.dataset.templateSearchText.toLowerCase().includes(query);
$(this).prop('hidden', !visible);
if (visible) groupCount++;
});
$group.prop('hidden', groupCount === 0);
count += groupCount;
});
$gallery.find('[data-template-empty]').prop('hidden', count !== 0);
hidePeek();
}
$search.on('input', filter);
$filters.on('click', function () {
category = this.dataset.templateFilter;
$filters.attr('aria-pressed', 'false');
$(this).attr('aria-pressed', 'true');
filter();
});
$gallery.on('mouseenter focusin', '[data-template-preview]', function (event) {
if (event.type === 'mouseenter' && !matchMedia('(hover: hover)').matches) return;
const bounds = this.getBoundingClientRect();
const width = Math.min(430, window.innerWidth - bounds.right - 24);
if (width < 240) return;
const top = Math.max(12, Math.min(bounds.top, window.innerHeight - width * 0.625 - 56));
$peek.find('img').attr('src', $(this).find('img').attr('src'));
$peek.find('p').text(this.dataset.templateTitle);
$peek.css({width, top, left: bounds.right + 12}).prop('hidden', false);
});
$gallery.on('mouseleave focusout', '[data-template-preview]', hidePeek);
$gallery.closest('.studio-library').on('scroll', hidePeek);
$(window).on('scroll resize', hidePeek);
$gallery.on('click', '[data-template-preview]', function () {
hidePeek();
const $card = $(this).closest('[data-template-card]');
$selection = $card.find('[data-canvas-template]');
$dialog.find('h2').text(this.dataset.templateTitle);
$dialog.find('img').attr('src', $(this).find('img').attr('src'));
$use.prop('disabled', $selection.prop('disabled'));
$dialog.get(0).showModal();
});
$dialog.on('click', '[data-template-close]', () => $dialog.get(0).close());
$use.on('click', () => {
if (!$selection || $selection.prop('disabled')) return;
$dialog.get(0).close();
hidePeek();
$selection.trigger('click');
});
$gallery.on('studio:canvas-ready', () => {
if ($selection) $use.prop('disabled', $selection.prop('disabled'));
});
});
$('[data-preview-studio]').each(function () {
const $studio = $(this);
const $frame = $studio.find('iframe');
const $window = $studio.find('.studio-frame-window');
function fitPreview() {
const width = $window.width();
const height = $window.height();
if (!width || !height) return;
const viewport = $studio.hasClass('studio-phone') ? 390 : Math.max(1280, width);
const scale = Math.min(1, width / viewport);
$window.addClass('has-scaled-preview');
$frame.css({
width: viewport,
height: height / scale,
left: (width - viewport * scale) / 2,
transform: 'scale(' + scale + ')'
});
}
if ('ResizeObserver' in window) {
new ResizeObserver(fitPreview).observe($window.get(0));
} else {
$(window).on('resize', fitPreview);
}
fitPreview();
const $layout = $studio.closest('.studio-layout');
const $settings = $layout.find('.studio-inspector');
const $sizing = $studio.find('[data-media-sizing]');
const $width = $sizing.find('[data-media-width]');
const availableWidths = Array.from($width.get(0).options, ({value}) => value).filter((value) => value !== '0');
const sizeClasses = availableWidths.map((value) => 'studio-media-' + value);
const $presets = $layout.find('[data-canvas-presets]');
const $templateStatus = $presets.find('[data-template-status]');
const $pending = $presets.find('[data-template-pending]');
const heroControls = new Map();
let selectedMedia;
$studio.on('click', '[data-preview-size]', function () {
const $button = $(this);
$studio.toggleClass('studio-phone', $button.data('preview-size') === 'phone');
$studio.find('[data-preview-size]').attr('aria-pressed', 'false');
$button.attr('aria-pressed', 'true');
fitPreview();
});
const $toolbar = $studio.find('[data-canvas-toolbar]');
const $commands = $toolbar.find('[data-canvas-command]');
const $properties = $studio.find('[data-canvas-properties]');
const $propertyForm = $properties.find('form');
const $propertyError = $properties.find('[data-property-error]');
const propertyInput = (name) => $propertyForm.find('[name="' + name + '"]');
const pageInput = (name) => $settings.find('[name="' + name + '"]');
const settingsSnapshot = () => $settings.serializeArray()
.filter(({name}) => name !== 'csrf' && name !== 'canvas_sections');
const savedSettings = JSON.stringify(settingsSnapshot());
let dialogAction;
let doc;
let activeBody;
let savedRange;
let sections = [];
let saveComplete = false;
function sectionChanges(withEdits = true) {
return sections.flatMap(({key, version, fields, source}) => {
const changes = {};
for (const [field, {node, initial}] of Object.entries(fields)) {
const value = field === 'body' ? node.innerHTML : node.textContent;
if (version === null || value !== initial) {
changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value;
}
}
return Object.keys(changes).length ? [{key, version, fields: changes}] : [];
});
}
$settings.on('studio:sync', () => pageInput('canvas_sections').val(JSON.stringify(sectionChanges())));
$settings.on('studio:saved', () => { saveComplete = true; });
$settings.on('studio:busy', (_event, busy) => {
$layout.prop('inert', busy);
$settings.prop('inert', busy);
});
$(window).on('beforeunload', (event) => {
if (!saveComplete && (sectionChanges(false).length || JSON.stringify(settingsSnapshot()) !== savedSettings)) {
event.preventDefault();
event.originalEvent.returnValue = '';
}
});
function openProperties(heading, values, apply, mime = null, allowEmptyUrl = false) {
$properties.find('[data-property-heading]').text(heading);
$propertyError.prop('hidden', true);
for (const key of ['label', 'url', 'alt', 'poster', 'quicklinks']) {
const visible = Object.hasOwn(values, key);
$propertyForm.find('[data-property-row="' + key + '"]').prop('hidden', !visible);
propertyInput(key).val(visible ? values[key] : '');
}
$properties.find('[data-property-pick="url"]').prop('hidden', mime === null);
$properties.find('[data-property-pick="poster"]').prop('hidden', !Object.hasOwn(values, 'poster'));
dialogAction = {values, apply, mime, allowEmptyUrl};
$properties.get(0).showModal();
}
$properties.on('click', '[data-property-close]', () => $properties.get(0).close());
$properties.on('click', '[data-property-pick]', function () {
const field = this.dataset.propertyPick;
openPicker(field === 'poster' ? 'image/' : dialogAction.mime,
(file) => propertyInput(field).val(file.url).trigger('focus'));
});
$propertyForm.on('submit', (event) => {
event.preventDefault();
const {values, apply, mime, allowEmptyUrl} = dialogAction;
const result = Object.fromEntries(Object.keys(values).map((field) => [field, propertyInput(field).val().trim()]));
if ((Object.hasOwn(result, 'url') && ((!result.url && !allowEmptyUrl) || (result.url && !safeLink(result.url, mime !== null))))
|| (result.poster && !safeLink(result.poster, true))) {
$propertyError.prop('hidden', false).text('请输入有效的站内地址或链接。媒体也可使用 HTTPS 地址。');
return;
}
if (apply(result) !== false) $properties.get(0).close();
});
function rememberSelection() {
const selection = doc.getSelection();
if (selection.rangeCount && activeBody?.contains(selection.anchorNode) && activeBody.contains(selection.focusNode)) {
savedRange = selection.getRangeAt(0).cloneRange();
}
}
function selectBody(body) {
if (body !== activeBody) {
activeBody = body;
savedRange = null;
}
$commands.prop('disabled', !activeBody);
}
function editBody(body, range, command, value) {
if (!body?.isConnected) return;
body.focus();
const selection = doc.getSelection();
if (!range || !body.contains(range.commonAncestorContainer)) {
range = doc.createRange();
range.selectNodeContents(body);
range.collapse(false);
}
selection.removeAllRanges();
selection.addRange(range);
doc.execCommand(command, false, value);
rememberSelection();
}
$toolbar.on('mousedown', '[data-canvas-command]', (event) => event.preventDefault());
$toolbar.on('click', '[data-canvas-command]', function () {
const command = this.dataset.canvasCommand;
const body = activeBody;
const range = savedRange?.cloneRange();
const edit = (action, value) => editBody(body, range, action, value);
if (command === 'media') {
openPicker('', (file) => {
const markup = mediaMarkup(file);
if (markup) edit('insertHTML', markup);
});
} else if (command === 'link') {
openProperties('插入链接', {label: range?.toString() || '', url: ''}, ({label, url}) => {
queueMicrotask(() => {
if (range && !range.collapsed && label === range.toString()) {
edit('createLink', url);
} else {
edit('insertHTML', $('<a>', {href: url}).text(label || url).prop('outerHTML'));
}
});
});
} else {
const commands = {heading: ['formatBlock', 'h3'], bold: ['bold'], list: ['insertUnorderedList']};
edit(...commands[command]);
}
});
function configureText(node, label, placeholder = false) {
node.contentEditable = 'plaintext-only';
node.setAttribute('aria-label', label);
if (placeholder) node.dataset.studioPlaceholder = label;
}
function bindPage($doc) {
const labels = {name: '页面名称', heading: '首屏标题', accent: '标题第二行', lead: '首屏简介'};
$doc.find('[data-studio-field]').each(function () {
const field = this.dataset.studioField;
const $target = $(this);
const $input = pageInput(field);
configureText(this, labels[field], ['accent', 'lead'].includes(field));
$target.text($input.val()).on('input', () => $input.val($target.text()));
$input.on('input.canvas', () => $target.text($input.val()));
});
const $image = $doc.find('[data-studio-hero-image]');
const $visual = $image.parent();
function syncImage() {
const path = pageInput('image').val().trim();
const valid = safeLink(path, true);
setMediaWidth($visual.get(0), pageInput('image_scale').val());
$visual.prop('hidden', !valid).parent().toggleClass('hero-text-only', !valid);
if (valid) $image.attr('src', path);
else $image.removeAttr('src');
$image.attr('alt', pageInput('alt').val());
}
$settings.find('[name="image"], [name="alt"]').on('input.canvas', syncImage);
syncImage();
$image.attr({tabindex: '0', role: 'button', 'aria-label': '编辑首屏图片'});
heroControls.set('image', () => {
openProperties('首屏图片', {url: pageInput('image').val(), alt: pageInput('alt').val()}, ({url, alt}) => {
pageInput('image').val(url);
pageInput('alt').val(alt);
syncImage();
}, 'image/', true);
});
$doc.find('[data-studio-action]').each(function () {
const $button = $(this);
const index = this.dataset.studioAction;
const $label = pageInput('label' + index);
const $url = pageInput('url' + index);
function sync() {
const url = $url.val().trim();
$button.text($label.val()).attr('href', safeLink(url) ? url : '#').prop('hidden', !$label.val() && !url);
}
$label.add($url).on('input.canvas', sync);
const editButton = () => {
openProperties('首屏按钮', {label: $label.val(), url: $url.val()}, ({label, url}) => {
if (Boolean(label) !== Boolean(url)) {
$propertyError.prop('hidden', false).text('请同时填写按钮文案和链接,或将两项都留空。');
return false;
}
$label.val(label);
$url.val(url);
sync();
}, null, true);
};
heroControls.set(index, editButton);
$button.on('click', (event) => {
event.preventDefault();
editButton();
});
sync();
});
const $navigation = $doc.find('[data-studio-navigation]');
const $navContent = $navigation.find('.section-nav-inner');
const $navInput = pageInput('quicklinks');
const navLines = () => $navInput.val().split(/\r\n|[\n\r\v\f\u0085\u2028\u2029]/);
function syncNavigation() {
const lines = navLines();
$navContent.empty();
for (const [index, line] of lines.entries()) {
if (!line.trim()) continue;
const separator = line.indexOf('|');
const label = (separator < 0 ? line : line.slice(0, separator)).trim();
const url = separator < 0 ? '' : line.slice(separator + 1).trim();
const link = doc.createElement('a');
link.href = safeLink(url) ? url : '#';
link.textContent = label || url;
link.addEventListener('click', (event) => {
event.preventDefault();
openProperties('本页目录链接', {label, url}, (next) => {
if (!next.label || /[|\r\n]/.test(next.label)) {
$propertyError.prop('hidden', false).text('请填写目录文案,文案不能包含竖线。');
return false;
}
const updated = navLines();
updated[index] = next.label + ' | ' + next.url;
$navInput.val(updated.join('\n'));
syncNavigation();
});
});
$navContent.append(link);
}
$navigation.prop('hidden', !$navContent.children().length);
}
$navInput.on('input.canvas', syncNavigation);
heroControls.set('navigation', () => {
openProperties('本页目录', {quicklinks: $navInput.val()}, ({quicklinks}) => {
$navInput.val(quicklinks);
syncNavigation();
});
});
syncNavigation();
}
function editResource(node) {
const tag = node.localName;
if (tag === 'a') {
const onlyChild = node.firstElementChild;
const text = node.childElementCount === 0 ? node : (
node.childElementCount === 1 && onlyChild.matches('span, strong, b, em, i, small')
&& !onlyChild.childElementCount && node.textContent.trim() === onlyChild.textContent.trim() ? onlyChild : null
);
const values = text ? {label: text.textContent, url: node.getAttribute('href') || ''} : {url: node.getAttribute('href') || ''};
openProperties('正文链接', values, ({label, url}) => {
node.setAttribute('href', url);
if (text && label !== values.label) text.textContent = label;
});
return;
}
const source = tag === 'img' ? node : (node.hasAttribute('src') ? node : node.querySelector('source') || node);
const values = {url: source.getAttribute('src') || ''};
if (tag === 'img') values.alt = node.getAttribute('alt') || '';
if (tag === 'video') values.poster = node.getAttribute('poster') || '';
openProperties({img: '正文图片', video: '视频', audio: '音频'}[tag], values, ({url, alt, poster}) => {
if (url !== values.url) {
source.setAttribute('src', url);
if (source !== node) source.removeAttribute('type');
if (tag !== 'img') node.load();
}
if (alt !== undefined && alt !== values.alt) node.setAttribute('alt', alt);
if (poster !== undefined && poster !== values.poster) {
if (poster) node.setAttribute('poster', poster);
else node.removeAttribute('poster');
}
}, (tag === 'img' ? 'image' : tag) + '/');
}
function registerSection(section, version = Number(section.dataset.studioSection)) {
const fields = {};
for (const node of section.querySelectorAll('[data-studio-part]')) {
const part = node.dataset.studioPart;
const body = part === 'body';
const label = {title: '区块标题', lead: '添加区块简介', body: '区块正文'}[part];
if (body) {
node.contentEditable = 'true';
node.setAttribute('aria-label', label);
node.dataset.studioPlaceholder = label;
} else {
configureText(node, label, part === 'lead');
}
fields[part] = {node, initial: body ? node.innerHTML : node.textContent};
}
const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from(
atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0)
));
sections.push({key: section.id, version, fields, source});
}
function setMediaWidth(node, width) {
node.classList.remove(...sizeClasses);
if (availableWidths.includes(width)) node.classList.add('studio-media-' + width);
}
function selectMedia(node) {
selectedMedia?.removeAttribute('data-studio-selected');
selectedMedia = node;
if (!node) {
$sizing.prop('hidden', true);
return;
}
node.setAttribute('data-studio-selected', '');
const width = node.hasAttribute('data-studio-hero-image') ? pageInput('image_scale').val()
: availableWidths.find((value) => node.classList.contains('studio-media-' + value)) || '0';
$width.val(width);
$sizing.prop('hidden', false);
}
function replaceMedia() {
if (!selectedMedia?.isConnected) return;
if (selectedMedia.hasAttribute('data-studio-hero-image')) heroControls.get('image')();
else editResource(selectedMedia);
}
$width.on('change', function () {
if (!selectedMedia?.isConnected) return;
const hero = selectedMedia.hasAttribute('data-studio-hero-image');
if (hero) pageInput('image_scale').val(this.value);
setMediaWidth(hero ? selectedMedia.parentElement : selectedMedia, this.value);
});
$sizing.on('click', '[data-replace-media]', replaceMedia);
$layout.on('click', '[data-hero-control]', function () {
heroControls.get(this.dataset.heroControl)?.();
});
$presets.on('mousedown', '[data-canvas-template]', (event) => event.preventDefault());
$presets.on('click', '[data-canvas-template]', function () {
const markup = $presets.find('template[data-preset="' + this.dataset.canvasTemplate + '"]').get(0).innerHTML;
if ($presets.find('[data-template-inline]').prop('checked')) {
if (!activeBody) {
$templateStatus.text('先在画布中选择要插入的区块正文。');
return;
}
// Insert at the saved caret without replacing any selected text.
const insertion = savedRange?.cloneRange();
insertion?.collapse(false);
editBody(activeBody, insertion, 'insertHTML', markup);
$templateStatus.text('已插入当前正文。');
return;
}
if (sections.filter(({version}) => version === null).length >= 50) {
$templateStatus.text('请先保存,再添加更多区块。');
return;
}
const end = doc.querySelector('[data-studio-section-end]');
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('');
section.id = id;
const title = section.querySelector('[data-studio-part="title"]');
title.id = 'heading-' + id;
title.textContent = this.dataset.templateTitle;
section.setAttribute('aria-labelledby', title.id);
section.querySelector('[data-studio-part="body"]').innerHTML = markup;
end.before(section);
registerSection(section, null);
section.scrollIntoView({block: 'start'});
section.querySelector('[data-studio-part="body"]').focus({preventScroll: true});
const $cancel = $('<button>', {type: 'button', text: '取消新增:' + title.textContent});
const $item = $('<li>').append($cancel).appendTo($pending);
$pending.prop('hidden', false);
$cancel.on('click', () => {
if (section.contains(activeBody)) selectBody(null);
if (section.contains(selectedMedia)) selectMedia(null);
section.remove();
sections = sections.filter(({key}) => key !== id);
$item.remove();
$pending.prop('hidden', !$pending.children().length);
$templateStatus.text('已取消新增区块。');
});
$templateStatus.text('已添加 ' + title.textContent + ' 区块。');
});
function attachCanvas() {
doc = $frame.get(0).contentDocument;
if (!doc?.querySelector('[data-studio-field]') || doc.documentElement.hasAttribute('data-studio-editing')) return;
doc.documentElement.setAttribute('data-studio-editing', '');
const $doc = $(doc);
$settings.find(':input').off('.canvas');
bindPage($doc);
selectBody(null);
selectMedia(null);
$pending.empty().prop('hidden', true);
sections = [];
$doc.find('[data-studio-section]').each((_, section) => registerSection(section));
$doc.on('focusin.canvas', '[contenteditable]', function () {
selectBody(this.dataset.studioPart === 'body' ? this : null);
});
$doc.on('selectionchange.canvas', rememberSelection);
$doc.on('click.canvas', (event) => {
if (!event.target.closest?.('[data-studio-selected]')) selectMedia(null);
});
$doc.on('click.canvas auxclick.canvas', 'a', (event) => event.preventDefault());
const mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video';
$doc.on('click.canvas dblclick.canvas', mediaTargets, function (event) {
event.preventDefault();
event.stopPropagation();
selectBody(this.closest('[data-studio-part="body"]'));
selectMedia(this);
if (event.type === 'dblclick') replaceMedia();
});
$doc.on('click.canvas', '[data-studio-part="body"] a', function (event) {
event.preventDefault();
if ($(this).find('img, audio, video').length && event.target.closest('img, audio, video')) return;
selectBody(this.closest('[data-studio-part="body"]'));
editResource(this);
});
$doc.on('keydown.canvas', '[data-studio-hero-image]', function (event) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
selectMedia(this);
$width.trigger('focus');
}
});
$doc.on('beforeinput.canvas', '[contenteditable="plaintext-only"]', (event) => {
if (event.originalEvent?.inputType === 'insertParagraph' || event.originalEvent?.inputType === 'insertLineBreak') {
event.preventDefault();
}
});
$doc.on('paste.canvas drop.canvas', '[contenteditable]', (event) => {
event.preventDefault();
if (event.type === 'paste') {
doc.execCommand('insertText', false, event.originalEvent.clipboardData.getData('text/plain'));
}
});
$toolbar.prop('hidden', false);
$layout.find('[data-canvas-jump]').prop('hidden', false);
$layout.find('[data-canvas-template], [data-hero-control]').prop('disabled', false);
$presets.triggerHandler('studio:canvas-ready');
}
$frame.on('load', attachCanvas);
if ($frame.contents().find('[data-studio-field]').length) attachCanvas();
$studio.closest('.studio-layout').on('click', '[data-canvas-jump]', function () {
const section = doc?.getElementById(this.dataset.canvasJump);
const body = section?.querySelector('[data-studio-part="body"]');
if (!body) return;
$studio.get(0).scrollIntoView({block: 'start'});
section.scrollIntoView({block: 'start'});
body.focus({preventScroll: true});
});
});
$('[data-rich-canvas]').each(function () {
const $canvas = $(this);
const $editor = $canvas.closest('[data-editor]');
const $area = $editor.find('textarea');
const $form = $editor.closest('form');
const $status = $editor.find('[data-rich-status]');
const $visualButtons = $editor.find('[data-insert], [data-rich-media]');
let savedRange;
let source = false;
$area.prop('hidden', true);
$canvas.prop('hidden', false);
$form.on('studio:sync', () => {
if (!source) $area.val($canvas.html());
});
function restoreRange() {
const selection = window.getSelection();
const root = $canvas.get(0);
$canvas.trigger('focus');
if (!savedRange || !root.contains(savedRange.commonAncestorContainer)) {
savedRange = document.createRange();
savedRange.selectNodeContents(root);
savedRange.collapse(false);
}
selection.removeAllRanges();
selection.addRange(savedRange);
}
function edit(command, value) {
restoreRange();
document.execCommand(command, false, value);
}
$canvas.on('click', 'a', (event) => event.preventDefault());
$canvas.on('keyup mouseup focusout input', function () {
const selection = window.getSelection();
if (selection.rangeCount && this.contains(selection.anchorNode) && this.contains(selection.focusNode)) {
savedRange = selection.getRangeAt(0).cloneRange();
}
});
$canvas.on('paste', function (event) {
event.preventDefault();
document.execCommand('insertText', false, event.originalEvent.clipboardData.getData('text/plain'));
});
$editor.on('mousedown', '[data-insert], [data-rich-media]', (event) => event.preventDefault());
$editor.on('click', '[data-insert]', function () {
const command = $(this).data('insert');
if (command === 'link') {
const href = window.prompt('输入链接地址', 'https://')?.trim();
if (!href) return;
if (!safeLink(href)) {
$status.prop('hidden', false).text('请输入站内地址或有效的链接。');
return;
}
restoreRange();
const selection = window.getSelection();
if (selection.isCollapsed) {
edit('insertHTML', $('<a>', {href}).text(href).prop('outerHTML'));
} else {
edit('createLink', href);
}
return;
}
if (command === 'heading') edit('formatBlock', 'h3');
if (command === 'bold') edit('bold');
if (command === 'list') edit('insertUnorderedList');
});
$editor.on('click', '[data-rich-media]', function () {
openPicker('', (file) => {
const markup = mediaMarkup(file);
if (markup) edit('insertHTML', markup);
});
});
$editor.on('click', '[data-source-toggle]', function () {
const $button = $(this);
if (!source) {
$area.val($canvas.html()).prop('hidden', false).trigger('focus');
$canvas.prop('hidden', true);
$visualButtons.prop('disabled', true);
$button.text('返回可视化').attr('aria-pressed', 'true');
source = true;
return;
}
$button.prop('disabled', true);
$.ajax({
url: '/admin/preview',
method: 'POST',
dataType: 'text',
data: {csrf: $form.find('[name="csrf"]').val(), format: 'html', body: $area.val()}
}).done(function (html) {
$canvas.html(html).prop('hidden', false);
$area.prop('hidden', true);
$visualButtons.prop('disabled', false);
$button.text('HTML 源码').attr('aria-pressed', 'false');
$status.prop('hidden', true);
savedRange = null;
source = false;
}).fail(() => $status.prop('hidden', false).text('源码暂时无法转换,当前编辑内容已保留。'))
.always(() => $button.prop('disabled', false));
});
});
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

+27
View File
@@ -12,9 +12,11 @@ CREATE TABLE IF NOT EXISTS pages (
lead TEXT NOT NULL, lead TEXT NOT NULL,
image TEXT NOT NULL, image TEXT NOT NULL,
alt TEXT NOT NULL, alt TEXT NOT NULL,
image_scale INTEGER NOT NULL DEFAULT 0,
actions TEXT NOT NULL, actions TEXT NOT NULL,
quicklinks TEXT NOT NULL, quicklinks TEXT NOT NULL,
partners TEXT NOT NULL, partners TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('draft', 'published')),
updated_at TEXT, updated_at TEXT,
version INTEGER NOT NULL DEFAULT 0 version INTEGER NOT NULL DEFAULT 0
); );
@@ -61,3 +63,28 @@ CREATE TABLE IF NOT EXISTS login_attempts (
CREATE TABLE IF NOT EXISTS schema_migrations ( CREATE TABLE IF NOT EXISTS schema_migrations (
name TEXT PRIMARY KEY name TEXT PRIMARY KEY
); );
CREATE TABLE IF NOT EXISTS catalog (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
category TEXT NOT NULL,
body TEXT NOT NULL,
image TEXT NOT NULL,
alt TEXT NOT NULL,
url TEXT NOT NULL,
label TEXT NOT NULL,
extra_url TEXT NOT NULL DEFAULT '',
extra_label TEXT NOT NULL DEFAULT '',
position INTEGER NOT NULL DEFAULT 0,
version INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS catalog_order ON catalog (position, id);
CREATE TABLE IF NOT EXISTS media (
name TEXT PRIMARY KEY,
label TEXT NOT NULL,
mime TEXT NOT NULL,
size INTEGER NOT NULL,
created_at TEXT NOT NULL,
archived INTEGER NOT NULL DEFAULT 0
);
+163
View File
@@ -0,0 +1,163 @@
'use strict';
const assert = require('node:assert/strict');
const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const baseURL = process.env.LAYSENSE_TEST_URL || 'http://127.0.0.1:8787';
const email = process.env.LAYSENSE_TEST_EMAIL;
const password = process.env.LAYSENSE_TEST_PASSWORD;
if (!email || !password) {
throw new Error('Set LAYSENSE_TEST_EMAIL and LAYSENSE_TEST_PASSWORD for a disposable test database.');
}
async function run(browser) {
const context = await browser.newContext({baseURL, viewport: {width: 1480, height: 960}, reducedMotion: 'reduce'});
const page = await context.newPage();
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
await page.goto('/admin/login');
await page.locator('[name=email]').fill(email);
await page.locator('[name=password]').fill(password);
await page.locator('form button[type=submit]').click();
await page.waitForURL('**/admin');
const csrf = await page.locator('[name=csrf]').first().inputValue();
const slug = 'studio-browser-' + Date.now().toString(36);
async function post(path, values) {
const response = await context.request.post(path, {
form: {csrf, ...values},
headers: {'X-Requested-With': 'XMLHttpRequest'},
});
assert.equal(response.status(), 200, await response.text());
return response.json();
}
await post('/admin/new-page', {slug, name: '画布测试页'});
await post('/admin/page-blocks/' + slug, {operation: 'create', key: 'fixtures', preset: 'text'});
await post('/admin/pages/' + slug + '/fixtures', {
version: '0', title: '媒体和链接', lead: '', style: 'plain',
body: '<p><img src="/assets/favicon.png" alt="示例图片" width="96"></p>'
+ '<p><a href="/services">示例链接</a></p>'
+ '<video controls width="260" preload="none"><source src="/assets/original/drag-in-components.mp4"></video>'
+ '<audio controls src="/assets/original/drag-in-components.mp4" preload="none"></audio>',
});
const editorPath = '/admin/pages/' + slug;
await page.goto(editorPath);
const version = await page.locator('#studio-page-settings [name=version]').inputValue();
await post(editorPath, {
version, name: '画布测试页', status: 'draft', title: '画布测试页',
description: '', heading: '画布测试页', accent: '', lead: '',
image: '/assets/original/home-hero.webp', alt: '首屏示例', image_scale: '0',
});
await page.reload();
const frame = page.frameLocator('iframe[title="可编辑页面画布"]');
const sizing = page.locator('[data-media-sizing]');
const properties = page.locator('[data-canvas-properties]');
const closeProperties = () => properties.locator('[data-property-close]').click();
const image = frame.locator('#fixtures img');
await image.click();
await sizing.waitFor({state: 'visible'});
assert.equal(await image.getAttribute('data-studio-selected'), '');
await sizing.locator('[data-media-width]').selectOption('50');
assert.match(await image.getAttribute('class'), /studio-media-50/);
await image.dblclick();
await properties.waitFor({state: 'visible'});
assert.equal(await properties.locator('h2').textContent(), '正文图片');
await properties.locator('[name=url]').fill('/assets/original/home-hero.webp');
await properties.locator('button[type=submit]').click();
assert.equal(await image.getAttribute('src'), '/assets/original/home-hero.webp');
const hero = frame.locator('[data-studio-hero-image]');
await page.locator('iframe[title="可编辑页面画布"]').evaluate((iframe) => iframe.contentWindow.scrollTo(0, 0));
await hero.click();
await sizing.waitFor({state: 'visible'});
assert.equal(await hero.getAttribute('data-studio-selected'), '');
await sizing.locator('[data-replace-media]').click();
assert.equal(await properties.locator('h2').textContent(), '首屏图片');
await closeProperties();
await frame.locator('#fixtures a').click();
await properties.waitFor({state: 'visible'});
assert.equal(await properties.locator('h2').textContent(), '正文链接');
await properties.locator('[name=url]').fill('/articles');
await properties.locator('button[type=submit]').click();
assert.equal(await frame.locator('#fixtures a').getAttribute('href'), '/articles');
for (const [tag, label] of [['video', '视频'], ['audio', '音频']]) {
const media = frame.locator('#fixtures ' + tag);
await media.dispatchEvent('dblclick');
await properties.waitFor({state: 'visible'});
assert.equal(await properties.locator('h2').textContent(), label);
await closeProperties();
}
const gallery = page.locator('[data-canvas-presets]');
assert.equal(await gallery.locator('[data-template-group]').count(), 6);
assert.equal(await gallery.locator('[data-template-card]').count(), 13);
const brokenPreviews = await gallery.locator('[data-template-card] img').evaluateAll(async (images) => {
for (const image of images) image.loading = 'eager';
await Promise.all(images.map((image) => image.decode()));
return images.filter((image) => image.naturalWidth !== 768).length;
});
assert.equal(brokenPreviews, 0);
await gallery.locator('[data-template-filter=cover]').click();
assert.equal(await gallery.locator('[data-template-card]:visible').count(), 2);
const cover = gallery.locator('[data-template-preview=cover]');
await cover.hover();
const peek = gallery.locator('[data-template-peek]');
await peek.waitFor({state: 'visible'});
assert((await peek.boundingBox()).width > (await cover.boundingBox()).width);
await cover.focus();
await page.keyboard.press('Enter');
const dialog = gallery.locator('[data-template-dialog]');
await dialog.waitFor({state: 'visible'});
assert.equal(await dialog.locator('h2').textContent(), '图文封面');
await dialog.locator('[data-template-use]').click();
await frame.locator('section[id^=block-] h2').filter({hasText: '图文封面'}).waitFor();
await gallery.locator('[data-template-filter=""]').click();
const search = gallery.locator('[data-template-search]');
await search.fill('does-not-exist');
await gallery.locator('[data-template-empty]').waitFor({state: 'visible'});
await search.fill('双栏');
assert.equal(await gallery.locator('[data-template-card]:visible').count(), 1);
await Promise.all([
page.waitForResponse((response) => response.url().endsWith(editorPath) && response.request().method() === 'POST' && response.ok()),
page.getByRole('button', {name: '保存页面', exact: true}).first().click(),
]);
await page.locator('[data-save-confirmation]').waitFor({state: 'visible'});
await frame.locator('section[id^=block-] .studio-cover').waitFor();
assert.equal(await frame.locator('#fixtures a').getAttribute('href'), '/articles');
assert.equal(await frame.locator('#fixtures img').getAttribute('src'), '/assets/original/home-hero.webp');
const phone = await browser.newContext({
baseURL, viewport: {width: 390, height: 844}, isMobile: true, hasTouch: true,
storageState: await context.storageState(),
});
const phonePage = await phone.newPage();
phonePage.on('pageerror', (error) => errors.push(error.message));
await phonePage.goto(editorPath);
const phoneGallery = phonePage.locator('[data-canvas-presets]');
await phoneGallery.locator('[data-template-filter=cover]').tap();
await phoneGallery.locator('[data-template-preview=banner]').tap();
await phoneGallery.locator('[data-template-dialog]').waitFor({state: 'visible'});
assert.equal(await phoneGallery.locator('[data-template-dialog] h2').textContent(), '横幅');
assert.deepEqual(errors, []);
await phone.close();
await context.close();
}
(async () => {
const browser = await chromium.launch({executablePath: process.env.CHROMIUM_EXECUTABLE || undefined});
try {
await run(browser);
console.log('Passed Chromium canvas media/link interactions, template gallery, and persistence.');
} finally {
await browser.close();
}
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});