LaySite 1.4.5 · 站点图标、Head 编辑器和容器发布 #16

Merged
enoch merged 2 commits from ChatGPT/laysite:laysite-1.4.5 into main 2026-11-27 22:41:24 +08:00
16 changed files with 159 additions and 48 deletions
Showing only changes of commit 074591d34f - Show all commits
+50 -9
View File
@@ -4,9 +4,12 @@ on:
release: release:
types: [published] types: [published]
permissions:
releases: read
jobs: jobs:
container: container:
if: ${{ gitea.repository == 'laysense/laysite' && !gitea.event.release.prerelease }} if: ${{ gitea.repository == 'laysense/laysite' }}
runs-on: host runs-on: host
timeout-minutes: 30 timeout-minutes: 30
steps: steps:
@@ -14,10 +17,33 @@ jobs:
shell: bash shell: bash
env: env:
RELEASE_TAG: ${{ gitea.event.release.tag_name }} RELEASE_TAG: ${{ gitea.event.release.tag_name }}
RELEASE_API_TOKEN: ${{ secrets.GITEA_TOKEN }}
PACKAGE_USERNAME: ${{ secrets.PACKAGE_USERNAME }} PACKAGE_USERNAME: ${{ secrets.PACKAGE_USERNAME }}
PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }} PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }}
run: | run: |
set -euo pipefail set -euo pipefail
: "${RELEASE_TAG:?The release event did not specify a tag.}"
: "${RELEASE_API_TOKEN:?The job did not receive GITEA_TOKEN.}"
registry=git.laysense.com
source_url="https://$registry/laysense/laysite"
encoded_tag="$(python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1], safe=""))' "$RELEASE_TAG")"
release_json="$(printf 'Authorization: token %s\n' "$RELEASE_API_TOKEN" \
| curl --fail --silent --show-error --max-time 30 --header @- \
"https://$registry/api/v1/repos/laysense/laysite/releases/tags/$encoded_tag")"
release_type="$(printf '%s' "$release_json" | python3 -c '
import json, sys
release = json.load(sys.stdin)
if release.get("tag_name") != sys.argv[1] or release.get("draft") is not False:
sys.exit("The release tag does not match a published release.")
prerelease = release.get("prerelease")
if not isinstance(prerelease, bool):
sys.exit("The release API did not report its prerelease status.")
print("prerelease" if prerelease else "stable")
' "$RELEASE_TAG")"
if [ "$release_type" = 'prerelease' ]; then
echo 'Skipping the container build for a prerelease.'
exit 0
fi
if ! printf '%s\n' "$RELEASE_TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then if ! printf '%s\n' "$RELEASE_TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
echo 'The release tag must use vMAJOR.MINOR.PATCH.' >&2 echo 'The release tag must use vMAJOR.MINOR.PATCH.' >&2
exit 1 exit 1
@@ -30,12 +56,16 @@ jobs:
export DOCKER_CONFIG="$work/docker" export DOCKER_CONFIG="$work/docker"
mkdir -m 700 "$DOCKER_CONFIG" mkdir -m 700 "$DOCKER_CONFIG"
registry=git.laysense.com
source_url="https://$registry/laysense/laysite"
image="$registry/laysense/laysite:$RELEASE_TAG" image="$registry/laysense/laysite:$RELEASE_TAG"
git init --quiet "$work/source" git init --quiet "$work/source"
git -C "$work/source" fetch --quiet --depth 1 "$source_url.git" "refs/tags/$RELEASE_TAG" git -C "$work/source" fetch --quiet --no-tags "$source_url.git" \
git -C "$work/source" checkout --quiet --detach FETCH_HEAD refs/heads/main:refs/remotes/origin/main "refs/tags/$RELEASE_TAG:refs/tags/$RELEASE_TAG"
release_commit="$(git -C "$work/source" rev-parse "refs/tags/$RELEASE_TAG^{commit}")"
if ! git -C "$work/source" merge-base --is-ancestor "$release_commit" refs/remotes/origin/main; then
echo 'The release tag must point to a commit on main.' >&2
exit 1
fi
git -C "$work/source" checkout --quiet --detach "$release_commit"
if [ "$(cat "$work/source/VERSION")" != "${RELEASE_TAG#v}" ]; then if [ "$(cat "$work/source/VERSION")" != "${RELEASE_TAG#v}" ]; then
echo 'VERSION in the release commit must match the tag.' >&2 echo 'VERSION in the release commit must match the tag.' >&2
exit 1 exit 1
@@ -44,20 +74,31 @@ jobs:
docker build --pull --tag "$image" \ docker build --pull --tag "$image" \
--label "org.opencontainers.image.source=$source_url" \ --label "org.opencontainers.image.source=$source_url" \
--label "org.opencontainers.image.version=${RELEASE_TAG#v}" \ --label "org.opencontainers.image.version=${RELEASE_TAG#v}" \
--label "org.opencontainers.image.revision=$(git -C "$work/source" rev-parse HEAD)" \ --label "org.opencontainers.image.revision=$release_commit" \
"$work/source" "$work/source"
printf '%s' "$PACKAGE_TOKEN" | docker login "$registry" --username "$PACKAGE_USERNAME" --password-stdin printf '%s' "$PACKAGE_TOKEN" | docker login "$registry" --username "$PACKAGE_USERNAME" --password-stdin
docker push "$image" docker push "$image"
package_url="https://$registry/api/v1/packages/laysense/container/laysite" package_url="https://$registry/api/v1/packages/laysense/container/laysite"
package_api() { package_api() {
printf 'Authorization: token %s\n' "$PACKAGE_TOKEN" \ printf 'Authorization: token %s\n' "$PACKAGE_TOKEN" \
| curl --fail --silent --show-error --header @- "$@" | curl --fail --silent --show-error --max-time 30 --header @- "$@"
} }
linked_repository() { linked_repository() {
package_api "$package_url/$RELEASE_TAG" | python3 -c \ local response
response="$(package_api "$package_url/$RELEASE_TAG")" || return 1
printf '%s' "$response" | python3 -c \
'import json, sys; print((json.load(sys.stdin).get("repository") or {}).get("full_name", ""))' 'import json, sys; print((json.load(sys.stdin).get("repository") or {}).get("full_name", ""))'
} }
linked_repo="$(linked_repository)" wait_for_package() {
local attempt
for attempt in 1 2 3 4; do
if linked_repository; then return 0; fi
if [ "$attempt" -lt 4 ]; then sleep 2; fi
done
echo 'The uploaded package is not visible in the API yet.' >&2
return 1
}
linked_repo="$(wait_for_package)"
if [ -z "$linked_repo" ]; then if [ -z "$linked_repo" ]; then
if ! package_api --request POST "$package_url/-/link/laysite"; then if ! package_api --request POST "$package_url/-/link/laysite"; then
[ "$(linked_repository)" = 'laysense/laysite' ] || exit 1 [ "$(linked_repository)" = 'laysense/laysite' ] || exit 1
+3 -3
View File
@@ -61,7 +61,7 @@ php start.php start
<script src="/assets/uploads/11111111111111111111111111111111.js" defer></script> <script src="/assets/uploads/11111111111111111111111111111111.js" defer></script>
``` ```
保存后,画布与独立预览都会加载样式。自定义脚本在独立预览和公开页面运行,独立预览中的脚本与后台会话隔离。以站点权限运行的脚本应来自可信来源。站点备份包含图标、Head 代码和上传的资源。 保存后,画布与独立预览都会加载样式。自定义脚本在独立预览和公开页面运行。启用自定义脚本后,独立预览会隔离 Cookie,并禁用表单提交和会员登录。内联脚本早于 LaySite 的 jQuery 执行。如需使用 jQuery,请用带 `defer` 的外部脚本,或在内联脚本中等待 `DOMContentLoaded`。站点备份包含图标、Head 代码和上传的资源。
### 维护页与 404 页 ### 维护页与 404 页
@@ -164,9 +164,9 @@ docker run -d --name laysite --restart unless-stopped \
docker exec -it laysite php bin/admin.php admin@example.com docker exec -it laysite php bin/admin.php admin@example.com
``` ```
示例由宿主机上的反向代理终止 HTTPS。容器以 UID/GID 10001 运行。使用宿主机目录代替命名卷时,请让该用户可写入挂载目录。升级时以新标签重建容器,并挂载同一个数据卷。 示例由宿主机上的反向代理终止 HTTPS。容器以 UID/GID 10001 运行。使用宿主机目录代替命名卷时,请让该用户可写入挂载目录。升级时以新标签重建容器,并挂载同一个数据卷。默认的 `runtime/` 存放会话、日志和缓存,重建后管理员需要重新登录。如需保留这些数据,也可挂载 `/opt/laysite/runtime`。
Gitea Actions 使用 `host` 标签。runner 的运行账户需要访问 Docker,并可调用 Git、curl 和 Python 3。发布前在仓库「设置 → Actions → Secrets」配置 `PACKAGE_USERNAME` 和 `PACKAGE_TOKEN`。令牌需要 `write:package` 权限,账号也须能向 `laysense` 发布包并关联 LaySite 仓库。工作流以 Release 标签检出源码,确认 `VERSION` 一致后构建、上传镜像并关联仓库。镜像会显示在 LaySite 的 Packages 页。 Gitea Actions 使用 `host` 标签。runner 的运行账户需要访问 Docker,并可调用 Git、curl 和 Python 3。内置 `GITEA_TOKEN` 使用 `releases: read` 读取 Release 元数据。OCI 推送使用仓库 Actions Secrets 中的 `PACKAGE_USERNAME` 和 `PACKAGE_TOKEN`。PAT 需要 `write:package`,所属账号须能向 `laysense` 发布包并关联 LaySite 仓库。工作流只发布正式 Release,核对标签指向 `main` 历史中的提交且与 `VERSION` 一致。镜像会显示在 LaySite 仓库的 Packages 页。[Gitea Actions 令牌权限](https://docs.gitea.com/usage/actions/token-permissions/) · [OCI 发布的权限限制](https://docs.gitea.com/usage/actions/comparison/#package-repository-authorization)
## 生产反代 ## 生产反代
+1
View File
@@ -11,6 +11,7 @@ use Throwable;
final class Database final class Database
{ {
public const MIGRATION_REQUIRED = '数据库尚未完成升级。请在站点目录运行 php bin/install.php。';
private const SCHEMA_VERSION = 8; private const SCHEMA_VERSION = 8;
// Avoid reusing a deleted ID that may still be open in an editing form. // Avoid reusing a deleted ID that may still be open in an editing form.
public const NEXT_ARTICLE_ID = 'MAX(COALESCE((SELECT MAX(id) FROM articles), 0), public const NEXT_ARTICLE_ID = 'MAX(COALESCE((SELECT MAX(id) FROM articles), 0),
+21 -5
View File
@@ -6,6 +6,7 @@ namespace App\Content;
use App\Config\Environment; use App\Config\Environment;
use PDO; use PDO;
use PDOException;
use RuntimeException; use RuntimeException;
final class McpSettings final class McpSettings
@@ -16,10 +17,13 @@ final class McpSettings
public static function read(): array public static function read(): array
{ {
$row = self::stored(Database::connect()); $row = self::stored(Database::connect());
if ($row === null) { $migrationRequired = $row === false;
$token = self::legacyToken(); $keyError = '';
if (!is_array($row)) {
$token = $migrationRequired ? null : self::legacyToken();
return ['enabled' => $token !== null, 'version' => 0, 'token' => $token, 'legacy' => $token !== null]; return ['enabled' => $token !== null, 'version' => 0, 'legacy' => $token !== null]
+ compact('token', 'migrationRequired', 'keyError');
} }
$enabled = (bool) $row['enabled']; $enabled = (bool) $row['enabled'];
@@ -27,12 +31,14 @@ final class McpSettings
if ($enabled && $row['encrypted_secret'] !== null) { if ($enabled && $row['encrypted_secret'] !== null) {
try { try {
$token = SiteSecrets::decrypt($row['encrypted_secret'], self::CONTEXT); $token = SiteSecrets::decrypt($row['encrypted_secret'], self::CONTEXT);
} catch (SiteKeyFileError $error) {
$keyError = $error->getMessage();
} catch (RuntimeException) { } catch (RuntimeException) {
// Keep the settings accessible so an administrator can replace an unreadable key. // Keep the settings accessible so an administrator can replace an unreadable key.
} }
} }
return ['enabled' => $enabled, 'version' => (int) $row['version'], 'token' => $token, 'legacy' => false]; return ['version' => (int) $row['version'], 'legacy' => false] + compact('enabled', 'token', 'migrationRequired', 'keyError');
} }
public static function save(bool $enabled, bool $rotate, int $version): void public static function save(bool $enabled, bool $rotate, int $version): void
@@ -42,6 +48,9 @@ final class McpSettings
} }
Database::write(static function (PDO $pdo) use ($enabled, $rotate, $version): void { Database::write(static function (PDO $pdo) use ($enabled, $rotate, $version): void {
$row = self::stored($pdo); $row = self::stored($pdo);
if ($row === false) {
throw new RuntimeException(Database::MIGRATION_REQUIRED);
}
if ($version !== (int) ($row['version'] ?? 0)) { if ($version !== (int) ($row['version'] ?? 0)) {
throw new RuntimeException('MCP 设置已更新,请刷新后再保存。'); throw new RuntimeException('MCP 设置已更新,请刷新后再保存。');
} }
@@ -58,9 +67,16 @@ final class McpSettings
}); });
} }
private static function stored(PDO $pdo): ?array private static function stored(PDO $pdo): array|false|null
{ {
try {
return $pdo->query('SELECT enabled, encrypted_secret, version FROM mcp_settings WHERE id = 1')->fetch() ?: null; return $pdo->query('SELECT enabled, encrypted_secret, version FROM mcp_settings WHERE id = 1')->fetch() ?: null;
} catch (PDOException $error) {
if (($error->errorInfo[2] ?? '') === 'no such table: mcp_settings') {
return false;
}
throw $error;
}
} }
private static function legacyToken(): ?string private static function legacyToken(): ?string
+7 -2
View File
@@ -38,7 +38,9 @@ final class PageHead
continue; continue;
} }
if ($tag === 'script') { if ($tag === 'script') {
if (strtolower($attributes['type'] ?? '') !== 'application/ld+json') {
$result['hasScript'] = true; $result['hasScript'] = true;
}
if (!isset($attributes['src'])) { if (!isset($attributes['src'])) {
$result['inlineScript'] = true; $result['inlineScript'] = true;
$attributes['nonce'] = $nonce; $attributes['nonce'] = $nonce;
@@ -83,8 +85,11 @@ final class PageHead
|| ($node->nodeType === XML_TEXT_NODE && trim($node->textContent) === '')) { || ($node->nodeType === XML_TEXT_NODE && trim($node->textContent) === '')) {
continue; continue;
} }
if (!$node instanceof DOMElement || !isset(self::ATTRIBUTES[$node->tagName]) || count($entries) >= 40) { if (!$node instanceof DOMElement || !isset(self::ATTRIBUTES[$node->tagName])) {
throw new RuntimeException('Head 最多支持 40 个 meta、样式表、style 或 script 标签。'); throw new RuntimeException('Head 仅支持 meta、样式表(link)、style 和 script 标签。');
}
if (count($entries) >= 40) {
throw new RuntimeException('Head 最多允许 40 个标签。');
} }
$tag = $node->tagName; $tag = $node->tagName;
$attributes = []; $attributes = [];
+5 -2
View File
@@ -132,14 +132,17 @@ final class Repository
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): void
{ {
Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections, $sectionOrder): void { Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections, $sectionOrder): void {
$head = $data['head_html'] ?? null;
$query = $pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?, $query = $pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?,
image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, visibility = ?, header_id = ?, footer_id = ?, palette_id = ?, status = ?, updated_at = ?, image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, visibility = ?, header_id = ?, footer_id = ?, palette_id = ?, status = ?, updated_at = ?,
presentation = COALESCE(?, presentation), head_html = COALESCE(?, head_html), version = version + 1 WHERE slug = ? AND version = ?'); presentation = COALESCE(?, presentation), ' . ($head === null ? '' : 'head_html = ?, ')
. 'version = version + 1 WHERE slug = ? AND version = ?');
$query->execute([ $query->execute([
$data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'], $data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'],
$data['image'], $data['alt'], $data['image_scale'], Database::json($data['alignments']), Database::json($data['actions']), Database::json($data['quicklinks']), $data['image'], $data['alt'], $data['image_scale'], Database::json($data['alignments']), Database::json($data['actions']), Database::json($data['quicklinks']),
Database::json($data['visibility']), $data['header_id'], $data['footer_id'], $data['palette_id'], $data['status'], self::now(), Database::json($data['visibility']), $data['header_id'], $data['footer_id'], $data['palette_id'], $data['status'], self::now(),
isset($data['presentation']) ? CanvasStyle::encode($data['presentation']) : null, $data['head_html'] ?? null, $slug, $version, isset($data['presentation']) ? CanvasStyle::encode($data['presentation']) : null,
...($head === null ? [] : [$head]), $slug, $version,
]); ]);
self::checkVersion($query->rowCount()); self::checkVersion($query->rowCount());
if ($data['status'] === 'draft' && str_starts_with($slug, 'system--')) { if ($data['status'] === 'draft' && str_starts_with($slug, 'system--')) {
+9
View File
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace App\Content;
final class SiteKeyFileError extends \RuntimeException
{
}
+9 -5
View File
@@ -44,8 +44,12 @@ final class SiteSecrets
private static function key(bool $create = false): string private static function key(bool $create = false): string
{ {
$path = Database::path() . '.key'; $path = Database::path() . '.key';
clearstatcache(true, $path);
if (is_link($path)) { if (is_link($path)) {
throw new RuntimeException('密钥文件不能使用符号链接。'); throw new SiteKeyFileError('密钥文件不能使用符号链接。');
}
if (!$create && !file_exists($path)) {
throw new RuntimeException('站点密钥文件缺失。');
} }
$mask = umask(0077); $mask = umask(0077);
try { try {
@@ -54,22 +58,22 @@ final class SiteSecrets
umask($mask); umask($mask);
} }
if ($file === false) { if ($file === false) {
throw new RuntimeException('无法打开站点密钥文件。'); throw new SiteKeyFileError('无法打开站点密钥文件。');
} }
try { try {
if (!flock($file, $create ? LOCK_EX : LOCK_SH) || (fstat($file)['mode'] & 0077) !== 0) { if (!flock($file, $create ? LOCK_EX : LOCK_SH) || (fstat($file)['mode'] & 0077) !== 0) {
throw new RuntimeException('站点密钥文件需能上锁,并且只能由运行用户访问。'); throw new SiteKeyFileError('站点密钥文件需能上锁,并且只能由运行用户访问。');
} }
$key = stream_get_contents($file, self::KEY_BYTES + 1); $key = stream_get_contents($file, self::KEY_BYTES + 1);
if ($create && $key === '') { if ($create && $key === '') {
$key = random_bytes(self::KEY_BYTES); $key = random_bytes(self::KEY_BYTES);
if (fwrite($file, $key) !== self::KEY_BYTES || !fflush($file)) { if (fwrite($file, $key) !== self::KEY_BYTES || !fflush($file)) {
ftruncate($file, 0); ftruncate($file, 0);
throw new RuntimeException('无法写入站点密钥文件。'); throw new SiteKeyFileError('无法写入站点密钥文件。');
} }
} }
if (!is_string($key) || strlen($key) !== self::KEY_BYTES) { if (!is_string($key) || strlen($key) !== self::KEY_BYTES) {
throw new RuntimeException('站点密钥文件格式无效。'); throw new SiteKeyFileError('站点密钥文件格式无效。');
} }
return $key; return $key;
+5 -1
View File
@@ -324,6 +324,7 @@ class AdminController
$layoutKind = $page['layout_kind']; $layoutKind = $page['layout_kind'];
$layout = $layoutKind === null ? null : DesignLibrary::find($page['layout_id'], $layoutKind); $layout = $layoutKind === null ? null : DesignLibrary::find($page['layout_id'], $layoutKind);
$default = $layout && ($site[$layoutKind . '_id'] ?? null) === $layout['id']; $default = $layout && ($site[$layoutKind . '_id'] ?? null) === $layout['id'];
$headEditor = !$layout && array_key_exists('head_html', $page);
$error = ''; $error = '';
if ($request->method() === 'POST') { if ($request->method() === 'POST') {
$data = []; $data = [];
@@ -348,6 +349,9 @@ class AdminController
} }
try { try {
if ($head !== null) { if ($head !== null) {
if (!$headEditor) {
throw new RuntimeException(Database::MIGRATION_REQUIRED);
}
$data['head_html'] = PageHead::normalize($head); $data['head_html'] = PageHead::normalize($head);
} }
$data['actions'] = $request->post('hero_actions') === null ? $page['actions'] $data['actions'] = $request->post('hero_actions') === null ? $page['actions']
@@ -426,7 +430,7 @@ class AdminController
return $this->render($request, 'admin-page', [ return $this->render($request, 'admin-page', [
'title' => '编辑 ' . $page['name'], 'page' => $page, 'categories' => $repo->categories(), 'wideAdmin' => true, 'canvasSourceEditor' => true, 'error' => $error, 'saved' => $request->get('saved') === '1', 'title' => '编辑 ' . $page['name'], 'page' => $page, 'categories' => $repo->categories(), 'wideAdmin' => true, 'canvasSourceEditor' => true, 'error' => $error, 'saved' => $request->get('saved') === '1',
'pageTemplateDrawer' => !$layout, 'headEditor' => !$layout, 'designs' => DesignLibrary::all(), 'layout' => $layout, 'layoutDefault' => $default, 'pageTemplateDrawer' => !$layout, 'headEditor' => $headEditor, 'designs' => DesignLibrary::all(), 'layout' => $layout, 'layoutDefault' => $default,
'layoutBase' => $layout && ($site['layout_defaults'][$layoutKind] ?? null) === $layout['id'], 'layoutBase' => $layout && ($site['layout_defaults'][$layoutKind] ?? null) === $layout['id'],
'siteName' => $site['name'], 'layoutHasMember' => $layoutKind === 'header' && LayoutPage::hasMember($page['sections']), 'siteName' => $site['name'], 'layoutHasMember' => $layoutKind === 'header' && LayoutPage::hasMember($page['sections']),
'layoutDefaults' => array_intersect_key($site, ['header_id' => true, 'footer_id' => true]), 'layoutDefaults' => array_intersect_key($site, ['header_id' => true, 'footer_id' => true]),
+1 -1
View File
@@ -34,7 +34,7 @@ final class McpController
return new Response(503, ['Cache-Control' => 'no-store']); return new Response(503, ['Cache-Control' => 'no-store']);
} }
$secret = $settings['token']; $secret = $settings['token'];
if ($settings['enabled'] && $secret === null) { if ($settings['migrationRequired'] || ($settings['enabled'] && $secret === null)) {
return new Response(503, ['Cache-Control' => 'no-store']); return new Response(503, ['Cache-Control' => 'no-store']);
} }
$header = $request->header('authorization', ''); $header = $request->header('authorization', '');
+8 -5
View File
@@ -70,8 +70,8 @@ $spacingPresets = [0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128];
<div class="canvas-font-combo"> <div class="canvas-font-combo">
<input id="canvas-font-size" type="number" data-canvas-font-size min="8" max="144" step="1" placeholder="px" disabled> <input id="canvas-font-size" type="number" data-canvas-font-size min="8" max="144" step="1" placeholder="px" disabled>
<select data-font-preset aria-label="常用字号(px)" title="常用字号" disabled> <select data-font-preset aria-label="常用字号(px)" title="常用字号" disabled>
<option value="" hidden>▾</option> <option value="" hidden>—</option>
<?php foreach ($fontSizes as $size): ?><option value="<?= $size ?>"><?= $size ?> px</option><?php endforeach ?> <?php foreach ($fontSizes as $size): ?><option value="<?= $size ?>"><?= $size ?></option><?php endforeach ?>
</select> </select>
</div> </div>
</div> </div>
@@ -134,8 +134,8 @@ $spacingPresets = [0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128];
<fieldset class="admin-options canvas-spacing-fields"><legend id="spacing-<?= $prefix ?>-legend"><?= $label ?>(px)</legend> <fieldset class="admin-options canvas-spacing-fields"><legend id="spacing-<?= $prefix ?>-legend"><?= $label ?>(px)</legend>
<div class="canvas-spacing-preset"> <div class="canvas-spacing-preset">
<label id="spacing-preset-<?= $prefix ?>-label" for="spacing-preset-<?= $prefix ?>">四边预设</label> <label id="spacing-preset-<?= $prefix ?>-label" for="spacing-preset-<?= $prefix ?>">四边预设</label>
<input id="spacing-preset-<?= $prefix ?>" type="range" min="0" max="<?= count($spacingPresets) - 1 ?>" step="1" <input id="spacing-preset-<?= $prefix ?>" type="range" min="-1" max="<?= count($spacingPresets) - 1 ?>" step="1"
value="<?= array_search(16, $spacingPresets, true) ?>" data-spacing-preset="<?= $e(Database::json($spacingPresets)) ?>" value="-1" data-spacing-preset="<?= $e(Database::json($spacingPresets)) ?>"
list="spacing-preset-ticks" aria-labelledby="spacing-<?= $prefix ?>-legend spacing-preset-<?= $prefix ?>-label"> list="spacing-preset-ticks" aria-labelledby="spacing-<?= $prefix ?>-legend spacing-preset-<?= $prefix ?>-label">
<output for="spacing-preset-<?= $prefix ?>" data-spacing-readout aria-live="off">默认</output> <output for="spacing-preset-<?= $prefix ?>" data-spacing-readout aria-live="off">默认</output>
<button class="button button-outline" type="button" data-spacing-reset>恢复默认</button> <button class="button button-outline" type="button" data-spacing-reset>恢复默认</button>
@@ -146,6 +146,7 @@ $spacingPresets = [0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128];
</fieldset> </fieldset>
<?php endforeach ?> <?php endforeach ?>
<datalist id="spacing-preset-ticks"> <datalist id="spacing-preset-ticks">
<option value="-1"></option>
<?php foreach (array_keys($spacingPresets) as $index): ?><option value="<?= $index ?>"></option><?php endforeach ?> <?php foreach (array_keys($spacingPresets) as $index): ?><option value="<?= $index ?>"></option><?php endforeach ?>
</datalist> </datalist>
<div class="actions"> <div class="actions">
@@ -281,8 +282,10 @@ $spacingPresets = [0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128];
<label>发布状态<select name="status"><option value="draft" <?= $page['status'] === 'draft' ? 'selected' : '' ?>>草稿</option> <label>发布状态<select name="status"><option value="draft" <?= $page['status'] === 'draft' ? 'selected' : '' ?>>草稿</option>
<option value="published" <?= $page['status'] === 'published' ? 'selected' : '' ?>>已发布</option></select></label> <option value="published" <?= $page['status'] === 'published' ? 'selected' : '' ?>>已发布</option></select></label>
<?php endif ?> <?php endif ?>
<?php if (!$layout): ?> <?php if ($headEditor): ?>
<?= View::fragment('head-settings', ['label' => '本页 Head', 'head' => $page['head_html']]) ?> <?= View::fragment('head-settings', ['label' => '本页 Head', 'head' => $page['head_html']]) ?>
<?php elseif (!$layout): ?>
<p class="field-note">本页 Head 尚不可用。<?= $e(Database::MIGRATION_REQUIRED) ?></p>
<?php endif ?> <?php endif ?>
<div class="form-submit"><button class="button button-primary" type="submit"><?= View::fragment('studio-icon', ['icon' => 'save']) ?>保存页面</button></div> <div class="form-submit"><button class="button button-primary" type="submit"><?= View::fragment('studio-icon', ['icon' => 'save']) ?>保存页面</button></div>
</form> </form>
+2
View File
@@ -12,6 +12,8 @@ $e = View::escape(...);
<textarea id="head-source" name="head_html" data-head-source rows="10" spellcheck="false" <textarea id="head-source" name="head_html" data-head-source rows="10" spellcheck="false"
autocapitalize="off" maxlength="<?= PageHead::MAX_LENGTH ?>"><?= $e($head) ?></textarea> autocapitalize="off" maxlength="<?= PageHead::MAX_LENGTH ?>"><?= $e($head) ?></textarea>
<p class="field-note">可添加 meta、样式表、style 和 script。全站代码先加载,本页代码随后加载。保存后,画布载入样式,脚本在独立预览和公开页面运行。</p> <p class="field-note">可添加 meta、样式表、style 和 script。全站代码先加载,本页代码随后加载。保存后,画布载入样式,脚本在独立预览和公开页面运行。</p>
<p class="field-note">需要使用 jQuery 时,请插入带 defer 的外部脚本,或让内联脚本等待 DOMContentLoaded。</p>
<p class="feedback error" data-head-limit role="status" hidden>Head 代码最多 32 KB(UTF-8)。请删减代码,或改用外部文件。</p>
<div class="actions"> <div class="actions">
<button class="button button-outline" type="button" data-head-asset="text/css"><?= View::fragment('studio-icon', ['icon' => 'add']) ?>插入样式表</button> <button class="button button-outline" type="button" data-head-asset="text/css"><?= View::fragment('studio-icon', ['icon' => 'add']) ?>插入样式表</button>
<button class="button button-outline" type="button" data-head-asset="text/javascript"><?= View::fragment('studio-icon', ['icon' => 'add']) ?>插入脚本</button> <button class="button button-outline" type="button" data-head-asset="text/javascript"><?= View::fragment('studio-icon', ['icon' => 'add']) ?>插入脚本</button>
+12 -6
View File
@@ -1,4 +1,5 @@
<?php <?php
use App\Content\Database;
use App\Content\McpSettings; use App\Content\McpSettings;
use App\Content\View; use App\Content\View;
@@ -37,16 +38,21 @@ $e = View::escape(...);
<input type="hidden" name="csrf" value="<?= $e($token) ?>"> <input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="settings_section" value="mcp"> <input type="hidden" name="settings_section" value="mcp">
<input type="hidden" name="version" value="<?= $e($mcp['version']) ?>"> <input type="hidden" name="version" value="<?= $e($mcp['version']) ?>">
<label><input type="checkbox" name="mcp_enabled" value="1"<?= $mcp['enabled'] ? ' checked' : '' ?>> 开放 MCP</label> <label><input type="checkbox" name="mcp_enabled" value="1"<?= $mcp['enabled'] ? ' checked' : '' ?><?= $mcp['migrationRequired'] ? ' disabled' : '' ?>> 开放 MCP</label>
<p class="field-note">允许持有密钥的 AI 客户端通过 Streamable HTTP 新建和编辑草稿。</p> <p class="field-note">允许持有密钥的 AI 客户端通过 Streamable HTTP 新建和编辑草稿。</p>
<?php if ($mcp['migrationRequired']): ?>
<p class="feedback error"><?= $e(Database::MIGRATION_REQUIRED) ?></p>
<?php endif ?>
<?php if ($mcp['enabled']): ?> <?php if ($mcp['enabled']): ?>
<label>连接网址<input type="url" readonly value="<?= $e(View::absolute(McpSettings::PATH)) ?>"></label> <label>连接网址<input type="url" readonly value="<?= $e(View::absolute(McpSettings::PATH)) ?>"></label>
<?php if ($mcp['token'] === null): ?> <?php if ($mcp['keyError'] !== ''): ?>
<p class="feedback error">当前密钥无法读取。生成新密钥后即可重新连接。</p> <p class="feedback error"><?= $e($mcp['keyError']) ?> 请检查数据库旁的 <code>.key</code> 文件及运行账户的权限。</p>
<?php elseif ($mcp['token'] === null): ?>
<p class="feedback error">当前密钥无法读取。可以生成新密钥并重新连接。</p>
<?php else: ?> <?php else: ?>
<details class="settings-stack"> <details class="settings-stack">
<summary>查看连接密钥</summary> <summary>查看连接密钥</summary>
<label>Bearer 密钥<input type="text" readonly spellcheck="false" autocomplete="off" value="<?= $e($mcp['token']) ?>"></label> <label>Bearer 密钥<input type="text" class="mcp-token" readonly spellcheck="false" autocomplete="off" value="<?= $e($mcp['token']) ?>"></label>
<p class="field-note">在客户端设置 Authorization 请求头,格式为 Bearer 后加一个空格和密钥。</p> <p class="field-note">在客户端设置 Authorization 请求头,格式为 Bearer 后加一个空格和密钥。</p>
</details> </details>
<?php endif ?> <?php endif ?>
@@ -55,8 +61,8 @@ $e = View::escape(...);
<p class="field-note">当前密钥来自环境变量 LAYSITE_MCP_TOKEN。保存后由后台管理。</p> <p class="field-note">当前密钥来自环境变量 LAYSITE_MCP_TOKEN。保存后由后台管理。</p>
<?php endif ?> <?php endif ?>
<div class="actions"> <div class="actions">
<button type="submit" class="button button-primary"><?= View::fragment('studio-icon', ['icon' => 'save']) ?>保存 MCP 设置</button> <button type="submit" class="button button-primary"<?= $mcp['migrationRequired'] ? ' disabled' : '' ?>><?= View::fragment('studio-icon', ['icon' => 'save']) ?>保存 MCP 设置</button>
<?php if ($mcp['enabled']): ?> <?php if ($mcp['enabled'] && $mcp['keyError'] === ''): ?>
<button type="submit" class="button button-outline" name="rotate_mcp_token" value="1" data-confirm="生成新密钥后,原有的 MCP 连接需要更换密钥。继续吗?"><?= View::fragment('studio-icon', ['icon' => 'refresh']) ?>生成新密钥</button> <button type="submit" class="button button-outline" name="rotate_mcp_token" value="1" data-confirm="生成新密钥后,原有的 MCP 连接需要更换密钥。继续吗?"><?= View::fragment('studio-icon', ['icon' => 'refresh']) ?>生成新密钥</button>
<?php endif ?> <?php endif ?>
</div> </div>
+2 -1
View File
@@ -113,7 +113,7 @@
.canvas-font-combo { gap: 0; } .canvas-font-combo { gap: 0; }
.canvas-font-combo input { border-start-end-radius: 0; border-end-end-radius: 0; } .canvas-font-combo input { border-start-end-radius: 0; border-end-end-radius: 0; }
.canvas-font-combo select { .canvas-font-combo select {
appearance: none; text-align: center; width: 2.15rem; min-height: 2.45rem; padding: 0; width: 3.1rem; min-height: 2.45rem; padding: 0 .15rem;
color: var(--ink); background: var(--white); border: 1px solid var(--line); border-inline-start: 0; color: var(--ink); background: var(--white); border: 1px solid var(--line); border-inline-start: 0;
border-start-end-radius: .35rem; border-end-end-radius: .35rem; cursor: pointer; border-start-end-radius: .35rem; border-end-end-radius: .35rem; cursor: pointer;
} }
@@ -446,6 +446,7 @@
:is(.canvas-source, .head-settings) .CodeMirror-focused { outline: 2px solid var(--accent); outline-offset: 1px; } :is(.canvas-source, .head-settings) .CodeMirror-focused { outline: 2px solid var(--accent); outline-offset: 1px; }
.head-settings-fields { display: grid; gap: .65rem; margin-block-start: .6rem; } .head-settings-fields { display: grid; gap: .65rem; margin-block-start: .6rem; }
.head-settings .CodeMirror { height: clamp(13rem, 38vh, 22rem); margin: 0; } .head-settings .CodeMirror { height: clamp(13rem, 38vh, 22rem); margin: 0; }
.mcp-token { font-family: var(--mono); }
.favicon-editor-row { display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; } .favicon-editor-row { display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; }
.favicon-preview { .favicon-preview {
display: grid; place-items: center; inline-size: 6rem; block-size: 6rem; display: grid; place-items: center; inline-size: 6rem; block-size: 6rem;
+13 -1
View File
@@ -4,6 +4,15 @@ jQuery(function ($) {
$('[data-head-settings]').each(function () { $('[data-head-settings]').each(function () {
const $details = $(this); const $details = $(this);
const source = $details.find('[data-head-source]').get(0); const source = $details.find('[data-head-source]').get(0);
const $limit = $details.find('[data-head-limit]');
const encoder = new TextEncoder();
const size = (value) => encoder.encode(value).length;
function fits(current, removed, added) {
const original = size(current);
const next = original - size(removed) + size(added);
$limit.prop('hidden', next <= source.maxLength);
return next <= source.maxLength || next < original;
}
let editor; let editor;
$details.on('toggle', () => { $details.on('toggle', () => {
if (!this.open || !window.CodeMirror) return; if (!this.open || !window.CodeMirror) return;
@@ -12,6 +21,9 @@ jQuery(function ($) {
mode: 'htmlmixed', lineNumbers: true, lineWrapping: true, indentUnit: 2, tabSize: 2, mode: 'htmlmixed', lineNumbers: true, lineWrapping: true, indentUnit: 2, tabSize: 2,
}); });
editor.getInputField().setAttribute('aria-labelledby', 'head-source-label'); editor.getInputField().setAttribute('aria-labelledby', 'head-source-label');
editor.on('beforeChange', (cm, change) => {
if (!fits(cm.getValue(), cm.getRange(change.from, change.to), change.text.join('\n'))) change.cancel();
});
editor.on('change', () => editor.save()); editor.on('change', () => editor.save());
} }
editor.refresh(); editor.refresh();
@@ -26,7 +38,7 @@ jQuery(function ($) {
if (editor) { if (editor) {
editor.replaceSelection(value); editor.replaceSelection(value);
editor.focus(); editor.focus();
} else { } else if (fits(source.value, source.value.slice(source.selectionStart, source.selectionEnd), value)) {
source.setRangeText(value, source.selectionStart, source.selectionEnd, 'end'); source.setRangeText(value, source.selectionStart, source.selectionEnd, 'end');
source.focus(); source.focus();
} }
+9 -5
View File
@@ -753,8 +753,13 @@ jQuery(function ($) {
const target = doc && formatTarget(); const target = doc && formatTarget();
$format.add($fontSize).add($fontPreset).prop('disabled', !target); $format.add($fontSize).add($fontPreset).prop('disabled', !target);
const sample = target && (selectedText()[0]?.node || target); const sample = target && (selectedText()[0]?.node || target);
const computed = sample ? doc.defaultView.getComputedStyle(sample.nodeType === 1 ? sample : sample.parentElement) : null; const element = sample?.nodeType === 1 ? sample : sample?.parentElement;
if (!$fontSize.is(':focus')) $fontSize.val(computed ? Math.round(parseFloat(computed.fontSize)) : ''); const computed = element ? doc.defaultView.getComputedStyle(element) : null;
const sizeClass = element && classesOf(element).size;
const size = sizeClass ? sizeClass.slice('studio-style-size-'.length)
: (computed ? String(Math.round(parseFloat(computed.fontSize))) : '');
if (!$fontSize.is(':focus')) $fontSize.val(size);
$fontPreset.val($fontPreset.find('option').toArray().some((option) => option.value === size) ? size : '');
$color.add($clearColor).prop('disabled', !target); $color.add($clearColor).prop('disabled', !target);
const rgb = computed?.color.match(/^rgba?\((\d+), (\d+), (\d+)(?:, [\d.]+)?\)$/); const rgb = computed?.color.match(/^rgba?\((\d+), (\d+), (\d+)(?:, [\d.]+)?\)$/);
if (rgb && !$color.is(':focus')) $color.val('#' + rgb.slice(1).map((channel) => Number(channel).toString(16).padStart(2, '0')).join('')); if (rgb && !$color.is(':focus')) $color.val('#' + rgb.slice(1).map((channel) => Number(channel).toString(16).padStart(2, '0')).join(''));
@@ -815,7 +820,6 @@ jQuery(function ($) {
$format.on('click', function () { applyTextStyle(this.dataset.canvasFormat); }); $format.on('click', function () { applyTextStyle(this.dataset.canvasFormat); });
$fontPreset.on('change', function () { $fontPreset.on('change', function () {
applyTextStyle('size', this.value); applyTextStyle('size', this.value);
this.value = '';
}); });
$fontSize.on('change', function () { $fontSize.on('change', function () {
if (this.validity.valid) applyTextStyle('size', this.value === '' ? '' : String(this.valueAsNumber)); if (this.validity.valid) applyTextStyle('size', this.value === '' ? '' : String(this.valueAsNumber));
@@ -833,7 +837,7 @@ jQuery(function ($) {
const presets = $preset.data('spacingPreset'); const presets = $preset.data('spacingPreset');
const index = same && values[0] !== '' ? presets.indexOf(Number(values[0])) : -1; const index = same && values[0] !== '' ? presets.indexOf(Number(values[0])) : -1;
const label = !same ? '自定义' : (values[0] === '' ? '默认' : values[0] + ' px'); const label = !same ? '自定义' : (values[0] === '' ? '默认' : values[0] + ' px');
$preset.val(index === -1 ? $preset.prop('defaultValue') : index).attr('aria-valuetext', label); $preset.val(index).attr('aria-valuetext', label);
$fields.find('[data-spacing-readout]').text(label); $fields.find('[data-spacing-readout]').text(label);
} }
@@ -850,7 +854,7 @@ jQuery(function ($) {
$spacingForm.on('input', '[data-spacing-preset]', function () { $spacingForm.on('input', '[data-spacing-preset]', function () {
const $preset = $(this); const $preset = $(this);
const $fields = $preset.closest('fieldset'); const $fields = $preset.closest('fieldset');
$fields.find('[data-spacing-side]').val($preset.data('spacingPreset')[this.valueAsNumber]); $fields.find('[data-spacing-side]').val($preset.data('spacingPreset')[this.valueAsNumber] ?? '');
syncSpacingPreset($fields); syncSpacingPreset($fields);
}).on('input', '[data-spacing-side]', function () { }).on('input', '[data-spacing-side]', function () {
syncSpacingPreset($(this).closest('fieldset')); syncSpacingPreset($(this).closest('fieldset'));