diff --git a/README.md b/README.md
index 6d9b0ef..675c427 100644
--- a/README.md
+++ b/README.md
@@ -36,22 +36,27 @@ php start.php start
## 页面与站点设计
-- 在「页面」新建空白草稿或从整页模板创建。画布支持编辑、媒体拖拽调整宽度、移动端预览、区块复制与删除。
+- 在「页面」新建空白草稿或从整页模板创建。画布支持编辑、媒体拖拽调整宽度、移动端预览、区块复制与删除。插入媒体时先放入占位图,双击占位图或使用「替换媒体」选择文件。
- 在「组件」中可选择图左、图右和交错图文。大图封面、均分图文、大图与清单、故事与图注都提供两种方向。手机上图文按组件顺序堆叠。
- 「图层」可展开到最内层的元素。可拖拽调整区块及内容元素的顺序,也可用箭头在同层移动或用定位图标选中画布中的元素。生成的区块外壳和动态文章列表保留其结构。移除的首屏可通过撤销或「页面设置 → 页面显示」恢复。
- 选中最外层区块的「编辑 HTML」可修改正文、标题和简介源码。首屏还可以转为完整自定义 HTML,并随时恢复为模板首屏。应用前服务端会清理 HTML,应用后可撤销,保存页面后才会写入站点。
- 点击面包屑或目录文案可就地编辑,双击或打开属性可修改链接。「页面设置 → 首屏与目录」可管理整组链接。模板内其他导航与常规内容一起编辑。
+- 「保存页面」在当前画布完成保存。使用「发布」保存并公开草稿,也可以用「转为草稿」下架页面。
- 发布的普通页面提供「查看公开页面」,显示访客实际看到的版本。草稿、页头、页脚和系统页面提供后台预览,显示已保存的内容。未保存的改动可在画布上查看。
- 选中元素后,可用四边预设滑块同步设置内边距或外边距,逐边输入精确数值,或恢复模板默认值。选中文字后可以输入 8–144 px 的字号,也可以从旁边的下拉菜单选择常用字号。文字颜色、粗体、斜体和删除线同样支持选区。
- 选中图片可拖拽调整宽度,也可在工具栏选择块级、行内或行内块布局。Enter 或 Shift+Enter 在当前元素内换行。正文用 Ctrl+Enter(macOS 上为 ⌘+Enter)或工具栏「换段」新建段落,列表中则新增列表项。
-- 画布支持 Ctrl/⌘+Z 撤销和 Ctrl/⌘+Shift+Z 重做。页面设置的输入框保留浏览器原生撤销。
+- 画布支持 Ctrl/⌘+Z 撤销和 Ctrl/⌘+Shift+Z 重做。页面设置的输入框保留浏览器原生撤销。每次成功保存都会开始一段新的画布编辑历史。
- 选中按钮后可复制。在「属性」中选择纯色填充、线框、下划线或无样式,并选择是否在新标签页打开。首屏支持最多八个按钮。
- 在「网站页面 → 新建页面」选择普通页面、页头、页脚、维护页或 404 页。它们共用同一个画布。页头页脚版式在「组件 → 页头/页脚」,也可添加封面、视频、文章等常规区块,或在页面设置中显示首屏。页脚组件默认附带可编辑的 Powered by LaySite 链接。
-- 新站点的「基础页头」和「基础页脚」已经设为站点默认,可在「网站页面」用画布编辑。也可将其他页头页脚设为站点默认,取消后会恢复相应的基础版式。普通页面各用一个下拉框选择隐藏、站点默认或指定方案。配色方案在「站点设计」管理。
+- 新站点的「基础页头」和「基础页脚」已经设为站点默认,可在「网站页面」用画布编辑。也可将其他页头页脚设为站点默认,取消后会恢复相应的基础版式。普通页面各用一个下拉框选择隐藏、站点默认或指定方案。配色方案在「站点设计」管理。列表和页面内的配色选择都会显示色样。
- 媒体库和媒体选择器只列出用户上传文件。编辑器图标、示例资产、字体、模板缩略图和产品标识随程序发布。
- 发布后的站点具备独立标题、描述、canonical、Open Graph、站点地图和 robots.txt。可在「站点设置」配置站点名称和静态资源 CDN。
-画布样式以白名单 CSS 类保存。间距与字号使用限定范围内的整数,服务端生成带版本指纹的样式表,画布和使用这些类的公开页按需加载。内容经过 HTML 清理,内联 `style` 属性会被移除。
+选中文字后可调整字号、字距、行距、字形和颜色。选中支持背景的容器或组件后,可以选择纯色、渐变或背景图。渐变支持线性与中心扩散,可在色条上添加、拖动和删除色标。在线性模式下通过滑块调整角度。背景图可选覆盖、完整显示、拉伸、原始尺寸或平铺,并可调整图片位置。文字颜色和背景色选择器均提供当前配色方案的色样。样式以经过校验的 CSS 类保存,内容中的内联 `style` 属性会被清理。网页和画布按需加载样式。
+
+渐变色标使用 Grapick 0.1.13,按 MIT 许可随后台提供。[Grapick 源码包](https://registry.npmjs.org/grapick/-/grapick-0.1.13.tgz)
+
+在「网站页面」可删除页面。删除首页后,访问 `/` 会显示站点的 404 页面。要重建首页,新建网址标识为 `home` 的普通页面并发布即可。在「文章分类」删除分类会保留文章,并从动态组件的展示范围移除该分类。
### 站点图标与 Head
@@ -64,7 +69,7 @@ php start.php start
```
-保存后,画布与独立预览都会加载样式。自定义脚本在独立预览和公开页面运行。启用自定义脚本后,独立预览会隔离 Cookie,并禁用表单提交和会员登录。内联脚本早于 LaySite 的 jQuery 执行。如需使用 jQuery,请用带 `defer` 的外部脚本,或在内联脚本中等待 `DOMContentLoaded`。站点备份包含图标、Head 代码和上传的资源。
+保存后,打开独立预览或重新进入画布即可加载更新后的 Head 样式。自定义脚本在独立预览和公开页面运行。启用自定义脚本后,独立预览会隔离 Cookie,并禁用表单提交和会员登录。内联脚本早于 LaySite 的 jQuery 执行。如需使用 jQuery,请用带 `defer` 的外部脚本,或在内联脚本中等待 `DOMContentLoaded`。站点备份包含图标、Head 代码和上传的资源。
### 维护页与 404 页
@@ -159,7 +164,7 @@ Docker 镜像以正式 Release 的标签发布到 `git.laysense.com/laysense/lay
### Docker 托管平台
-在平台选用镜像 `git.laysense.com/laysense/laysite:v1.4.7`,服务端口填 `8787`,永久卷挂载到 `/opt/laysite/storage`。在平台的环境变量面板填写以下配置。若平台在入口终止 HTTPS,启用安全 Cookie。
+在平台选用镜像 `git.laysense.com/laysense/laysite:v1.5.0`,服务端口填 `8787`,永久卷挂载到 `/opt/laysite/storage`。在平台的环境变量面板填写以下配置。若平台在入口终止 HTTPS,启用安全 Cookie。
| 环境变量 | 推荐填写 |
| --- | --- |
@@ -179,7 +184,7 @@ docker run -d --name laysite --restart unless-stopped \
-p 127.0.0.1:8787:8787 \
--env-file /path/to/laysite.env \
-v laysite-storage:/opt/laysite/storage \
- git.laysense.com/laysense/laysite:v1.4.7
+ git.laysense.com/laysense/laysite:v1.5.0
```
示例由宿主机上的反向代理终止 HTTPS。容器以 UID/GID 10001 运行。使用宿主机目录代替命名卷时,请让该用户可写入挂载目录。升级时以新标签重建容器,并挂载同一个数据卷。默认的 `runtime/` 存放会话、日志和缓存,重建后管理员需要重新登录。如需保留这些数据,也可挂载 `/opt/laysite/runtime`。
diff --git a/VERSION b/VERSION
index be05bba..bc80560 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.4.7
+1.5.0
diff --git a/app/Content/CanvasStyle.php b/app/Content/CanvasStyle.php
index 208054c..f65ac9e 100644
--- a/app/Content/CanvasStyle.php
+++ b/app/Content/CanvasStyle.php
@@ -18,6 +18,8 @@ final class CanvasStyle
'mt' => ['margin-top', -128, 128], 'mr' => ['margin-right', -128, 128],
'mb' => ['margin-bottom', -128, 128], 'ml' => ['margin-left', -128, 128],
'size' => ['font-size', 8, 144],
+ 'letter' => ['letter-spacing', -5, 24],
+ 'line' => ['line-height', 8, 30],
];
private const TYPOGRAPHY = [
'weight-bold' => 'font-weight:700', 'weight-normal' => 'font-weight:400',
@@ -25,6 +27,13 @@ final class CanvasStyle
'strike-on' => 'text-decoration-line:line-through', 'strike-off' => 'text-decoration-line:none',
];
private const PREFIX = 'studio-style-';
+ private const IMAGE_SIZES = [
+ 'cover' => 'cover', 'contain' => 'contain', 'stretch' => '100% 100%', 'original' => 'auto', 'tile' => 'auto',
+ ];
+ private const IMAGE_POSITIONS = [
+ 'c' => 'center', 'tl' => 'left top', 'tc' => 'center top', 'tr' => 'right top',
+ 'ml' => 'left center', 'mr' => 'right center', 'bl' => 'left bottom', 'bc' => 'center bottom', 'br' => 'right bottom',
+ ];
public static function encode(array $presentation): string
{
@@ -95,7 +104,7 @@ final class CanvasStyle
private static function classList(mixed $value, bool $textOnly = false): string
{
- if (!is_string($value) || strlen($value) > 320) {
+ if (!is_string($value) || strlen($value) > 1800) {
throw new RuntimeException('画布样式无效。');
}
$classes = [];
@@ -109,9 +118,11 @@ final class CanvasStyle
$classes[$property] = $class;
} elseif ($property === 'color' && ($size === 'theme' || preg_match('/^[a-f0-9]{6}$/D', $size))) {
$classes[$property] = $class;
+ } elseif (!$textOnly && $property === 'fill' && self::fill($size) !== null) {
+ $classes[$property] = $class;
} elseif (!$textOnly && $property === 'display' && in_array($size, ['block', 'inline', 'inline-block'], true)) {
$classes[$property] = $class;
- } elseif ((!$textOnly || $property === 'size') && isset(self::PROPERTIES[$property])
+ } elseif ((!$textOnly || in_array($property, ['size', 'letter', 'line'], true)) && isset(self::PROPERTIES[$property])
&& preg_match('/^(?:0|-?[1-9]\d{0,2})$/D', $size)) {
[, $min, $max] = self::PROPERTIES[$property];
if ((int) $size >= $min && (int) $size <= $max) {
@@ -163,12 +174,92 @@ final class CanvasStyle
return $markup;
}
- public static function colorRules(string $markup): string
+ private static function fill(string $token): ?string
{
- preg_match_all('/\bstudio-style-color-([a-f0-9]{6})(?![\w-])/', $markup, $matches);
+ if (preg_match('/^solid-([a-f0-9]{6})$/D', $token, $parts)) {
+ return 'background:#' . $parts[1] . '!important';
+ }
+ if (preg_match('/^gradient-(0|[1-9]\d{0,2})-([a-f0-9]{6})-([a-f0-9]{6})$/D', $token, $parts) && (int) $parts[1] <= 360) {
+ return "background:linear-gradient({$parts[1]}deg,#{$parts[2]},#{$parts[3]})!important";
+ }
+ if (str_starts_with($token, 'gradient-')) {
+ return self::gradient(substr($token, strlen('gradient-')));
+ }
+ $size = 'cover';
+ $position = 'c';
+ if (preg_match('/^image-v2-([a-z]+)-([a-z]+)-([A-Za-z0-9_-]{1,1334})$/D', $token, $parts)) {
+ [, $size, $position, $encoded] = $parts;
+ } elseif (preg_match('/^image-([A-Za-z0-9_-]{1,1334})$/D', $token, $parts)) {
+ $encoded = $parts[1];
+ } else {
+ return null;
+ }
+ if (!isset(self::IMAGE_SIZES[$size], self::IMAGE_POSITIONS[$position])) {
+ return null;
+ }
+ $url = base64_decode(strtr($encoded, '-_', '+/'), true);
+ if ($url === false || strlen($url) > 1000 || !mb_check_encoding($url, 'UTF-8') || !Html::url($url, true)
+ || rtrim(strtr(base64_encode($url), '+/', '-_'), '=') !== $encoded) {
+ return null;
+ }
+ // Quote the URL for CSS and keep the result safe inside a raw-text HTML style element.
+ $escaped = str_replace(['"', '<', '>'], ['\\22 ', '\\3c ', '\\3e '], $url);
+
+ $repeat = $size === 'tile' ? 'repeat' : 'no-repeat';
+
+ return 'background-image:url("' . $escaped . '")!important;background-position:' . self::IMAGE_POSITIONS[$position]
+ . '!important;background-size:' . self::IMAGE_SIZES[$size] . '!important;background-repeat:' . $repeat . '!important';
+ }
+
+ private static function gradient(string $token): ?string
+ {
+ $parts = explode('-', $token, 15);
+ $type = array_shift($parts);
+ if ($type === 'linear') {
+ $angle = array_shift($parts);
+ if ($angle === null || !preg_match('/^(0|[1-9]\d{0,2})$/D', $angle) || (int) $angle > 360) {
+ return null;
+ }
+ $direction = $angle . 'deg';
+ } elseif ($type === 'radial') {
+ $direction = 'circle at center';
+ } else {
+ return null;
+ }
+ if (count($parts) < 2 || count($parts) > 12) {
+ return null;
+ }
+ $last = 0;
+ $stops = [];
+ foreach ($parts as $stop) {
+ if (!preg_match('/^(0|[1-9]\d?|100)_([a-f0-9]{6})$/D', $stop, $color) || (int) $color[1] < $last) {
+ return null;
+ }
+ $last = (int) $color[1];
+ $stops[] = "#{$color[2]} {$last}%";
+ }
+
+ return "background:{$type}-gradient($direction," . implode(',', $stops) . ')!important';
+ }
+
+ public static function dynamicRules(string $markup): string
+ {
+ preg_match_all('/\bstudio-style-(color|fill)-([A-Za-z0-9_-]+)(?![\w-])/', $markup, $matches, PREG_SET_ORDER);
$css = '';
- foreach (array_unique($matches[1]) as $hex) {
- $css .= ".studio-style-color-{$hex}{color:#{$hex}!important}\n";
+ $seen = [];
+ foreach ($matches as [$class, $property, $value]) {
+ if (isset($seen[$class])) {
+ continue;
+ }
+ $seen[$class] = true;
+ if ($property === 'color') {
+ $rule = preg_match('/^[a-f0-9]{6}$/D', $value) ? "color:#{$value}!important" : null;
+ } else {
+ $rule = self::fill($value);
+ }
+ if ($rule !== null) {
+ $css .= ".$class" . '{' . $rule . "}\n";
+ }
}
return $css;
@@ -177,9 +268,11 @@ final class CanvasStyle
public static function stylesheet(): string
{
$css = '';
- foreach (self::PROPERTIES as $key => [$property, $min, $max]) {
+ foreach (self::PROPERTIES as $key => $definition) {
+ [$property, $min, $max] = $definition;
for ($value = $min; $value <= $max; $value++) {
- $css .= '.' . self::PREFIX . "$key-$value{{$property}:{$value}px!important}\n";
+ $length = $key === 'line' ? $value / 10 : $value . 'px';
+ $css .= '.' . self::PREFIX . "$key-$value{{$property}:{$length}!important}\n";
}
}
for ($width = self::MIN_MEDIA_SCALE; $width <= 100; $width++) {
diff --git a/app/Content/Database.php b/app/Content/Database.php
index 358b23f..e123ef0 100644
--- a/app/Content/Database.php
+++ b/app/Content/Database.php
@@ -64,21 +64,23 @@ final class Database
}
}
$pdo->prepare('INSERT OR IGNORE INTO site_settings (id, payload) VALUES (1, ?)')->execute([self::json(['name' => '我的网站'])]);
- $pdo->prepare("INSERT OR IGNORE INTO pages
- (slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
- VALUES ('home', '首页', '我的网站', '欢迎访问我的网站。', '我的网站', '', '', '', '', '[]', '[]')")
- ->execute();
- $articles = $pdo->prepare("INSERT OR IGNORE INTO pages
- (slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
- VALUES ('articles', '文章与动态', '文章与动态', '浏览站点发布的文章。', '文章与动态', '', '', '', '', '[]', '[]')");
- $articles->execute();
- if ($articles->rowCount() === 1) {
- $pdo->prepare("INSERT INTO sections (page_slug, key, title, lead, body, feed, position)
- VALUES ('articles', 'posts', '最新文章', '', '', ?, 0)")->execute([BlockTemplates::ARTICLE_FEED]);
- }
- $category = $pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
- foreach (Repository::CATEGORIES as $slug => $name) {
- $category->execute([$slug, $name]);
+ if ($version === 0) {
+ $pdo->prepare("INSERT OR IGNORE INTO pages
+ (slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
+ VALUES ('home', '首页', '我的网站', '欢迎访问我的网站。', '我的网站', '', '', '', '', '[]', '[]')")
+ ->execute();
+ $articles = $pdo->prepare("INSERT OR IGNORE INTO pages
+ (slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
+ VALUES ('articles', '文章与动态', '文章与动态', '浏览站点发布的文章。', '文章与动态', '', '', '', '', '[]', '[]')");
+ $articles->execute();
+ if ($articles->rowCount() === 1) {
+ $pdo->prepare("INSERT INTO sections (page_slug, key, title, lead, body, feed, position)
+ VALUES ('articles', 'posts', '最新文章', '', '', ?, 0)")->execute([BlockTemplates::ARTICLE_FEED]);
+ }
+ $category = $pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
+ foreach (Repository::CATEGORIES as $slug => $name) {
+ $category->execute([$slug, $name]);
+ }
}
if ($version < 2) {
OAuthCredentials::migrateLegacy($pdo);
diff --git a/app/Content/DesignLibrary.php b/app/Content/DesignLibrary.php
index 0a95fe1..1a19067 100644
--- a/app/Content/DesignLibrary.php
+++ b/app/Content/DesignLibrary.php
@@ -39,6 +39,18 @@ final class DesignLibrary
return $query->fetchAll();
}
+ public static function palettes(): array
+ {
+ $rows = Database::connect()->query("SELECT id, name, preset, payload FROM design_presets
+ WHERE kind = 'palette' ORDER BY id")->fetchAll();
+ foreach ($rows as &$row) {
+ $row['colors'] = self::normalize('palette', $row['preset'], json_decode($row['payload'], true, flags: JSON_THROW_ON_ERROR));
+ unset($row['payload'], $row['preset']);
+ }
+
+ return $rows;
+ }
+
public static function find(int $id, string $kind): ?array
{
if ($id < 1) {
diff --git a/app/Content/LayoutPage.php b/app/Content/LayoutPage.php
index 7781107..969e544 100644
--- a/app/Content/LayoutPage.php
+++ b/app/Content/LayoutPage.php
@@ -128,4 +128,19 @@ final class LayoutPage
DesignLibrary::setDefault($pdo, $kind, $id, $config['default']);
}
}
+
+ public static function deletePreset(PDO $pdo, string $kind, int $id): void
+ {
+ $field = $kind . '_id';
+ $pdo->prepare("UPDATE pages SET $field = NULL, version = version + 1 WHERE $field = ?")->execute([$id]);
+ $site = json_decode($pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
+ if (($site['layout_defaults'][$kind] ?? null) === $id) {
+ unset($site['layout_defaults'][$kind]);
+ }
+ if (($site[$field] ?? null) === $id) {
+ $site[$field] = $site['layout_defaults'][$kind] ?? null;
+ }
+ $pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
+ $pdo->prepare('DELETE FROM design_presets WHERE id = ?')->execute([$id]);
+ }
}
diff --git a/app/Content/Licenses.php b/app/Content/Licenses.php
index 189ebcb..1ef0a94 100644
--- a/app/Content/Licenses.php
+++ b/app/Content/Licenses.php
@@ -36,6 +36,8 @@ final class Licenses
'url' => 'https://github.com/codemirror/codemirror5', 'file' => $root . '/public/assets/vendor/codemirror/LICENSE'],
'js-beautify' => ['name' => 'JS Beautifier', 'version' => '1.15.4', 'license' => 'MIT',
'url' => 'https://github.com/beautifier/js-beautify', 'file' => $root . '/public/assets/vendor/js-beautify/LICENSE'],
+ 'grapick' => ['name' => 'Grapick', 'version' => '0.1.13', 'license' => 'MIT',
+ 'url' => 'https://github.com/artf/grapick', 'file' => $root . '/public/assets/vendor/grapick/LICENSE'],
'geist' => ['name' => 'Geist', 'license' => 'OFL-1.1',
'url' => 'https://github.com/vercel/geist-font', 'file' => $root . '/public/assets/geist-OFL.txt'],
'dompurify' => ['name' => 'DOMPurify', 'version' => self::declaredVersion($editor, '~@license DOMPurify\h+' . $version . '~'), 'license' => 'Apache-2.0 / MPL-2.0',
diff --git a/app/Content/PageDraft.php b/app/Content/PageDraft.php
index dc4b6fa..eee5202 100644
--- a/app/Content/PageDraft.php
+++ b/app/Content/PageDraft.php
@@ -8,7 +8,7 @@ use RuntimeException;
final class PageDraft
{
- public const RESERVED = ['.', '.laysite', 'admin', 'assets', 'home', 'account', 'mcp', 'palette'];
+ public const RESERVED = ['.', '.laysite', 'admin', 'assets', 'account', 'mcp', 'palette'];
public static function slug(mixed $value, array $reserved = self::RESERVED, bool $includeSpecial = false): string
{
diff --git a/app/Content/Repository.php b/app/Content/Repository.php
index 909e2f6..c70bca8 100644
--- a/app/Content/Repository.php
+++ b/app/Content/Repository.php
@@ -98,7 +98,7 @@ final class Repository
$catalog = $feed['mode'] === 'catalog';
$grouped = $network || ($feed['mode'] === 'tabs' && count($feed['categories']) > 1);
$archivePath = '/articles/feed/' . $page['slug'] . '/' . $section['key'];
- $section['archivePath'] = empty($page['layout_kind']) && ($page['page_type'] ?? 'page') === 'page' && $page['status'] === 'published' ? $archivePath : null;
+ $section['archivePath'] = $feed['categories'] && empty($page['layout_kind']) && ($page['page_type'] ?? 'page') === 'page' && $page['status'] === 'published' ? $archivePath : null;
$section['articleFeed'] = [];
$section['networkFeed'] = $network;
$section['catalogFeed'] = $catalog;
@@ -129,9 +129,9 @@ final class Repository
AND sections.key = ? AND sections.feed IS NOT NULL", [$page, $key]);
}
- public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false, ?array $sectionOrder = null): void
+ public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false, ?array $sectionOrder = null): array
{
- Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections, $sectionOrder): void {
+ return Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections, $sectionOrder): array {
$head = $data['head_html'] ?? null;
$query = $pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?,
image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, visibility = ?, header_id = ?, footer_id = ?, palette_id = ?, status = ?, updated_at = ?,
@@ -163,9 +163,32 @@ final class Repository
if ($sectionOrder !== null) {
self::writeSectionOrder($pdo, $slug, $sectionOrder);
}
+ $page = $this->page($slug);
if (isset($data['layoutConfig'])) {
- LayoutPage::saveSettings($pdo, $this->page($slug), $data['layoutConfig']);
+ LayoutPage::saveSettings($pdo, $page, $data['layoutConfig']);
}
+
+ return $page;
+ });
+ }
+
+ public function deletePage(string $slug, int $version): bool
+ {
+ return Database::write(function (PDO $pdo) use ($slug, $version): bool {
+ $page = $this->one('SELECT pages.layout_id, d.kind AS layout_kind FROM pages
+ LEFT JOIN design_presets d ON pages.layout_id = d.id WHERE pages.slug = ?', [$slug]);
+ if ($page === null) {
+ return false;
+ }
+ $delete = $pdo->prepare('DELETE FROM pages WHERE slug = ? AND version = ?');
+ $delete->execute([$slug, $version]);
+ self::checkVersion($delete->rowCount());
+ if ($page['layout_id'] !== null) {
+ LayoutPage::deletePreset($pdo, $page['layout_kind'], $page['layout_id']);
+ }
+ SiteDesign::unsetSystemPage($pdo, $slug);
+
+ return true;
});
}
@@ -173,7 +196,7 @@ final class Repository
{
Database::write(function (PDO $pdo) use ($page, $key, $data, $version): void {
self::updateSection($pdo, $page, $key, $data, $version);
- self::touchPage($pdo, $page);
+ self::touchPage($pdo, $page, bumpVersion: false);
});
}
@@ -189,7 +212,7 @@ final class Repository
{
Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body, $feed, $lead): void {
self::insertSection($pdo, $page, $key, compact('title', 'style', 'body', 'feed', 'lead'));
- self::touchPage($pdo, $page, structureChanged: true);
+ self::touchPage($pdo, $page);
});
}
@@ -197,7 +220,14 @@ final class Repository
{
$query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, alignments, presentation, position)
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?');
- $query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $data['alignments'] ?? '{}', $data['presentation'] ?? '{}', $page]);
+ $feed = $data['feed'] ?? null;
+ if ($feed !== null) {
+ $config = json_decode($feed, true, flags: JSON_THROW_ON_ERROR);
+ $available = $pdo->query('SELECT slug FROM article_categories')->fetchAll(PDO::FETCH_COLUMN);
+ $config['categories'] = array_values(array_intersect($config['categories'], $available));
+ $feed = Database::json($config);
+ }
+ $query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $feed, $data['alignments'] ?? '{}', $data['presentation'] ?? '{}', $page]);
if ($query->rowCount() !== 1) {
throw new RuntimeException('此区块锚点已被使用。');
}
@@ -233,7 +263,7 @@ final class Repository
self::checkVersion($revision !== false && (int) $revision === $pageVersion ? 1 : 0);
if ($operation === 'delete') {
self::deleteSection($pdo, $page, $key, $version);
- self::touchPage($pdo, $page, structureChanged: true);
+ self::touchPage($pdo, $page);
return;
}
@@ -252,7 +282,7 @@ final class Repository
}
[$keys[$index], $keys[$other]] = [$keys[$other], $keys[$index]];
self::writeSectionOrder($pdo, $page, $keys);
- self::touchPage($pdo, $page, structureChanged: true);
+ self::touchPage($pdo, $page);
});
}
@@ -270,9 +300,9 @@ final class Repository
}
}
- private static function touchPage(PDO $pdo, string $slug, bool $structureChanged = false): void
+ private static function touchPage(PDO $pdo, string $slug, bool $bumpVersion = true): void
{
- $revision = $structureChanged ? ', version = version + 1' : '';
+ $revision = $bumpVersion ? ', version = version + 1' : '';
$pdo->prepare('UPDATE pages SET updated_at = ?' . $revision . ' WHERE slug = ?')->execute([self::now(), $slug]);
}
@@ -290,6 +320,36 @@ final class Repository
}
}
+ public function deleteCategory(string $slug): bool
+ {
+ return Database::write(function (PDO $pdo) use ($slug): bool {
+ if ($this->one('SELECT 1 FROM article_categories WHERE slug = ?', [$slug]) === null) {
+ return false;
+ }
+ $pdo->prepare('UPDATE articles SET version = version + 1 WHERE id IN
+ (SELECT article_id FROM article_category_links WHERE category_slug = ?)')->execute([$slug]);
+ $pdo->prepare('DELETE FROM article_category_links WHERE category_slug = ?')->execute([$slug]);
+ $pdo->prepare('DELETE FROM article_categories WHERE slug = ?')->execute([$slug]);
+
+ $sections = $pdo->prepare("SELECT page_slug, key, feed FROM sections WHERE EXISTS
+ (SELECT 1 FROM json_each(sections.feed, '$.categories') WHERE value = ?)");
+ $sections->execute([$slug]);
+ $update = $pdo->prepare('UPDATE sections SET feed = ?, version = version + 1 WHERE page_slug = ? AND key = ?');
+ $affected = [];
+ foreach ($sections->fetchAll() as $section) {
+ $feed = json_decode($section['feed'], true, flags: JSON_THROW_ON_ERROR);
+ $feed['categories'] = array_values(array_diff($feed['categories'], [$slug]));
+ $update->execute([Database::json($feed), $section['page_slug'], $section['key']]);
+ $affected[$section['page_slug']] = true;
+ }
+ foreach (array_keys($affected) as $page) {
+ self::touchPage($pdo, $page);
+ }
+
+ return true;
+ });
+ }
+
public function articles(string|array|null $category = null, ?string $tag = null, bool $public = true,
int $limit = 30, int $offset = 0, bool $directoryOrder = false): array
{
diff --git a/app/Content/SiteBackup.php b/app/Content/SiteBackup.php
index 4b4a560..0e0711f 100644
--- a/app/Content/SiteBackup.php
+++ b/app/Content/SiteBackup.php
@@ -157,8 +157,8 @@ final class SiteBackup
}
}
}
- if (count($tables['site_settings']) !== 1 || !in_array('home', array_column($tables['pages'], 'slug'), true)) {
- throw new RuntimeException('备份缺少站点身份或首页。');
+ if (count($tables['site_settings']) !== 1) {
+ throw new RuntimeException('备份缺少站点身份。');
}
$designs = [];
foreach ($tables['design_presets'] as &$row) {
@@ -198,7 +198,7 @@ final class SiteBackup
$publishedSystemPages[$row['slug']] = $row['page_type'];
}
} elseif ($layout === null) {
- PageDraft::slug($row['slug'] ?? null, array_diff(PageDraft::RESERVED, ['home']));
+ PageDraft::slug($row['slug'] ?? null);
} else {
$kind = is_int($layout) ? ($designs[$layout] ?? null) : null;
if (!in_array($kind, ['header', 'footer'], true) || ($row['slug'] ?? null) !== LayoutPage::slug($kind, $layout)) {
diff --git a/app/Content/View.php b/app/Content/View.php
index 0dd7b64..224b2d2 100644
--- a/app/Content/View.php
+++ b/app/Content/View.php
@@ -49,7 +49,7 @@ final class View
}
}
$html = self::fragment($template, $data);
- $data['canvasColors'] = $admin ? '' : CanvasStyle::colorRules($html . ($data['headerMarkup'] ?? '') . ($data['footerMarkup'] ?? ''));
+ $data['canvasColors'] = $admin ? '' : CanvasStyle::dynamicRules($html . ($data['headerMarkup'] ?? '') . ($data['footerMarkup'] ?? ''));
$headSources = $admin ? [] : array_filter([$data['site']['head_html'] ?? '', $data['page']['head_html'] ?? '']);
$data['styleNonce'] = $data['canvasColors'] !== '' || !empty($data['canvas']) || $headSources !== []
? base64_encode(random_bytes(18)) : '';
diff --git a/app/Controller/AdminController.php b/app/Controller/AdminController.php
index febbd26..d68d692 100644
--- a/app/Controller/AdminController.php
+++ b/app/Controller/AdminController.php
@@ -127,7 +127,7 @@ class AdminController
return $this->render($request, 'admin-dashboard', [
'title' => '内容管理', 'pages' => $repo->pages(), 'articles' => $repo->articles(public: false, limit: 5),
- 'site' => $repo->site(),
+ 'site' => $repo->site(), 'deleted' => $request->get('deleted') === '1',
'pageTemplateDrawer' => true,
]);
}
@@ -237,9 +237,25 @@ class AdminController
return $this->render($request, 'admin-article-categories', [
'title' => '文章分类', 'categories' => $repo->categories(), 'name' => $name, 'slug' => $slug,
'error' => $error, 'saved' => $request->get('saved') === '1',
+ 'deleted' => $request->get('deleted') === '1',
], $error === '' ? 200 : 422);
}
+ public function deleteCategory(Request $request, string $slug): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ try {
+ $deleted = (new Repository())->deleteCategory($slug);
+ } catch (RuntimeException $exception) {
+ return $this->error($request, $this->validationMessage($exception), 422);
+ }
+
+ return $deleted ? $this->success($request, '/admin/article-categories?deleted=1')
+ : $this->error($request, '找不到此文章分类。', 404);
+ }
+
public function article(Request $request, ?string $id = null): Response
{
if ($failure = $this->guard($request)) {
@@ -248,10 +264,10 @@ class AdminController
$repo = new Repository();
$categories = $repo->categories();
$preset = $request->get('category');
- $preset = is_string($preset) && isset($categories[$preset]) ? $preset : 'news';
+ $preset = is_string($preset) && isset($categories[$preset]) ? $preset : (isset($categories['news']) ? 'news' : null);
$article = $id !== null ? $repo->articleById((int) $id) : [
'title' => '', 'slug' => '', 'summary' => '', 'body' => '', 'body_format' => 'markdown',
- 'categories' => [$preset => $categories[$preset]], 'card' => [], 'tags' => [], 'status' => 'draft', 'version' => 0,
+ 'categories' => $preset === null ? [] : [$preset => $categories[$preset]], 'card' => [], 'tags' => [], 'status' => 'draft', 'version' => 0,
];
if (!$article) {
return $this->error($request, '找不到这篇文章。', 404);
@@ -267,7 +283,7 @@ class AdminController
if (mb_strlen($data['title']) < 1 || mb_strlen($data['title']) > 120
|| !preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/D', $data['slug']) || strlen($data['slug']) > 100
|| mb_strlen($data['summary']) > 250 || strlen($data['body']) > 200000
- || $data['categories'] === [] || array_diff($data['categories'], array_keys($categories))
+ || array_diff($data['categories'], array_keys($categories))
|| !in_array($data['body_format'], ['markdown', 'html'], true)
|| !in_array($data['status'], ['draft', 'published'], true)) {
throw new RuntimeException('请检查标题、网址标识、分类、摘要和正文长度。');
@@ -338,7 +354,8 @@ class AdminController
if ($layout) {
$data['title'] = $data['name'];
}
- $data['status'] = $layout || $request->post('status') === null || $slug === 'home' ? $page['status'] : $this->input($request, 'status');
+ $publication = $request->post('status');
+ $data['status'] = $layout || $publication === null ? $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);
@@ -420,7 +437,17 @@ class AdminController
throw new RuntimeException('区块顺序无效。');
}
}
- $repo->savePage($slug, $data, $this->version($request), $sections, sectionOrder: $order === '' ? null : $order);
+ $saved = $repo->savePage($slug, $data, $this->version($request), $sections, sectionOrder: $order === '' ? null : $order);
+ if ($request->expectsJson()) {
+ return $this->json([
+ 'saved' => true, 'version' => $saved['version'], 'name' => $saved['name'], 'status' => $saved['status'],
+ 'sections' => array_map(static function (array $section) use ($sections): array {
+ $key = $section['key'];
+ return ['key' => $key, 'version' => $section['version']]
+ + (isset($sections[$key]) ? ['body' => $section['body'], 'feed' => $section['feed']] : []);
+ }, $saved['sections']),
+ ]);
+ }
return $this->success($request, '/admin/pages/' . $slug . '?saved=1');
} catch (RuntimeException $exception) {
@@ -434,9 +461,25 @@ class AdminController
'layoutBase' => $layout && ($site['layout_defaults'][$layoutKind] ?? null) === $layout['id'],
'siteName' => $site['name'], 'layoutHasMember' => $layoutKind === 'header' && LayoutPage::hasMember($page['sections']),
'layoutDefaults' => array_intersect_key($site, ['header_id' => true, 'footer_id' => true]),
+ 'palettes' => DesignLibrary::palettes(),
], $error !== '' ? 422 : 200);
}
+ public function deletePage(Request $request, string $slug): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ try {
+ $deleted = (new Repository())->deletePage($slug, $this->version($request));
+ } catch (RuntimeException $exception) {
+ return $this->error($request, $this->validationMessage($exception), 422);
+ }
+
+ return $deleted ? $this->success($request, '/admin?deleted=1')
+ : $this->error($request, '找不到此页面。', 404);
+ }
+
public function section(Request $request, string $slug, string $key): Response
{
if ($failure = $this->guard($request)) {
@@ -604,7 +647,7 @@ class AdminController
protected function guard(Request $request): ?Response
{
if (!$this->signedIn($request)) {
- return $request->isAjax()
+ return $request->expectsJson()
? $this->json(['message' => '登录已过期。请在新标签页重新登录,再返回继续编辑。'], 401)
: View::redirect('/admin/login');
}
@@ -741,8 +784,8 @@ class AdminController
{
$categories = $this->selectedCategories($selected);
$limit = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 30]]);
- if (!in_array($mode, ['merged', 'tabs', 'network', 'catalog'], true) || !$categories || array_diff($categories, array_keys($available)) || $limit === false) {
- throw new RuntimeException('请选择文章分类,并将展示数量设为 1 至 30。');
+ if (!in_array($mode, ['merged', 'tabs', 'network', 'catalog'], true) || array_diff($categories, array_keys($available)) || $limit === false) {
+ throw new RuntimeException('请检查展示方式、分类和展示数量(1 至 30)。');
}
return Database::json(compact('categories', 'mode', 'limit'));
@@ -761,7 +804,7 @@ class AdminController
protected function success(Request $request, string $path): Response
{
- return $request->isAjax() ? $this->json(['redirect' => $path]) : View::redirect($path);
+ return $request->expectsJson() ? $this->json(['redirect' => $path]) : View::redirect($path);
}
protected function json(array $payload, int $status = 200): Response
@@ -777,7 +820,7 @@ class AdminController
protected function render(Request $request, string $view, array $data, int $status = 200): Response
{
$token = $this->token($request);
- if ($request->isAjax() && $status >= 400) {
+ if ($request->expectsJson() && $status >= 400) {
return $this->json([
'message' => $data['error'] ?? $data['title'],
...(!empty($data['field']) ? ['field' => $data['field']] : []),
diff --git a/app/Controller/DesignController.php b/app/Controller/DesignController.php
index fb1b269..f1db301 100644
--- a/app/Controller/DesignController.php
+++ b/app/Controller/DesignController.php
@@ -27,7 +27,7 @@ final class DesignController extends AdminController
}
return $this->render($request, 'admin-design', [
- 'title' => '站点设计', 'items' => DesignLibrary::all('palette'),
+ 'title' => '站点设计', 'items' => DesignLibrary::palettes(),
]);
}
diff --git a/app/Controller/SiteController.php b/app/Controller/SiteController.php
index 235e8cb..fc62f09 100644
--- a/app/Controller/SiteController.php
+++ b/app/Controller/SiteController.php
@@ -241,7 +241,7 @@ final class SiteController
return View::render('missing', [
'site' => (new Repository())->site(), 'title' => '页面未找到', 'description' => '',
- 'path' => null, 'noindex' => true,
+ 'path' => null, 'noindex' => true, 'atHomepage' => $path === '/',
], 404);
}
diff --git a/app/view/admin-article-categories.php b/app/view/admin-article-categories.php
index fe11bb6..8aa0e25 100644
--- a/app/view/admin-article-categories.php
+++ b/app/view/admin-article-categories.php
@@ -6,6 +6,7 @@ $e = View::escape(...);
返回文章列表
= View::fragment('admin-feedback', compact('error', 'saved')) ?>
+
分类已删除。
-
+
diff --git a/app/view/admin-category-checkboxes.php b/app/view/admin-category-checkboxes.php
index 208f97d..48e99a8 100644
--- a/app/view/admin-category-checkboxes.php
+++ b/app/view/admin-category-checkboxes.php
@@ -6,6 +6,7 @@ $checked = array_fill_keys($selected, true);
?>