forked from laysense/laysite
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc58b438d4 | ||
|
|
1f5990e687 | ||
|
|
9fb69f4d00 | ||
|
|
b77d742698 | ||
|
|
9e6679f493 | ||
|
|
a68f766f6e | ||
|
|
a7b37ee7d4 | ||
|
|
a78869dba4 |
@@ -109,17 +109,24 @@ php bin/backup.php export /srv/backups/laysite-2026-11.tar
|
||||
php bin/backup.php import /srv/backups/laysite-2026-11.tar --replace
|
||||
```
|
||||
|
||||
可在「账户 → 关于系统」点击「检查更新」,比较本机版本与 `git.laysense.com/laysense/laysite` 的最新 `vX.Y.Z` 发布标签。已合并但尚未打标签的版本不会出现在检查结果里。检查结果缓存 5 分钟。
|
||||
可在「账户 → 关于系统」点击「检查更新」,比较本机版本和 LaySite 仓库的最新正式发布。检查结果缓存 5 分钟。维护者发版时,先更新 `VERSION`,再用该提交创建同版本标签与正式 Release。
|
||||
|
||||
维护者发布新版本时,在发布提交上创建并推送与 `VERSION` 对应的标签,例如 `v1.4.0`。
|
||||
|
||||
使用 Git 标签选择部署版本。更新命令先备份,再检出所选版本、安装锁定依赖并运行 SQLite 初始化或迁移。更新时暂停 Webman,更新结束后重新启动。保持源代码工作区干净,并将备份放到部署路径之外。
|
||||
独立更新器 `bin/update.php` 可从已安装站点的根目录运行。它先读取官方主分支的 [更新器兼容表](updatescript_map.json),按内置的更新器版本选择起始和目标范围,再从 Gitea 的 Release 列表查找可用版本。范围包含两端,`v1.1.0-latest` 上限为当前最新正式发布。可通过兼容表收紧旧更新器的适用范围。
|
||||
|
||||
```sh
|
||||
bin/update.sh check
|
||||
bin/update.sh v1.1.0 /srv/backups/pre-update.tar
|
||||
php bin/update.php
|
||||
php bin/update.php check
|
||||
php bin/update.php v1.4.2 /srv/backups/pre-update.tar
|
||||
# 从旧安装运行单独下载的更新器
|
||||
php /path/to/update.php v1.4.2
|
||||
```
|
||||
|
||||
无参数时会显示可选版本及发布说明,选择编号或标签后开始更新。指定版本会直接检查并执行。省略备份路径时会写入 `storage/backups/`。原 `bin/update.sh` 入口已停用。
|
||||
|
||||
更新前请暂停 Webman。脚本从 LaySite 上游下载所选标签的 ZIP,通过 PHP 的 Phar 和 zlib 读取。它先比较当前发布包、新发布包和本地文件,再备份站点、按需安装 Composer 依赖、替换程序文件并运行 SQLite 迁移。
|
||||
|
||||
站点设置、SQLite、媒体和站点新增的文件保留原位。对于本地与上游都改过的同一文件,脚本会在替换前列出冲突路径。处理这些定制后再更新。
|
||||
|
||||
从 v1.0.0 升级时,让执行迁移的进程能读到原先填写的 `LAYSITE_OAUTH_*` 值。升级会将这些密钥转存到 SQLite,成功后即可移除旧变量。若迁移时缺少某个旧值,在对应会员页头补填密钥即可启用登录。
|
||||
|
||||
从 v1.1.0 更新画布功能时,更新脚本会添加样式字段,并将已有页头和页脚迁到「网站页面」,保留页面引用和已有认证配置。手动更新源码后,运行 `php bin/install.php` 再启动 Webman。
|
||||
|
||||
@@ -9,6 +9,7 @@ use RuntimeException;
|
||||
final class CanvasStyle
|
||||
{
|
||||
public const PAGE = ['hero', 'heading', 'accent', 'lead', 'eyebrow', 'image', 'actions', 'navigation', 'breadcrumbs'];
|
||||
public const MIN_MEDIA_SCALE = 1;
|
||||
public const SECTION = ['section', 'title', 'lead', 'body'];
|
||||
|
||||
private const PROPERTIES = [
|
||||
@@ -82,7 +83,7 @@ final class CanvasStyle
|
||||
|| ($textLength += strlen($run[0])) > 2400 || !mb_check_encoding($run[0], 'UTF-8')) {
|
||||
throw new RuntimeException('文字格式无效。');
|
||||
}
|
||||
$cleanRuns[] = [$run[0], self::classList($run[1], textOnly: true)];
|
||||
$cleanRuns[] = [self::lineBreaks($run[0]), self::classList($run[1], textOnly: true)];
|
||||
}
|
||||
if ($classes !== '' || $cleanRuns !== []) {
|
||||
$styles[$role] = ['classes' => $classes, 'runs' => $cleanRuns];
|
||||
@@ -141,15 +142,21 @@ final class CanvasStyle
|
||||
return $result;
|
||||
}
|
||||
|
||||
public static function lineBreaks(string $text): string
|
||||
{
|
||||
return str_replace(["\r\n", "\r"], "\n", $text);
|
||||
}
|
||||
|
||||
public static function text(array $styles, string $role, string $plain): string
|
||||
{
|
||||
$plain = self::lineBreaks($plain);
|
||||
$runs = $styles[$role]['runs'] ?? [];
|
||||
if ($runs === [] || trim(implode('', array_column($runs, 0))) !== $plain) {
|
||||
return str_replace(["\r\n", "\r", "\n"], '<br>', View::escape($plain));
|
||||
if ($runs === [] || self::lineBreaks(trim(implode('', array_column($runs, 0)))) !== $plain) {
|
||||
return str_replace("\n", '<br>', View::escape($plain));
|
||||
}
|
||||
$markup = '';
|
||||
foreach ($runs as [$text, $class]) {
|
||||
$escaped = str_replace("\n", '<br>', View::escape($text));
|
||||
$escaped = str_replace("\n", '<br>', View::escape(self::lineBreaks($text)));
|
||||
$markup .= $class === '' ? $escaped : '<span class="' . View::escape($class) . '">' . $escaped . '</span>';
|
||||
}
|
||||
|
||||
@@ -175,7 +182,7 @@ final class CanvasStyle
|
||||
$css .= '.' . self::PREFIX . "$key-$value{{$property}:{$value}px!important}\n";
|
||||
}
|
||||
}
|
||||
for ($width = 10; $width <= 100; $width++) {
|
||||
for ($width = self::MIN_MEDIA_SCALE; $width <= 100; $width++) {
|
||||
$css .= ".studio-media-{$width}{--studio-media-factor:calc({$width} / 100)}\n";
|
||||
}
|
||||
foreach (self::TYPOGRAPHY as $key => $value) {
|
||||
|
||||
@@ -32,6 +32,10 @@ final class Licenses
|
||||
'url' => 'https://jquery.com/', 'file' => $root . '/public/assets/jquery-LICENSE.txt'],
|
||||
'toast-ui-editor' => ['name' => 'TOAST UI Editor', 'version' => self::declaredVersion($editor, '~@version\h+' . $version . '~'), 'license' => 'MIT',
|
||||
'url' => 'https://github.com/nhn/tui.editor', 'file' => $root . '/public/assets/vendor/toastui/LICENSE'],
|
||||
'codemirror' => ['name' => 'CodeMirror', 'version' => '5.65.21', 'license' => 'MIT',
|
||||
'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'],
|
||||
'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',
|
||||
|
||||
+15
-15
@@ -10,7 +10,7 @@ use RuntimeException;
|
||||
final class Updates
|
||||
{
|
||||
public const REPOSITORY = 'https://git.laysense.com/laysense/laysite';
|
||||
private const TAGS = 'https://git.laysense.com/api/v1/repos/laysense/laysite/tags';
|
||||
private const RELEASES = 'https://git.laysense.com/api/v1/repos/laysense/laysite/releases';
|
||||
|
||||
public static function current(): string
|
||||
{
|
||||
@@ -44,7 +44,7 @@ final class Updates
|
||||
$record = self::cached($path);
|
||||
if (($record['until'] ?? 0) <= time()) {
|
||||
try {
|
||||
$record = ['latest' => self::latestTag(), 'until' => time() + 300];
|
||||
$record = ['latest' => self::latestRelease(), 'until' => time() + 300];
|
||||
} catch (RuntimeException $exception) {
|
||||
$record = ['error' => $exception->getMessage(), 'until' => time() + 30];
|
||||
}
|
||||
@@ -97,7 +97,7 @@ final class Updates
|
||||
}
|
||||
}
|
||||
|
||||
private static function latestTag(): ?string
|
||||
private static function latestRelease(): ?string
|
||||
{
|
||||
$latest = null;
|
||||
$deadline = hrtime(true) + 3_000_000_000;
|
||||
@@ -107,25 +107,25 @@ final class Updates
|
||||
if ($remaining <= 0) {
|
||||
throw new RuntimeException('读取上游版本超时,请稍后重试。');
|
||||
}
|
||||
$tags = self::tags($page++, $remaining);
|
||||
foreach ($tags as $tag) {
|
||||
$name = $tag['name'] ?? null;
|
||||
if (!is_string($name)) {
|
||||
$releases = self::releases($page++, $remaining);
|
||||
foreach ($releases as $release) {
|
||||
$name = $release['tag_name'] ?? null;
|
||||
if (!is_string($name) || !is_bool($release['draft'] ?? null) || !is_bool($release['prerelease'] ?? null)) {
|
||||
throw new RuntimeException('上游仓库返回的版本列表无效。');
|
||||
}
|
||||
if (preg_match('/^v(\d+\.\d+\.\d+)$/D', $name, $match)
|
||||
if (!$release['draft'] && !$release['prerelease'] && preg_match('/^v(\d+\.\d+\.\d+)$/D', $name, $match)
|
||||
&& ($latest === null || version_compare($match[1], $latest, '>'))) {
|
||||
$latest = $match[1];
|
||||
}
|
||||
}
|
||||
} while (count($tags) === 50);
|
||||
} while (count($releases) === 50);
|
||||
|
||||
return $latest;
|
||||
}
|
||||
|
||||
private static function tags(int $page, int $timeout): array
|
||||
private static function releases(int $page, int $timeout): array
|
||||
{
|
||||
$curl = curl_init(self::TAGS . '?limit=50&page=' . $page);
|
||||
$curl = curl_init(self::RELEASES . '?limit=50&page=' . $page);
|
||||
if ($curl === false) {
|
||||
throw new RuntimeException('无法连接上游仓库,请稍后重试。');
|
||||
}
|
||||
@@ -138,7 +138,7 @@ final class Updates
|
||||
CURLOPT_HTTPHEADER => ['Accept: application/json'],
|
||||
CURLOPT_USERAGENT => 'LaySite version check',
|
||||
CURLOPT_WRITEFUNCTION => static function (CurlHandle $handle, string $chunk) use (&$body, &$overflow): int {
|
||||
if (strlen($body) + strlen($chunk) > 256 * 1024) {
|
||||
if (strlen($body) + strlen($chunk) > 1024 * 1024) {
|
||||
$overflow = true;
|
||||
return 0;
|
||||
}
|
||||
@@ -155,11 +155,11 @@ final class Updates
|
||||
if ($status !== 200) {
|
||||
throw new RuntimeException('上游版本列表暂不可用(HTTP ' . $status . ')。');
|
||||
}
|
||||
$tags = json_decode($body);
|
||||
if (!is_array($tags) || !array_is_list($tags)) {
|
||||
$releases = json_decode($body);
|
||||
if (!is_array($releases) || !array_is_list($releases)) {
|
||||
throw new RuntimeException('上游仓库返回的版本列表无效。');
|
||||
}
|
||||
|
||||
return array_map(static fn ($tag): array => is_object($tag) ? get_object_vars($tag) : [], $tags);
|
||||
return array_map(static fn ($release): array => is_object($release) ? get_object_vars($release) : [], $releases);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,6 +329,9 @@ class AdminController
|
||||
foreach (['title', 'description', 'heading', 'accent', 'lead', 'image', 'alt'] as $field) {
|
||||
$data[$field] = $this->input($request, $field);
|
||||
}
|
||||
foreach (['heading', 'accent', 'lead'] as $field) {
|
||||
$data[$field] = CanvasStyle::lineBreaks($data[$field]);
|
||||
}
|
||||
$data['name'] = $request->post('name') === null ? $page['name'] : $this->input($request, 'name');
|
||||
if ($layout) {
|
||||
$data['title'] = $data['name'];
|
||||
@@ -392,7 +395,7 @@ class AdminController
|
||||
(!$layout && $page['page_type'] === 'page' && $data['status'] === 'published' && $data['description'] === '') || mb_strlen($data['description']) > 300 ||
|
||||
(($data['visibility']['hero'] ?? true) && !array_key_exists('heroHtml', $data['presentation']) && $data['heading'] === '') || mb_strlen($data['heading'] . $data['accent']) > 110 ||
|
||||
mb_strlen($data['lead']) > 600 || mb_strlen($data['alt']) > 200 ||
|
||||
($data['image_scale'] !== 0 && ($data['image_scale'] < 10 || $data['image_scale'] > 100)) ||
|
||||
($data['image_scale'] !== 0 && ($data['image_scale'] < CanvasStyle::MIN_MEDIA_SCALE || $data['image_scale'] > 100)) ||
|
||||
strlen($data['image']) > 1000 || ($data['image'] !== '' && !Html::url($data['image'], true))) {
|
||||
throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。');
|
||||
}
|
||||
@@ -414,7 +417,7 @@ class AdminController
|
||||
}
|
||||
|
||||
return $this->render($request, 'admin-page', [
|
||||
'title' => '编辑 ' . $page['name'], 'page' => $page, 'categories' => $repo->categories(), 'wideAdmin' => 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, 'designs' => DesignLibrary::all(), 'layout' => $layout, 'layoutDefault' => $default,
|
||||
'layoutBase' => $layout && ($site['layout_defaults'][$layoutKind] ?? null) === $layout['id'],
|
||||
'siteName' => $site['name'], 'layoutHasMember' => $layoutKind === 'header' && LayoutPage::hasMember($page['sections']),
|
||||
|
||||
@@ -31,6 +31,12 @@ $active = match (true) {
|
||||
<link rel="stylesheet" href="/assets/page-template-drawer.css">
|
||||
<script src="/assets/page-template-drawer.js" defer></script>
|
||||
<?php endif ?>
|
||||
<?php if (!empty($canvasSourceEditor)): ?>
|
||||
<link rel="stylesheet" href="/assets/vendor/codemirror/codemirror.min.css">
|
||||
<script src="/assets/vendor/codemirror/codemirror.min.js" defer></script>
|
||||
<script src="/assets/vendor/codemirror/xml.min.js" defer></script>
|
||||
<script src="/assets/vendor/js-beautify/beautify-html.min.js" defer></script>
|
||||
<?php endif ?>
|
||||
<?php if (!empty($articleEditor)): ?>
|
||||
<link rel="stylesheet" href="/assets/vendor/toastui/toastui-editor.min.css">
|
||||
<script src="<?= $e(Assets::TOAST_UI_EDITOR) ?>" defer></script>
|
||||
@@ -78,7 +84,21 @@ $active = match (true) {
|
||||
<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 noreferrer">打开媒体库上传</a>
|
||||
<div class="actions picker-actions">
|
||||
<button class="button button-outline" type="button" data-refresh-picker><?= View::fragment('studio-icon', ['icon' => 'refresh']) ?>刷新资源</button>
|
||||
<a class="back-link" href="/admin/media" target="_blank" rel="noopener noreferrer">打开媒体库上传</a>
|
||||
</div>
|
||||
</dialog>
|
||||
<dialog class="media-picker admin-action-dialog" id="admin-action-dialog" aria-labelledby="admin-action-heading">
|
||||
<form class="admin-form" method="dialog">
|
||||
<h2 id="admin-action-heading" data-action-title></h2>
|
||||
<p data-action-message hidden></p>
|
||||
<label data-action-field hidden><span data-action-label></span><input data-action-value></label>
|
||||
<div class="actions">
|
||||
<button class="button button-primary" data-action-accept value="accept" type="submit">确定</button>
|
||||
<button class="button button-outline" data-action-cancel type="button">取消</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
<?php endif ?>
|
||||
</body>
|
||||
|
||||
+18
-4
@@ -91,7 +91,7 @@ $systemLabel = SystemPage::TYPES[$page['page_type']] ?? null;
|
||||
<button type="button" data-element-<?= $action ?> aria-label="<?= $label ?>" title="<?= $label ?>"><?= View::fragment('studio-icon', compact('icon')) ?></button>
|
||||
<?php endforeach ?>
|
||||
</div>
|
||||
<button class="studio-media-handle" type="button" role="slider" aria-label="媒体宽度" aria-valuemin="10" aria-valuemax="100" aria-valuenow="100" data-media-handle hidden></button>
|
||||
<button class="studio-media-handle" type="button" role="slider" aria-label="媒体宽度" aria-valuemin="<?= CanvasStyle::MIN_MEDIA_SCALE ?>" aria-valuemax="100" aria-valuenow="100" data-media-handle hidden></button>
|
||||
<div class="studio-media-sizing" data-media-sizing hidden>
|
||||
<output data-media-size aria-hidden="true"></output>
|
||||
<button class="button button-outline" type="button" data-reset-media>原始尺寸</button>
|
||||
@@ -103,7 +103,10 @@ $systemLabel = SystemPage::TYPES[$page['page_type']] ?? null;
|
||||
<div class="admin-heading compact"><h2 id="canvas-source-heading">编辑区块 HTML</h2></div>
|
||||
<form class="admin-form" method="dialog">
|
||||
<label>源代码区域<select data-source-part></select></label>
|
||||
<label>HTML<textarea data-source-code rows="15" spellcheck="false" autocapitalize="off" maxlength="300000"></textarea></label>
|
||||
<div>
|
||||
<label for="canvas-source-code">HTML 源码</label>
|
||||
<textarea id="canvas-source-code" data-source-code rows="15" spellcheck="false" autocapitalize="off" maxlength="300000" wrap="off"></textarea>
|
||||
</div>
|
||||
<p class="field-note" data-source-hint></p>
|
||||
<p class="feedback error" data-source-error role="alert" hidden></p>
|
||||
<div class="actions">
|
||||
@@ -118,6 +121,17 @@ $systemLabel = SystemPage::TYPES[$page['page_type']] ?? null;
|
||||
<form class="admin-form" method="dialog">
|
||||
<?php foreach (['p' => ['内边距', 0], 'm' => ['外边距', -128]] as $prefix => [$label, $min]): ?>
|
||||
<fieldset class="admin-options canvas-spacing-fields"><legend><?= $label ?>(px)</legend>
|
||||
<label class="canvas-spacing-preset">四边预设
|
||||
<select data-spacing-preset>
|
||||
<option value="">自定义</option>
|
||||
<option value="template">恢复默认</option>
|
||||
<option value="0">无间距 · 0 px</option>
|
||||
<option value="8">紧凑 · 8 px</option>
|
||||
<option value="16">常规 · 16 px</option>
|
||||
<option value="24">宽松 · 24 px</option>
|
||||
<option value="32">大间距 · 32 px</option>
|
||||
</select>
|
||||
</label>
|
||||
<?php foreach (['t' => '上', 'r' => '右', 'b' => '下', 'l' => '左'] as $side => $direction): ?>
|
||||
<label><?= $direction ?><input name="<?= $prefix . $side ?>" type="number" min="<?= $min ?>" max="128" step="1" placeholder="默认"></label>
|
||||
<?php endforeach ?>
|
||||
@@ -246,8 +260,8 @@ $systemLabel = SystemPage::TYPES[$page['page_type']] ?? null;
|
||||
];
|
||||
?>
|
||||
<?php foreach ($contentFields as $field => $value): ?>
|
||||
<?php if ($field === 'quicklinks'): ?>
|
||||
<textarea name="quicklinks" hidden><?= $e($value) ?></textarea>
|
||||
<?php if (in_array($field, ['heading', 'accent', 'lead', 'quicklinks'], true)): ?>
|
||||
<textarea name="<?= $e($field) ?>" hidden><?= $e($value) ?></textarea>
|
||||
<?php else: ?>
|
||||
<input type="hidden" name="<?= $e($field) ?>" value="<?= $e($value) ?>">
|
||||
<?php endif ?>
|
||||
|
||||
+575
@@ -0,0 +1,575 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
final class LaySiteUpdater
|
||||
{
|
||||
private const UPDATESCRIPT_VERSION = '1.0.0';
|
||||
private const HOST = 'https://git.laysense.com';
|
||||
private const PROJECT = '/laysense/laysite';
|
||||
private const MAP_PATH = self::PROJECT . '/raw/branch/main/updatescript_map.json';
|
||||
private const RELEASES_PATH = '/api/v1/repos' . self::PROJECT . '/releases';
|
||||
private const TAG = '/^v(\d+\.\d+\.\d+)$/D';
|
||||
|
||||
// These two releases shipped with 1.4.0 in VERSION. Identify their original files when updating old installations.
|
||||
private const LEGACY_VERSIONS = [
|
||||
'1.4.2' => [
|
||||
'bin/update.sh' => 'a1cc96a5ecc3db3074563877dec07f0ebf8689e90e0e9aece838071df4793e26',
|
||||
'bin/update.php' => 'b13d3e925b59589f4d599d6deebb1fb27fa81ad0b98e5d0c67199279c3de9635',
|
||||
],
|
||||
'1.4.1' => [
|
||||
'public/assets/vendor/codemirror/xml.min.js' => 'c0c38a5cf20549c4e20d90428edd830cbbf6a631245a1ac2fb8e88676d4c0b7a',
|
||||
],
|
||||
];
|
||||
private const LEGACY_BASES = ['1.3.0' => 'd5bedabaa1d0187e29060c41fb030e9587a8692f'];
|
||||
private const MANAGED = '/^(?:(?:app|bin|config|public|resources|support|\.agents\/skills\/laysite-mcp)\/.+|\.env\.example|\.gitattributes|\.gitignore|LICENSE|NOTICE|README\.md|VERSION|updatescript_map\.json|composer\.(?:json|lock)|start\.php)$/D';
|
||||
private const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024;
|
||||
private const MAX_EXPANDED_BYTES = 256 * 1024 * 1024;
|
||||
|
||||
public function __construct(private readonly string $root)
|
||||
{
|
||||
}
|
||||
|
||||
public function execute(?string $target, ?string $backup): void
|
||||
{
|
||||
$current = $this->version();
|
||||
$map = self::remoteJson(self::MAP_PATH, 65536, 10000);
|
||||
$rule = is_object($map) ? ($map->{self::UPDATESCRIPT_VERSION} ?? null) : null;
|
||||
if (!is_object($rule)) {
|
||||
throw new RuntimeException('当前更新器未列入兼容表,请下载新版 update.php。');
|
||||
}
|
||||
$from = self::parseRange($rule->from ?? null);
|
||||
$to = self::parseRange($rule->to ?? null);
|
||||
$releases = self::releases();
|
||||
$latest = array_key_first($releases);
|
||||
$latestVersion = $latest === null ? null : substr($latest, 1);
|
||||
if (!self::inRange($current, $from, $latestVersion)) {
|
||||
throw new RuntimeException("当前站点 v$current 超出此更新器的起始版本范围 {$rule->from}。");
|
||||
}
|
||||
$eligible = array_filter($releases, static function (string $tag) use ($current, $to, $latestVersion): bool {
|
||||
$version = substr($tag, 1);
|
||||
|
||||
return version_compare($version, $current, '>') && self::inRange($version, $to, $latestVersion);
|
||||
}, ARRAY_FILTER_USE_KEY);
|
||||
printf("更新器 v%s,当前站点 v%s\n兼容起始版本 %s,目标范围 %s\n",
|
||||
self::UPDATESCRIPT_VERSION, $current, $rule->from, $rule->to);
|
||||
|
||||
if ($target === 'check') {
|
||||
if ($latest !== null) {
|
||||
printf("上游最新正式发布 %s\n", $latest);
|
||||
}
|
||||
echo $eligible === [] ? "暂无可升级的正式发布版本。\n"
|
||||
: '可升级至 ' . implode('、', array_keys($eligible)) . PHP_EOL;
|
||||
return;
|
||||
}
|
||||
if ($target === null) {
|
||||
$target = self::chooseRelease($eligible);
|
||||
if ($target === null) {
|
||||
return;
|
||||
}
|
||||
} elseif ($target === 'v' . $current) {
|
||||
printf("当前已安装 %s。\n", $target);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isset($eligible[$target])) {
|
||||
throw new RuntimeException("无法从 v$current 升级到 {$target}。可选版本为 "
|
||||
. ($eligible === [] ? '无。' : implode('、', array_keys($eligible)) . '。'));
|
||||
}
|
||||
$this->update($current, $target, $backup);
|
||||
}
|
||||
|
||||
private static function parseRange(mixed $value): array
|
||||
{
|
||||
if (!is_string($value) || !preg_match('/^v(\d+\.\d+\.\d+)-(?:v(\d+\.\d+\.\d+)|latest)$/D', $value, $parts)
|
||||
|| (isset($parts[2]) && version_compare($parts[1], $parts[2], '>'))) {
|
||||
throw new RuntimeException('更新器兼容表中的版本范围无效。');
|
||||
}
|
||||
|
||||
return [$parts[1], $parts[2] ?? null];
|
||||
}
|
||||
|
||||
private static function inRange(string $version, array $range, ?string $latest): bool
|
||||
{
|
||||
[$minimum, $maximum] = $range;
|
||||
$maximum ??= $latest;
|
||||
|
||||
return version_compare($version, $minimum, '>=') && ($maximum === null || version_compare($version, $maximum, '<='));
|
||||
}
|
||||
|
||||
private static function releases(): array
|
||||
{
|
||||
$result = [];
|
||||
$deadline = hrtime(true) + 10_000_000_000;
|
||||
for ($page = 1; ; $page++) {
|
||||
$timeout = (int) (($deadline - hrtime(true)) / 1_000_000);
|
||||
if ($timeout <= 0) {
|
||||
throw new RuntimeException('查询 LaySite 发布列表超时。');
|
||||
}
|
||||
$entries = self::remoteJson(self::RELEASES_PATH . "?limit=50&page=$page", 1024 * 1024, $timeout);
|
||||
if (!is_array($entries)) {
|
||||
throw new RuntimeException('LaySite 发布列表格式无效。');
|
||||
}
|
||||
foreach ($entries as $entry) {
|
||||
if (!is_string($entry->tag_name ?? null) || !is_bool($entry->draft ?? null) || !is_bool($entry->prerelease ?? null)) {
|
||||
throw new RuntimeException('LaySite 发布列表格式无效。');
|
||||
}
|
||||
if (!$entry->draft && !$entry->prerelease && preg_match(self::TAG, $entry->tag_name)) {
|
||||
$result[$entry->tag_name] = $entry;
|
||||
}
|
||||
}
|
||||
if (count($entries) < 50) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
uksort($result, static fn (string $a, string $b): int => version_compare(substr($b, 1), substr($a, 1)));
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function remoteJson(string $path, int $limit, int $timeout): mixed
|
||||
{
|
||||
$stream = fopen('php://temp', 'w+b');
|
||||
if ($stream === false) {
|
||||
throw new RuntimeException('无法创建更新查询缓冲区。');
|
||||
}
|
||||
try {
|
||||
self::download($path, $stream, $limit, $timeout);
|
||||
rewind($stream);
|
||||
|
||||
return json_decode((string) stream_get_contents($stream), flags: JSON_THROW_ON_ERROR);
|
||||
} finally {
|
||||
fclose($stream);
|
||||
}
|
||||
}
|
||||
|
||||
private static function chooseRelease(array $releases): ?string
|
||||
{
|
||||
if ($releases === []) {
|
||||
echo "暂无可升级的正式发布版本。\n";
|
||||
return null;
|
||||
}
|
||||
$tags = array_keys($releases);
|
||||
foreach ($tags as $index => $tag) {
|
||||
$release = $releases[$tag];
|
||||
$title = self::terminalText($release->name ?? '');
|
||||
$details = self::terminalText($release->body ?? '');
|
||||
printf("\n%d. %s%s\n", $index + 1, $tag, $title === '' || $title === $tag ? '' : ' · ' . str_replace("\n", ' ', $title));
|
||||
echo ' ' . str_replace("\n", "\n ", $details === '' ? '暂无发布说明。' : $details) . PHP_EOL;
|
||||
}
|
||||
|
||||
while (true) {
|
||||
echo "\n请选择版本编号或输入标签,回车取消\n> ";
|
||||
$selection = trim((string) fgets(STDIN));
|
||||
if ($selection === '' || strtolower($selection) === 'q') {
|
||||
return null;
|
||||
}
|
||||
if (isset($releases[$selection])) {
|
||||
return $selection;
|
||||
}
|
||||
if (ctype_digit($selection) && isset($tags[(int) $selection - 1])) {
|
||||
return $tags[(int) $selection - 1];
|
||||
}
|
||||
echo "请输入列表中的编号或版本。\n";
|
||||
}
|
||||
}
|
||||
|
||||
private static function terminalText(mixed $value): string
|
||||
{
|
||||
if (!is_string($value)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return trim(preg_replace('/[^\P{C}\n\t]/u', '', str_replace(["\r\n", "\r"], "\n", $value)) ?? '');
|
||||
}
|
||||
|
||||
private function update(string $current, string $target, ?string $backup): void
|
||||
{
|
||||
$runtime = $this->root . '/runtime';
|
||||
self::makeDirectory($runtime);
|
||||
$lock = fopen($runtime . '/release-update.lock', 'c');
|
||||
if ($lock === false || !flock($lock, LOCK_EX | LOCK_NB)) {
|
||||
throw new RuntimeException('无法取得 LaySite 更新锁。');
|
||||
}
|
||||
$pending = $runtime . '/release-update-pending';
|
||||
$work = $this->root . '/.laysite-update-' . bin2hex(random_bytes(8));
|
||||
try {
|
||||
if (file_exists($pending) || is_link($pending)) {
|
||||
throw new RuntimeException('上次更新尚未完成。请保留该次更新的备份,并检查 ' . trim((string) file_get_contents($pending)));
|
||||
}
|
||||
if ($this->version() !== $current) {
|
||||
throw new RuntimeException('站点版本已经变更,请重新选择更新目标。');
|
||||
}
|
||||
$backup = $this->backupPath($backup, $current, $target);
|
||||
|
||||
if (!mkdir($work, 0700)) {
|
||||
throw new RuntimeException('无法建立更新暂存目录。');
|
||||
}
|
||||
$base = $this->archive(self::LEGACY_BASES[$current] ?? ('v' . $current), $current, $work . '/base.zip');
|
||||
// Accept the VERSION file already identified above, including the old release numbering.
|
||||
$base['VERSION']['hash'] = hash_file('sha256', $this->root . '/VERSION');
|
||||
$release = $this->archive($target, substr($target, 1), $work . '/release.zip');
|
||||
$plan = $this->plan($base, $release, $backup);
|
||||
$php = getenv('LAYSITE_PHP') ?: PHP_BINARY;
|
||||
self::run([$php, 'bin/backup.php', 'export', $backup], $this->root);
|
||||
$vendor = $this->stageDependencies($work, $plan, $release);
|
||||
if ($plan !== $this->plan($base, $release, $backup)) {
|
||||
throw new RuntimeException('准备更新期间,站点文件发生了变化。');
|
||||
}
|
||||
$this->apply($work, $pending, $plan, $release, $vendor, $php);
|
||||
printf("已更新至 %s,可使用原站点配置启动 Webman。\n", $target);
|
||||
} finally {
|
||||
if (is_dir($work) && !is_file($pending)) {
|
||||
self::removeDirectory($work);
|
||||
}
|
||||
fclose($lock);
|
||||
}
|
||||
}
|
||||
|
||||
private function backupPath(?string $path, string $current, string $target): string
|
||||
{
|
||||
if ($path === null) {
|
||||
$directory = $this->root . '/storage/backups';
|
||||
self::makeDirectory($directory);
|
||||
$path = sprintf('%s/laysite-v%s-%s-%s-%s.tar', $directory, $current, $target, gmdate('Ymd-His'), bin2hex(random_bytes(4)));
|
||||
} elseif (!str_starts_with($path, '/')) {
|
||||
$path = $this->root . '/' . $path;
|
||||
}
|
||||
$directory = realpath(dirname($path));
|
||||
if ($directory === false || !str_ends_with($path, '.tar') || file_exists($path) || is_link($path)) {
|
||||
throw new RuntimeException('请指定已存在的目录和一个尚未使用的 .tar 备份文件名。');
|
||||
}
|
||||
$path = $directory . '/' . basename($path);
|
||||
printf("站点备份将写入 %s\n", $path);
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
private function version(): string
|
||||
{
|
||||
$version = trim((string) @file_get_contents($this->root . '/VERSION'));
|
||||
if (!preg_match('/^\d+\.\d+\.\d+$/D', $version)) {
|
||||
throw new RuntimeException('请从已安装 LaySite 的目录运行更新器。');
|
||||
}
|
||||
|
||||
if ($version === '1.4.0') {
|
||||
foreach (self::LEGACY_VERSIONS as $tag => $files) {
|
||||
foreach ($files as $path => $hash) {
|
||||
if (@hash_file('sha256', $this->root . '/' . $path) === $hash) {
|
||||
return $tag;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $version;
|
||||
}
|
||||
|
||||
private static function download(string $path, $stream, int $limit, int $timeout): void
|
||||
{
|
||||
$curl = curl_init(self::HOST . $path);
|
||||
$bytes = 0;
|
||||
curl_setopt_array($curl, [
|
||||
CURLOPT_USERAGENT => 'LaySite release updater',
|
||||
CURLOPT_CONNECTTIMEOUT_MS => min(3500, $timeout),
|
||||
CURLOPT_TIMEOUT_MS => $timeout,
|
||||
CURLOPT_FOLLOWLOCATION => false,
|
||||
CURLOPT_WRITEFUNCTION => static function (CurlHandle $curl, string $chunk) use ($stream, $limit, &$bytes): int {
|
||||
$bytes += strlen($chunk);
|
||||
|
||||
return $bytes > $limit ? 0 : (int) fwrite($stream, $chunk);
|
||||
},
|
||||
]);
|
||||
if (curl_exec($curl) === false) {
|
||||
throw new RuntimeException('下载 LaySite 发布文件失败。' . ($bytes > $limit ? '文件超过大小限制。' : curl_error($curl)));
|
||||
}
|
||||
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
|
||||
if ($status !== 200) {
|
||||
throw new RuntimeException("无法读取 LaySite 发布文件 {$path}(HTTP $status)。");
|
||||
}
|
||||
}
|
||||
|
||||
private function archive(string $ref, string $version, string $path): array
|
||||
{
|
||||
$stream = fopen($path, 'xb');
|
||||
if ($stream === false) {
|
||||
throw new RuntimeException('无法写入发布 ZIP。');
|
||||
}
|
||||
try {
|
||||
self::download(self::PROJECT . "/archive/$ref.zip", $stream, self::MAX_ARCHIVE_BYTES, 60_000);
|
||||
} finally {
|
||||
fclose($stream);
|
||||
}
|
||||
$archive = new PharData($path);
|
||||
$files = [];
|
||||
$size = 0;
|
||||
$prefix = 'phar://' . $path . '/laysite/';
|
||||
foreach (new RecursiveIteratorIterator($archive) as $entry) {
|
||||
$uri = $entry->getPathname();
|
||||
if (!str_starts_with($uri, $prefix)) {
|
||||
throw new RuntimeException('发布 ZIP 的目录结构无效。');
|
||||
}
|
||||
$name = substr($uri, strlen($prefix));
|
||||
if ($entry->isLink() || !$entry->isFile() || str_contains($name, '\\')
|
||||
|| preg_match('~(?:^|/)\.{0,2}(?:/|$)|[\x00-\x1f\x7f]~', $name)) {
|
||||
throw new RuntimeException('发布 ZIP 包含无效的文件路径。');
|
||||
}
|
||||
$size += $entry->getSize();
|
||||
if ($size > self::MAX_EXPANDED_BYTES) {
|
||||
throw new RuntimeException('发布 ZIP 解压后的大小超过限制。');
|
||||
}
|
||||
if (!preg_match(self::MANAGED, $name)) {
|
||||
continue;
|
||||
}
|
||||
$hash = hash_file('sha256', $uri);
|
||||
if ($hash === false || isset($files[$name])) {
|
||||
throw new RuntimeException('发布 ZIP 文件损坏。');
|
||||
}
|
||||
$files[$name] = ['uri' => $uri, 'hash' => $hash, 'mode' => $entry->getPerms() & 0777];
|
||||
}
|
||||
foreach (['VERSION', 'start.php', 'bin/install.php', 'composer.json', 'composer.lock', 'resources/schema.sql'] as $required) {
|
||||
if (!isset($files[$required])) {
|
||||
throw new RuntimeException('发布 ZIP 缺少 ' . $required);
|
||||
}
|
||||
}
|
||||
$embedded = trim((string) file_get_contents($files['VERSION']['uri']));
|
||||
if ($embedded !== $version) {
|
||||
if ($embedded !== '1.4.0' || !isset(self::LEGACY_VERSIONS[$version])) {
|
||||
throw new RuntimeException('发布 ZIP 的 VERSION 与所选版本不一致。');
|
||||
}
|
||||
$canonical = $path . '.version';
|
||||
$contents = $version . "\n";
|
||||
if (file_put_contents($canonical, $contents) !== strlen($contents)) {
|
||||
throw new RuntimeException('无法暂存发布版本号。');
|
||||
}
|
||||
$files['VERSION'] = ['uri' => $canonical, 'hash' => hash('sha256', $contents), 'mode' => 0644];
|
||||
}
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
private function plan(array $base, array $release, string $backup): array
|
||||
{
|
||||
clearstatcache();
|
||||
require_once $this->root . '/vendor/autoload.php';
|
||||
$database = App\Content\Database::path();
|
||||
$media = App\Content\Media::directory();
|
||||
$protected = array_unique([
|
||||
$database, realpath($database) ?: $database, $media, realpath($media) ?: $media, $backup,
|
||||
]);
|
||||
$plan = [];
|
||||
$conflicts = [];
|
||||
foreach (array_keys($base + $release) as $name) {
|
||||
$old = $base[$name]['hash'] ?? null;
|
||||
$next = $release[$name]['hash'] ?? null;
|
||||
if ($old === $next) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$path = $this->managedPath($name);
|
||||
foreach ($protected as $reserved) {
|
||||
if ($path === $reserved || str_starts_with($path, rtrim($reserved, '/') . '/')
|
||||
|| str_starts_with($reserved, $path . '/') || in_array($path, [$database . '.key', $database . '-wal', $database . '-shm'], true)) {
|
||||
throw new RuntimeException('更新路径与站点数据重叠。');
|
||||
}
|
||||
}
|
||||
$local = is_file($path) ? hash_file('sha256', $path) : null;
|
||||
if ($local === $next) {
|
||||
continue;
|
||||
}
|
||||
if ($local !== $old) {
|
||||
$conflicts[] = $name;
|
||||
continue;
|
||||
}
|
||||
$plan[] = $name;
|
||||
} catch (RuntimeException) {
|
||||
$conflicts[] = $name;
|
||||
}
|
||||
}
|
||||
if ($conflicts !== []) {
|
||||
sort($conflicts);
|
||||
throw new RuntimeException("以下路径与站点定制或数据冲突,尚未替换任何文件:\n" . implode("\n", $conflicts));
|
||||
}
|
||||
if (array_intersect(['composer.json', 'composer.lock'], $plan)) {
|
||||
$vendor = $this->root . '/vendor';
|
||||
foreach ($protected as $reserved) {
|
||||
if ($reserved === $vendor || str_starts_with($reserved, $vendor . '/')) {
|
||||
throw new RuntimeException('站点数据或备份路径位于 vendor 目录,请先调整该路径。');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $plan;
|
||||
}
|
||||
|
||||
private function managedPath(string $name): string
|
||||
{
|
||||
$path = $this->root;
|
||||
$parts = explode('/', $name);
|
||||
$leaf = array_pop($parts);
|
||||
foreach ($parts as $part) {
|
||||
$path .= '/' . $part;
|
||||
if (is_link($path) || (file_exists($path) && !is_dir($path))) {
|
||||
throw new RuntimeException('更新路径不可写:' . $name);
|
||||
}
|
||||
}
|
||||
$path .= '/' . $leaf;
|
||||
if (is_link($path) || (file_exists($path) && !is_file($path))) {
|
||||
throw new RuntimeException('更新路径不可写:' . $name);
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
private function stageDependencies(string $work, array $plan, array $release): ?string
|
||||
{
|
||||
if (!array_intersect(['composer.json', 'composer.lock'], $plan)) {
|
||||
return null;
|
||||
}
|
||||
$dependencies = $work . '/dependencies';
|
||||
self::makeDirectory($dependencies);
|
||||
foreach (['composer.json', 'composer.lock'] as $name) {
|
||||
$source = in_array($name, $plan, true) ? $release[$name]['uri'] : $this->root . '/' . $name;
|
||||
if (!copy($source, $dependencies . '/' . $name)) {
|
||||
throw new RuntimeException('无法准备 Composer 依赖。');
|
||||
}
|
||||
}
|
||||
$vendor = $dependencies . '/vendor';
|
||||
self::run([
|
||||
getenv('LAYSITE_COMPOSER') ?: 'composer', 'install', '--no-dev', '--prefer-dist',
|
||||
'--no-interaction', '--no-scripts', '--no-plugins',
|
||||
], $dependencies, array_replace(getenv(), ['COMPOSER' => 'composer.json', 'COMPOSER_VENDOR_DIR' => $vendor]));
|
||||
if (!is_file($vendor . '/autoload.php')) {
|
||||
throw new RuntimeException('Composer 没有在暂存目录生成依赖。');
|
||||
}
|
||||
|
||||
return $vendor;
|
||||
}
|
||||
|
||||
private function apply(string $work, string $pending, array $plan, array $release, ?string $vendor, string $php): void
|
||||
{
|
||||
$staged = [];
|
||||
foreach ($plan as $name) {
|
||||
$staged[$name] = null;
|
||||
if (isset($release[$name])) {
|
||||
$file = $work . '/files/' . $name;
|
||||
self::makeDirectory(dirname($file));
|
||||
$mode = $release[$name]['mode'] & 0755;
|
||||
if ($name === 'bin/update.sh') {
|
||||
$mode |= 0100;
|
||||
}
|
||||
if (!copy($release[$name]['uri'], $file) || !chmod($file, $mode ?: 0644)) {
|
||||
throw new RuntimeException('无法暂存文件 ' . $name);
|
||||
}
|
||||
$staged[$name] = $file;
|
||||
}
|
||||
}
|
||||
if ($vendor !== null) {
|
||||
if (is_link($this->root . '/vendor') || !is_dir($this->root . '/vendor')) {
|
||||
throw new RuntimeException('站点的 vendor 目录需要手动更新。');
|
||||
}
|
||||
$staged['vendor'] = $vendor;
|
||||
}
|
||||
$marker = fopen($pending, 'x');
|
||||
if ($marker === false) {
|
||||
throw new RuntimeException('无法写入更新记录。');
|
||||
}
|
||||
$record = $work . PHP_EOL;
|
||||
$written = fwrite($marker, $record);
|
||||
fclose($marker);
|
||||
if ($written !== strlen($record)) {
|
||||
unlink($pending);
|
||||
throw new RuntimeException('无法写入完整的更新记录。');
|
||||
}
|
||||
$applied = [];
|
||||
try {
|
||||
foreach ($staged as $name => $source) {
|
||||
$destination = $this->root . '/' . $name;
|
||||
$previous = $work . '/previous/' . $name;
|
||||
if (file_exists($destination)) {
|
||||
self::makeDirectory(dirname($previous));
|
||||
self::move($destination, $previous);
|
||||
}
|
||||
$applied[] = $name;
|
||||
if ($source !== null) {
|
||||
self::makeDirectory(dirname($destination));
|
||||
self::move($source, $destination);
|
||||
}
|
||||
}
|
||||
self::run([$php, 'bin/install.php'], $this->root);
|
||||
} catch (Throwable $error) {
|
||||
try {
|
||||
foreach (array_reverse($applied) as $name) {
|
||||
$path = $this->root . '/' . $name;
|
||||
if (file_exists($path)) {
|
||||
$discard = $work . '/discard/' . $name;
|
||||
self::makeDirectory(dirname($discard));
|
||||
self::move($path, $discard);
|
||||
}
|
||||
$previous = $work . '/previous/' . $name;
|
||||
if (file_exists($previous)) {
|
||||
self::move($previous, $path);
|
||||
}
|
||||
}
|
||||
unlink($pending);
|
||||
} catch (Throwable $rollback) {
|
||||
throw new RuntimeException('更新回退未完成。原文件保存在 ' . $work . '。' . $rollback->getMessage(), previous: $error);
|
||||
}
|
||||
throw new RuntimeException('更新失败,原程序文件已恢复。' . $error->getMessage(), previous: $error);
|
||||
}
|
||||
unlink($pending);
|
||||
}
|
||||
|
||||
private static function move(string $from, string $to): void
|
||||
{
|
||||
if (!rename($from, $to)) {
|
||||
throw new RuntimeException('无法移动 ' . $from . ' 到 ' . $to);
|
||||
}
|
||||
}
|
||||
|
||||
private static function run(array $command, string $directory, ?array $environment = null): void
|
||||
{
|
||||
$process = proc_open($command, [STDIN, STDOUT, STDERR], $pipes, $directory, $environment);
|
||||
if (!is_resource($process) || proc_close($process) !== 0) {
|
||||
throw new RuntimeException('命令执行失败:' . implode(' ', array_slice($command, 0, 2)));
|
||||
}
|
||||
}
|
||||
|
||||
private static function makeDirectory(string $path): void
|
||||
{
|
||||
if (!is_dir($path) && !mkdir($path, 0755, true) && !is_dir($path)) {
|
||||
throw new RuntimeException('无法建立目录 ' . $path);
|
||||
}
|
||||
}
|
||||
|
||||
private static function removeDirectory(string $path): void
|
||||
{
|
||||
$entries = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
|
||||
RecursiveIteratorIterator::CHILD_FIRST);
|
||||
foreach ($entries as $entry) {
|
||||
if ($entry->isDir() && !$entry->isLink()) {
|
||||
rmdir($entry->getPathname());
|
||||
} else {
|
||||
unlink($entry->getPathname());
|
||||
}
|
||||
}
|
||||
rmdir($path);
|
||||
}
|
||||
}
|
||||
|
||||
$target = $argv[1] ?? null;
|
||||
$backup = $argv[2] ?? null;
|
||||
if ($argc > 3 || ($target === 'check' && $backup !== null)
|
||||
|| ($target !== null && $target !== 'check' && !preg_match('/^v\d+\.\d+\.\d+$/D', $target))) {
|
||||
fwrite(STDERR, "用法:php bin/update.php [check | vX.Y.Z [备份路径.tar]]\n");
|
||||
exit(2);
|
||||
}
|
||||
|
||||
umask(0027);
|
||||
try {
|
||||
(new LaySiteUpdater(getcwd()))->execute($target, $backup);
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, $error->getMessage() . PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
php_bin=${LAYSITE_PHP:-php}
|
||||
composer_bin=${LAYSITE_COMPOSER:-composer}
|
||||
target=${1:-check}
|
||||
|
||||
if [ "$target" = check ]; then
|
||||
git fetch origin --tags
|
||||
git describe --tags --always
|
||||
git tag --list 'v[0-9]*' --sort=-version:refname | awk '/^v[0-9]+\.[0-9]+\.[0-9]+$/'
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! printf '%s\n' "$target" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$' || [ "$#" -ne 2 ]; then
|
||||
printf '%s\n' 'Usage: bin/update.sh check | vX.Y.Z /path/snapshot.tar' >&2
|
||||
exit 2
|
||||
fi
|
||||
if [ -n "$(git status --porcelain)" ]; then
|
||||
printf '%s\n' 'Commit or set aside local source changes before updating.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git fetch origin --tags
|
||||
current=$(git rev-parse HEAD)
|
||||
next=$(git rev-parse --verify "refs/tags/$target^{commit}")
|
||||
git merge-base --is-ancestor "$current" "$next"
|
||||
"$php_bin" bin/backup.php export "$2"
|
||||
|
||||
if git switch --detach "$next" &&
|
||||
"$composer_bin" install --no-dev --prefer-dist --no-interaction --no-scripts &&
|
||||
"$php_bin" bin/install.php
|
||||
then
|
||||
printf 'Updated to %s. Start Webman with the original site environment.\n' "$target"
|
||||
else
|
||||
git switch --detach "$current"
|
||||
"$composer_bin" install --no-dev --prefer-dist --no-interaction --no-scripts
|
||||
printf 'Update failed. The prior source version is checked out and the backup is at %s.\n' "$2" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -112,6 +112,7 @@
|
||||
.canvas-format-tools [aria-pressed=true] { background: var(--accent-light); color: var(--accent-deep); }
|
||||
.canvas-spacing-fields { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .5rem; }
|
||||
.canvas-spacing-fields input { padding-inline: .4rem; }
|
||||
.canvas-spacing-preset { grid-column: 1 / -1; grid-template-columns: max-content minmax(0, 15rem); align-items: center; }
|
||||
.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); }
|
||||
@@ -416,6 +417,17 @@
|
||||
|
||||
.canvas-source { width: min(56rem, calc(100% - 2rem)); }
|
||||
.canvas-source textarea { font: .9rem / 1.55 var(--mono); tab-size: 4; }
|
||||
.canvas-source .CodeMirror {
|
||||
height: clamp(12rem, 50vh, 32rem);
|
||||
margin-top: .4rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: .5rem;
|
||||
font: .9rem / 1.55 var(--mono);
|
||||
}
|
||||
.canvas-source .CodeMirror-focused { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||
.picker-actions { justify-content: flex-start; margin-top: .85rem; }
|
||||
.admin-action-dialog { max-width: min(30rem, calc(100% - 2rem)); }
|
||||
.admin-action-dialog h2, #media-picker h2 { margin: 0; font-size: 1.45rem; letter-spacing: -.018em; }
|
||||
.canvas-image-display { display: flex; align-items: center; gap: .35rem; font-size: .85rem; }
|
||||
.canvas-image-display select, .canvas-format-tools input[type=color] {
|
||||
background: var(--white); border: 1px solid var(--line); border-radius: .35rem;
|
||||
|
||||
+31
-2
@@ -1,6 +1,32 @@
|
||||
'use strict';
|
||||
|
||||
jQuery(function ($) {
|
||||
const $actionDialog = $('#admin-action-dialog');
|
||||
const $actionField = $actionDialog.find('[data-action-field]');
|
||||
const $actionValue = $actionField.find('[data-action-value]');
|
||||
|
||||
window.laySiteAction = function ({title, message = '', label, value = '', readOnly = false, accept = '确定'}) {
|
||||
const dialog = $actionDialog.get(0);
|
||||
if (!dialog || dialog.open) return Promise.resolve(null);
|
||||
const hasInput = Boolean(label);
|
||||
$actionDialog.find('[data-action-title]').text(title);
|
||||
$actionDialog.find('[data-action-message]').text(message).prop('hidden', !message);
|
||||
$actionDialog.find('[data-action-label]').text(label || '');
|
||||
$actionField.prop('hidden', !hasInput);
|
||||
$actionValue.val(value).prop({disabled: !hasInput, readOnly});
|
||||
$actionDialog.find('[data-action-accept]').text(accept);
|
||||
return new Promise((resolve) => {
|
||||
dialog.returnValue = '';
|
||||
$actionDialog.one('close', () => {
|
||||
resolve(dialog.returnValue === 'accept' ? (hasInput ? $actionValue.val() : true) : null);
|
||||
});
|
||||
dialog.showModal();
|
||||
if (hasInput) $actionValue.trigger('focus').trigger('select');
|
||||
else $actionDialog.find('[data-action-cancel]').trigger('focus');
|
||||
});
|
||||
};
|
||||
$actionDialog.on('click', '[data-action-cancel]', () => $actionDialog.get(0).close());
|
||||
|
||||
$('[data-page-layout-editor]').each(function () {
|
||||
const {pageLayoutEditor: kind, defaultId} = this.dataset;
|
||||
const $link = $(this);
|
||||
@@ -114,12 +140,15 @@ jQuery(function ($) {
|
||||
if (event.target.form?.method.toLowerCase() === 'post') clearSavedStatus();
|
||||
}, true);
|
||||
|
||||
$('form[method="post"]').on('submit', function (event) {
|
||||
$('form[method="post"]').on('submit', async function (event) {
|
||||
event.preventDefault();
|
||||
const $form = $(this);
|
||||
if ($form.attr('aria-busy') === 'true') return;
|
||||
const submitter = event.originalEvent?.submitter;
|
||||
if (submitter?.dataset.confirm && !window.confirm(submitter.dataset.confirm)) return;
|
||||
if (submitter?.dataset.confirm && !await window.laySiteAction({
|
||||
title: '确认操作', message: submitter.dataset.confirm,
|
||||
accept: submitter.getAttribute('aria-label') || submitter.textContent.trim() || '确定',
|
||||
})) return;
|
||||
clearSavedStatus();
|
||||
const action = $form.attr('action');
|
||||
const isLogin = action === '/admin/login';
|
||||
|
||||
@@ -38,8 +38,9 @@ jQuery(function ($) {
|
||||
$source.prop('hidden', true);
|
||||
$field.find('[data-article-editor-label]').removeAttr('for');
|
||||
$field.find('[data-insert-article-image]').prop('hidden', false).on('click', () => {
|
||||
$('#media-picker').triggerHandler('studio:pick', ['image/', (file) => {
|
||||
const alt = window.prompt('图片替代文本(装饰图可留空)', file.label);
|
||||
const $picker = $('#media-picker');
|
||||
$picker.triggerHandler('studio:pick', ['image/', async (file) => {
|
||||
const alt = await $picker.triggerHandler('studio:image-alt', [file]);
|
||||
if (alt === null) return;
|
||||
$status.empty();
|
||||
editor.focus();
|
||||
|
||||
@@ -415,6 +415,15 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
|
||||
|
||||
:where(img, video, audio, .hero-visual)[class*="studio-media-"] { max-width: 100%; }
|
||||
:is(.rich, .hero-inner, .editor-preview, .studio-layout-block) [class*="studio-media-"] { width: var(--studio-media-width, auto); }
|
||||
.studio-media-1 { --studio-media-width: 1%; }
|
||||
.studio-media-2 { --studio-media-width: 2%; }
|
||||
.studio-media-3 { --studio-media-width: 3%; }
|
||||
.studio-media-4 { --studio-media-width: 4%; }
|
||||
.studio-media-5 { --studio-media-width: 5%; }
|
||||
.studio-media-6 { --studio-media-width: 6%; }
|
||||
.studio-media-7 { --studio-media-width: 7%; }
|
||||
.studio-media-8 { --studio-media-width: 8%; }
|
||||
.studio-media-9 { --studio-media-width: 9%; }
|
||||
.studio-media-10 { --studio-media-width: 10%; }
|
||||
.studio-media-11 { --studio-media-width: 11%; }
|
||||
.studio-media-12 { --studio-media-width: 12%; }
|
||||
|
||||
+110
-41
@@ -8,16 +8,25 @@ jQuery(function ($) {
|
||||
let files = [];
|
||||
let mediaType = '';
|
||||
let pickerRequest;
|
||||
const $pickerRefresh = $picker.find('[data-refresh-picker]');
|
||||
const mediaUpdates = 'BroadcastChannel' in window ? new BroadcastChannel('laysite-media') : null;
|
||||
|
||||
function imageAlt(file) {
|
||||
return window.laySiteAction({
|
||||
title: '插入图片', label: '替代文本(装饰图可留空)', value: file.label, accept: '插入',
|
||||
});
|
||||
}
|
||||
$picker.on('studio:image-alt', (_event, file) => imageAlt(file));
|
||||
|
||||
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) {
|
||||
async function mediaMarkup(file) {
|
||||
let $node;
|
||||
if (file.mime.startsWith('image/')) {
|
||||
const alt = window.prompt('图片替代文本(装饰图可留空)', file.label);
|
||||
const alt = await imageAlt(file);
|
||||
if (alt === null) return '';
|
||||
$node = $('<img>', {src: file.url, alt, loading: 'lazy'});
|
||||
} else if (file.mime.startsWith('video/') || file.mime.startsWith('audio/')) {
|
||||
@@ -49,19 +58,32 @@ jQuery(function ($) {
|
||||
if (!$picker.length || typeof $picker.get(0).showModal !== 'function') return;
|
||||
pick = callback;
|
||||
mediaType = type;
|
||||
files = [];
|
||||
$picker.find('[data-media-query]').val('');
|
||||
$pickerItems.empty();
|
||||
$pickerStatus.text('加载资源…');
|
||||
$picker.get(0).showModal();
|
||||
refreshPicker();
|
||||
}
|
||||
|
||||
function refreshPicker() {
|
||||
if (!$picker.get(0)?.open) return;
|
||||
pickerRequest?.abort();
|
||||
pickerRequest = $.getJSON('/admin/media/options').done(function (response) {
|
||||
$pickerStatus.text('正在刷新资源…');
|
||||
$pickerRefresh.prop('disabled', true);
|
||||
pickerRequest = $.ajax({url: '/admin/media/options', dataType: 'json', cache: false}).done((response) => {
|
||||
files = response.files;
|
||||
renderPicker();
|
||||
}).fail(function (_request, status) {
|
||||
if (status !== 'abort') $pickerStatus.text('媒体库暂时无法打开。');
|
||||
});
|
||||
}).fail((_request, status) => {
|
||||
if (status !== 'abort') $pickerStatus.text('媒体库暂时无法刷新,请重试。');
|
||||
}).always(() => $pickerRefresh.prop('disabled', false));
|
||||
}
|
||||
|
||||
$picker.on('click', '[data-refresh-picker]', refreshPicker);
|
||||
$(window).on('focus', refreshPicker);
|
||||
$(document).on('visibilitychange', () => { if (!document.hidden) refreshPicker(); });
|
||||
mediaUpdates?.addEventListener('message', (event) => { if (event.data === 'changed') refreshPicker(); });
|
||||
$('form[action^="/admin/media"]').on('studio:saved', () => mediaUpdates?.postMessage('changed'));
|
||||
|
||||
$picker.on('studio:pick', (_event, type, callback) => openPicker(type, callback));
|
||||
$picker.on('input', '[data-media-query]', renderPicker);
|
||||
$picker.on('click', '[data-close-picker]', () => $picker.get(0).close());
|
||||
@@ -78,14 +100,15 @@ jQuery(function ($) {
|
||||
openPicker($button.data('asset-type') || '', (file) => $input.val(file.url).trigger('input').trigger('focus'));
|
||||
});
|
||||
|
||||
$('[data-copy-asset]').on('click', function () {
|
||||
$('[data-copy-asset]').on('click', async function () {
|
||||
const $button = $(this);
|
||||
const url = $button.data('copy-asset');
|
||||
if (!navigator.clipboard) {
|
||||
window.prompt('复制资源路径', url);
|
||||
return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
$button.text('已复制');
|
||||
} catch {
|
||||
window.laySiteAction({title: '复制资源路径', label: '资源路径', value: url, readOnly: true, accept: '完成'});
|
||||
}
|
||||
navigator.clipboard.writeText(url).then(() => $button.text('已复制')).catch(() => window.prompt('复制资源路径', url));
|
||||
});
|
||||
|
||||
$('[data-media-library]').each(function () {
|
||||
@@ -311,6 +334,8 @@ jQuery(function ($) {
|
||||
const bodyElements = 'a, article, blockquote, button, details, div, dl, dt, dd, figure, figcaption, footer, h1, h2, h3, h4, h5, h6, header, hr, li, nav, ol, p, pre, progress, section, summary, table, ul, td, th, caption, small';
|
||||
const mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video';
|
||||
const $handle = $studio.find('[data-media-handle]');
|
||||
const minMediaWidth = Number($handle.attr('aria-valuemin'));
|
||||
const pathGroups = '[data-studio-navigation], [data-studio-breadcrumbs]';
|
||||
const $mediaSize = $sizing.find('[data-media-size]');
|
||||
const mediaWidthClass = /^studio-media-\d+$/;
|
||||
|
||||
@@ -395,6 +420,7 @@ jQuery(function ($) {
|
||||
let saveComplete = false;
|
||||
let syncPageFromInputs;
|
||||
let spacingTarget;
|
||||
let sourceEditor;
|
||||
|
||||
function classesOf(node, textOnly = false) {
|
||||
const result = {};
|
||||
@@ -450,15 +476,18 @@ jQuery(function ($) {
|
||||
}
|
||||
|
||||
function paintText(node, value, runs) {
|
||||
const display = runs?.map(([text]) => text).join('').trim() === value ? runs : [[value, '']];
|
||||
const lineBreaks = (text) => text.replace(/\r\n?/g, '\n');
|
||||
const plain = lineBreaks(value);
|
||||
const display = runs?.map(([text]) => lineBreaks(text)).join('').trim() === plain ? runs : [[plain, '']];
|
||||
node.replaceChildren();
|
||||
for (const [text, tokens] of display) {
|
||||
const parent = tokens ? doc.createElement('span') : node;
|
||||
if (tokens) {
|
||||
parent.className = tokens;
|
||||
installMarkupColors(tokens);
|
||||
node.append(parent);
|
||||
}
|
||||
text.split('\n').forEach((line, index) => {
|
||||
lineBreaks(text).split('\n').forEach((line, index) => {
|
||||
if (index) parent.append(doc.createElement('br'));
|
||||
if (line) parent.append(line);
|
||||
});
|
||||
@@ -525,7 +554,10 @@ jQuery(function ($) {
|
||||
|
||||
function setPageStyle(node, style) {
|
||||
node.classList.remove(...Object.values(classesOf(node)));
|
||||
if (style?.classes) node.classList.add(...style.classes.split(' '));
|
||||
if (style?.classes) {
|
||||
installMarkupColors(style.classes);
|
||||
node.classList.add(...style.classes.split(' '));
|
||||
}
|
||||
}
|
||||
|
||||
function canvasOrder() {
|
||||
@@ -596,7 +628,7 @@ jQuery(function ($) {
|
||||
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', 'note', 'url', 'alt', 'poster', 'quicklinks', 'value', 'max', 'buttonStyle', 'newTab']) {
|
||||
for (const key of ['label', 'note', 'url', 'alt', 'poster', 'quicklinks', 'breadcrumbs', 'value', 'max', 'buttonStyle', 'newTab']) {
|
||||
const visible = Object.hasOwn(values, key);
|
||||
$propertyForm.find('[data-property-row="' + key + '"]').prop('hidden', !visible);
|
||||
propertyInput(key).val(visible ? values[key] : '');
|
||||
@@ -795,8 +827,14 @@ jQuery(function ($) {
|
||||
$spacingForm.find('input').each(function () {
|
||||
this.value = styles[this.name]?.slice(('studio-style-' + this.name + '-').length) || '';
|
||||
});
|
||||
$spacingForm.find('[data-spacing-preset]').val('');
|
||||
$spacing.get(0).showModal();
|
||||
});
|
||||
$spacingForm.on('change', '[data-spacing-preset]', function () {
|
||||
if (this.value !== '') $(this).closest('fieldset').find('input').val(this.value === 'template' ? '' : this.value);
|
||||
}).on('input', 'input', function () {
|
||||
$(this).closest('fieldset').find('[data-spacing-preset]').val('');
|
||||
});
|
||||
$elementTools.on('click', '[data-element-parent]', () => {
|
||||
const parent = parentElement(selectedElement);
|
||||
if (!parent) return;
|
||||
@@ -822,8 +860,8 @@ jQuery(function ($) {
|
||||
const range = savedRange?.cloneRange();
|
||||
const edit = (action, value) => editBody(body, range, action, value);
|
||||
if (command === 'media') {
|
||||
openPicker('', (file) => {
|
||||
const markup = mediaMarkup(file);
|
||||
openPicker('', async (file) => {
|
||||
const markup = await mediaMarkup(file);
|
||||
if (markup) edit('insertHTML', markup);
|
||||
});
|
||||
} else if (command === 'link') {
|
||||
@@ -1064,6 +1102,7 @@ jQuery(function ($) {
|
||||
renderLayers();
|
||||
};
|
||||
paths[type] = {read, sync, write};
|
||||
heroControls.set('remove-' + type, () => write([]));
|
||||
heroControls.set(type, () => {
|
||||
const field = crumb ? 'breadcrumbs' : 'quicklinks';
|
||||
openProperties(config.heading, {[field]: $input.val()}, (values) => {
|
||||
@@ -1287,11 +1326,14 @@ jQuery(function ($) {
|
||||
if (node) {
|
||||
const bounds = previewBounds(node);
|
||||
const x = getAlignment(node) === 'right' ? bounds.left : bounds.right;
|
||||
const y = (bounds.top + bounds.bottom) / 2;
|
||||
const visible = bounds.width > 0 && y >= 0 && y <= container.clientHeight
|
||||
&& x >= 0 && x <= container.clientWidth + 1;
|
||||
const top = Math.max(0, bounds.top);
|
||||
const bottom = Math.min(container.clientHeight, bounds.bottom);
|
||||
const visible = bounds.width > 0 && bounds.right > 0 && bounds.left < container.clientWidth && bottom > top;
|
||||
$handle.prop('hidden', !mediaDrag && !visible);
|
||||
$handle.css({left: Math.max(11, Math.min(x, container.clientWidth - 11)), top: y});
|
||||
$handle.css({
|
||||
left: Math.max(11, Math.min(x, container.clientWidth - 11)),
|
||||
top: Math.max(23, Math.min((top + bottom) / 2, container.clientHeight - 23)),
|
||||
});
|
||||
} else {
|
||||
$handle.prop('hidden', true);
|
||||
}
|
||||
@@ -1380,10 +1422,11 @@ jQuery(function ($) {
|
||||
$elementTools.find('[data-element-copy]').prop('hidden', !canCopy);
|
||||
const sectionRoot = node.hasAttribute('data-studio-section');
|
||||
const hero = node.hasAttribute('data-studio-hero') && isHeroVisible();
|
||||
const deleteLabel = hero || node.dataset.studioField === 'heading' ? '删除首屏'
|
||||
const pathGroup = node.matches(pathGroups);
|
||||
const deleteLabel = pathGroup ? (node.hasAttribute('data-studio-navigation') ? '删除本页目录' : '删除面包屑') : hero || node.dataset.studioField === 'heading' ? '删除首屏'
|
||||
: node.dataset.studioPart === 'title' || sectionRoot ? '删除区块' : '删除';
|
||||
$elementTools.find('[data-element-delete]').attr({'aria-label': deleteLabel, title: deleteLabel})
|
||||
.prop('hidden', !hero && !sectionRoot && !inBody && !selectedMedia && !node.matches(canvasFields));
|
||||
.prop('hidden', !hero && !pathGroup && !sectionRoot && !inBody && !selectedMedia && !node.matches(canvasFields));
|
||||
$elementTools.find('[data-element-properties]').prop('hidden', !hasProperties && !node.matches('[data-studio-navigation], [data-studio-breadcrumbs]'));
|
||||
$layers.find('.studio-layer-row').filter((_, row) => $(row).data('canvasNode') === node).attr('aria-current', 'true');
|
||||
if (target) showMediaWidth(currentMediaWidth(target));
|
||||
@@ -1411,7 +1454,10 @@ jQuery(function ($) {
|
||||
}
|
||||
const inBody = Boolean(node.parentElement?.closest('[data-studio-part="body"]'));
|
||||
selectElement(null);
|
||||
if (inBody) {
|
||||
if (!copy && node.matches(pathGroups)) {
|
||||
heroControls.get(node.hasAttribute('data-studio-breadcrumbs') ? 'remove-breadcrumbs' : 'remove-navigation')();
|
||||
captureHistory();
|
||||
} else if (inBody) {
|
||||
if (copy) {
|
||||
const $clone = $(node.cloneNode(true));
|
||||
$clone.find('[id]').addBack('[id]').removeAttr('id');
|
||||
@@ -1571,8 +1617,23 @@ jQuery(function ($) {
|
||||
}
|
||||
$source.find('[data-source-reset]').prop('hidden', true);
|
||||
}
|
||||
for (const part of parts.values()) part.draft = part.original;
|
||||
for (const [key, part] of parts) {
|
||||
if (key === 'body' || key === 'hero') {
|
||||
part.original = window.html_beautify?.(part.original, {indent_size: 2}) ?? part.original;
|
||||
}
|
||||
part.draft = part.original;
|
||||
}
|
||||
sourceParts = parts;
|
||||
if (!sourceEditor && window.CodeMirror) {
|
||||
sourceEditor = window.CodeMirror.fromTextArea($sourceCode.get(0), {
|
||||
mode: {name: 'xml', htmlMode: true}, lineNumbers: true, lineWrapping: true,
|
||||
indentUnit: 2, tabSize: 2, viewportMargin: 10,
|
||||
});
|
||||
sourceEditor.getInputField().setAttribute('aria-label', 'HTML 源码');
|
||||
sourceEditor.on('change', (editor) => {
|
||||
if (sourceParts) sourceParts.get($sourcePart.val()).draft = editor.getValue();
|
||||
});
|
||||
}
|
||||
$sourcePart.empty();
|
||||
for (const [key, {label}] of parts) $('<option>', {value: key, text: label}).appendTo($sourcePart);
|
||||
$sourcePart.prop('disabled', hero).triggerHandler('change');
|
||||
@@ -1581,11 +1642,18 @@ jQuery(function ($) {
|
||||
: '可编辑标题、简介和正文。区块外壳与动态文章列表由系统渲染。');
|
||||
$sourceError.prop('hidden', true);
|
||||
$source.get(0).showModal();
|
||||
$sourceCode.trigger('focus');
|
||||
if (sourceEditor) {
|
||||
sourceEditor.refresh();
|
||||
sourceEditor.focus();
|
||||
} else $sourceCode.trigger('focus');
|
||||
}
|
||||
|
||||
$sourcePart.on('change', () => {
|
||||
$sourceCode.val(sourceParts.get($sourcePart.val()).draft);
|
||||
const draft = sourceParts.get($sourcePart.val()).draft;
|
||||
if (sourceEditor) {
|
||||
sourceEditor.setValue(draft);
|
||||
sourceEditor.clearHistory();
|
||||
} else $sourceCode.val(draft);
|
||||
$sourceError.prop('hidden', true);
|
||||
});
|
||||
$sourceCode.on('input', () => { sourceParts.get($sourcePart.val()).draft = $sourceCode.val(); });
|
||||
@@ -1791,7 +1859,7 @@ jQuery(function ($) {
|
||||
layerButton('down', !canDropLayer(node, adjacentLayer(node, 1), 'after')));
|
||||
}
|
||||
if (root && (entry || node.hasAttribute('data-studio-hero'))) $actions.append(layerButton('source'));
|
||||
if (entry || layerContext(node) || node.hasAttribute('data-studio-hero')) $actions.append(layerButton('delete'));
|
||||
if (entry || layerContext(node) || node.matches(pathGroups) || node.hasAttribute('data-studio-hero')) $actions.append(layerButton('delete'));
|
||||
if (entry?.version != null) {
|
||||
const icon = $layout.find('template[data-layer-icon="settings"]').get(0).content.cloneNode(true);
|
||||
$('<a>', {class: 'button button-outline', href: $settings.attr('action') + '/' + entry.key,
|
||||
@@ -1937,10 +2005,11 @@ jQuery(function ($) {
|
||||
});
|
||||
}
|
||||
|
||||
function changeModule(section, copy) {
|
||||
async function changeModule(section, copy) {
|
||||
if (!section) return;
|
||||
if (!copy) {
|
||||
if (window.confirm('删除此区块?保存页面后生效。')) {
|
||||
const confirmed = await window.laySiteAction({title: '删除区块', message: '保存页面后生效,可在画布上撤销。', accept: '删除'});
|
||||
if (confirmed && section.node.isConnected) {
|
||||
removeSection(section);
|
||||
$studio.find('[data-canvas-status]').text('区块已移除,保存页面后生效。');
|
||||
}
|
||||
@@ -1975,12 +2044,12 @@ jQuery(function ($) {
|
||||
const classes = node.getAttribute('class');
|
||||
setMediaWidth(node, 100);
|
||||
const full = node.getBoundingClientRect();
|
||||
setMediaWidth(node, 10);
|
||||
setMediaWidth(node, minMediaWidth);
|
||||
const narrow = node.getBoundingClientRect();
|
||||
if (classes === null) node.removeAttribute('class');
|
||||
else node.setAttribute('class', classes);
|
||||
const fromLeft = getAlignment(node) === 'right';
|
||||
const edgeTravel = (fromLeft ? narrow.left - full.left : full.right - narrow.right) / .9;
|
||||
const edgeTravel = (fromLeft ? narrow.left - full.left : full.right - narrow.right) / (1 - minMediaWidth / 100);
|
||||
const available = edgeTravel > full.width * .15 ? edgeTravel : full.width;
|
||||
return {available, fromLeft, initialWidth: width || Math.round(100 * natural / (full.width || natural || 1))};
|
||||
}
|
||||
@@ -1988,7 +2057,7 @@ jQuery(function ($) {
|
||||
function resizeMedia(width) {
|
||||
const node = sizingTarget();
|
||||
if (!node) return;
|
||||
const next = width === null ? 0 : Math.round(Math.max(10, Math.min(100, width)));
|
||||
const next = width === null ? 0 : Math.round(Math.max(minMediaWidth, Math.min(100, width)));
|
||||
if (selectedMedia.hasAttribute('data-studio-hero-image')) pageInput('image_scale').val(next);
|
||||
if (next !== currentMediaWidth(node)) setMediaWidth(node, next);
|
||||
showMediaWidth(next);
|
||||
@@ -2019,7 +2088,7 @@ jQuery(function ($) {
|
||||
const step = event.shiftKey ? 10 : 1;
|
||||
const {initialWidth} = measureMedia();
|
||||
const increase = ['ArrowRight', 'ArrowUp'].includes(event.key);
|
||||
const next = {Home: 10, End: 100}[event.key] ?? initialWidth + (increase ? step : -step);
|
||||
const next = {Home: minMediaWidth, End: 100}[event.key] ?? initialWidth + (increase ? step : -step);
|
||||
resizeMedia(next);
|
||||
});
|
||||
$sizing.on('click', '[data-replace-media]', replaceMedia)
|
||||
@@ -2063,7 +2132,7 @@ jQuery(function ($) {
|
||||
$status.text('已插入' + $(this).text() + '。');
|
||||
};
|
||||
if (this.dataset.elementMime) {
|
||||
openPicker(this.dataset.elementMime, (file) => add(mediaMarkup(file)));
|
||||
openPicker(this.dataset.elementMime, async (file) => add(await mediaMarkup(file)));
|
||||
} else {
|
||||
add($presets.find('template[data-element="' + this.dataset.canvasElement + '"]').get(0).innerHTML);
|
||||
}
|
||||
@@ -2307,7 +2376,7 @@ jQuery(function ($) {
|
||||
const field = node.closest(canvasFields);
|
||||
const body = node.closest('[data-studio-part="body"]');
|
||||
const leaf = field || editableBodyElement(node);
|
||||
const wrapper = node.closest('[data-studio-section], [data-studio-hero], [data-studio-navigation]');
|
||||
const wrapper = node.closest('[data-studio-section], [data-studio-hero], ' + pathGroups);
|
||||
selectBody(body);
|
||||
selectElement(doc.getSelection()?.isCollapsed ? leaf || (body === node ? wrapper || body : body || wrapper) : null);
|
||||
});
|
||||
@@ -2431,10 +2500,10 @@ jQuery(function ($) {
|
||||
});
|
||||
|
||||
$editor.on('mousedown', '[data-insert], [data-rich-media]', (event) => event.preventDefault());
|
||||
$editor.on('click', '[data-insert]', function () {
|
||||
$editor.on('click', '[data-insert]', async function () {
|
||||
const command = $(this).data('insert');
|
||||
if (command === 'link') {
|
||||
const href = window.prompt('输入链接地址', 'https://')?.trim();
|
||||
const href = (await window.laySiteAction({title: '插入链接', label: '链接地址', value: 'https://', accept: '插入'}))?.trim();
|
||||
if (!href) return;
|
||||
if (!safeLink(href)) {
|
||||
$status.prop('hidden', false).text('请输入站内地址或有效的链接。');
|
||||
@@ -2455,8 +2524,8 @@ jQuery(function ($) {
|
||||
});
|
||||
|
||||
$editor.on('click', '[data-rich-media]', function () {
|
||||
openPicker('', (file) => {
|
||||
const markup = mediaMarkup(file);
|
||||
openPicker('', async (file) => {
|
||||
const markup = await mediaMarkup(file);
|
||||
if (markup) edit('insertHTML', markup);
|
||||
});
|
||||
});
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (C) 2017 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -0,0 +1,4 @@
|
||||
/* BASICS */.CodeMirror{/* Set height, width, borders, and global font properties here */font-family:monospace;height:300px;color:black;direction:ltr}/* PADDING */.CodeMirror-lines{padding:4px 0/* Vertical padding around content */}.CodeMirror pre.CodeMirror-line,.CodeMirror pre.CodeMirror-line-like{padding:0 4px/* Horizontal padding of content */}.CodeMirror-scrollbar-filler,.CodeMirror-gutter-filler{background-color:white/* The little square between H and V scrollbars */}/* GUTTER */.CodeMirror-gutters{border-right:1px solid #ddd;background-color:#f7f7f7;white-space:nowrap}.CodeMirror-linenumbers{}.CodeMirror-linenumber{padding:0 3px 0 5px;min-width:20px;text-align:right;color:#999;white-space:nowrap}.CodeMirror-guttermarker{color:black}.CodeMirror-guttermarker-subtle{color:#999}/* CURSOR */.CodeMirror-cursor{border-left:1px solid black;border-right:none;width:0}/* Shown when moving in bi-directional text */.CodeMirror div.CodeMirror-secondarycursor{border-left:1px solid silver}.cm-fat-cursor .CodeMirror-cursor{width:auto;border:0 !important;background:#7e7}.cm-fat-cursor div.CodeMirror-cursors{z-index:1}.cm-fat-cursor .CodeMirror-line::selection,.cm-fat-cursor .CodeMirror-line > span::selection,.cm-fat-cursor .CodeMirror-line > span > span::selection{background:transparent}.cm-fat-cursor .CodeMirror-line::-moz-selection,.cm-fat-cursor .CodeMirror-line > span::-moz-selection,.cm-fat-cursor .CodeMirror-line > span > span::-moz-selection{background:transparent}.cm-fat-cursor{caret-color:transparent}@-moz-keyframes blink{0%{}50%{background-color:transparent}100%{}}@-webkit-keyframes blink{0%{}50%{background-color:transparent}100%{}}@keyframes blink{0%{}50%{background-color:transparent}100%{}}/* Can style cursor different in overwrite (non-insert) mode */.CodeMirror-overwrite .CodeMirror-cursor{}.cm-tab{display:inline-block;text-decoration:inherit}.CodeMirror-rulers{position:absolute;left:0;right:0;top:-50px;bottom:0;overflow:hidden}.CodeMirror-ruler{border-left:1px solid #ccc;top:0;bottom:0;position:absolute}/* DEFAULT THEME */.cm-s-default .cm-header{color:blue}.cm-s-default .cm-quote{color:#090}.cm-negative{color:#d44}.cm-positive{color:#292}.cm-header,.cm-strong{font-weight:bold}.cm-em{font-style:italic}.cm-link{text-decoration:underline}.cm-strikethrough{text-decoration:line-through}.cm-s-default .cm-keyword{color:#708}.cm-s-default .cm-atom{color:#219}.cm-s-default .cm-number{color:#164}.cm-s-default .cm-def{color:#00f}.cm-s-default .cm-variable,.cm-s-default .cm-punctuation,.cm-s-default .cm-property,.cm-s-default .cm-operator{}.cm-s-default .cm-variable-2{color:#05a}.cm-s-default .cm-variable-3,.cm-s-default .cm-type{color:#085}.cm-s-default .cm-comment{color:#a50}.cm-s-default .cm-string{color:#a11}.cm-s-default .cm-string-2{color:#f50}.cm-s-default .cm-meta{color:#555}.cm-s-default .cm-qualifier{color:#555}.cm-s-default .cm-builtin{color:#30a}.cm-s-default .cm-bracket{color:#997}.cm-s-default .cm-tag{color:#170}.cm-s-default .cm-attribute{color:#00c}.cm-s-default .cm-hr{color:#999}.cm-s-default .cm-link{color:#00c}.cm-s-default .cm-error{color:#f00}.cm-invalidchar{color:#f00}.CodeMirror-composing{border-bottom:2px solid}/* Default styles for common addons */div.CodeMirror span.CodeMirror-matchingbracket{color:#0b0}div.CodeMirror span.CodeMirror-nonmatchingbracket{color:#a22}.CodeMirror-matchingtag{background:rgba(255, 150, 0, .3)}.CodeMirror-activeline-background{background:#e8f2ff}/* STOP *//* The rest of this file contains styles related to the mechanics of
|
||||
the editor. You probably shouldn't touch them. */.CodeMirror{position:relative;overflow:hidden;background:white}.CodeMirror-scroll{overflow:scroll !important;/* Things will break if this is overridden *//* 50px is the magic margin used to hide the element's real scrollbars *//* See overflow: hidden in .CodeMirror */margin-bottom:-50px;margin-right:-50px;padding-bottom:50px;height:100%;outline:none;/* Prevent dragging from highlighting the element */position:relative;z-index:0}.CodeMirror-sizer{position:relative;border-right:50px solid transparent}/* The fake, visible scrollbars. Used to force redraw during scrolling
|
||||
before actual scrolling happens, thus preventing shaking and
|
||||
flickering artifacts. */.CodeMirror-vscrollbar,.CodeMirror-hscrollbar,.CodeMirror-scrollbar-filler,.CodeMirror-gutter-filler{position:absolute;z-index:6;display:none;outline:none}.CodeMirror-vscrollbar{right:0;top:0;overflow-x:hidden;overflow-y:scroll}.CodeMirror-hscrollbar{bottom:0;left:0;overflow-y:hidden;overflow-x:scroll}.CodeMirror-scrollbar-filler{right:0;bottom:0}.CodeMirror-gutter-filler{left:0;bottom:0}.CodeMirror-gutters{position:absolute;left:0;top:0;min-height:100%;z-index:3}.CodeMirror-gutter{white-space:normal;height:100%;display:inline-block;vertical-align:top;margin-bottom:-50px}.CodeMirror-gutter-wrapper{position:absolute;z-index:4;background:none !important;border:none !important}.CodeMirror-gutter-background{position:absolute;top:0;bottom:0;z-index:4}.CodeMirror-gutter-elt{position:absolute;cursor:default;z-index:4}.CodeMirror-gutter-wrapper ::selection{background-color:transparent}.CodeMirror-gutter-wrapper ::-moz-selection{background-color:transparent}.CodeMirror-lines{cursor:text;min-height:1px/* prevents collapsing before first draw */}.CodeMirror pre.CodeMirror-line,.CodeMirror pre.CodeMirror-line-like{/* Reset some styles that the rest of the page might have set */-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;border-width:0;background:transparent;font-family:inherit;font-size:inherit;margin:0;white-space:pre;word-wrap:normal;line-height:inherit;color:inherit;z-index:2;position:relative;overflow:visible;-webkit-tap-highlight-color:transparent;-webkit-font-variant-ligatures:contextual;font-variant-ligatures:contextual}.CodeMirror-wrap pre.CodeMirror-line,.CodeMirror-wrap pre.CodeMirror-line-like{word-wrap:break-word;white-space:pre-wrap;word-break:normal}.CodeMirror-linebackground{position:absolute;left:0;right:0;top:0;bottom:0;z-index:0}.CodeMirror-linewidget{position:relative;z-index:2;padding:0.1px/* Force widget margins to stay inside of the container */}.CodeMirror-widget{}.CodeMirror-rtl pre{direction:rtl}.CodeMirror-code{outline:none}/* Force content-box sizing for the elements where we expect it */.CodeMirror-scroll,.CodeMirror-sizer,.CodeMirror-gutter,.CodeMirror-gutters,.CodeMirror-linenumber{-moz-box-sizing:content-box;box-sizing:content-box}.CodeMirror-measure{position:absolute;width:100%;height:0;overflow:hidden;visibility:hidden}.CodeMirror-cursor{position:absolute;pointer-events:none}.CodeMirror-measure pre{position:static}div.CodeMirror-cursors{visibility:hidden;position:relative;z-index:3}div.CodeMirror-dragcursors{visibility:visible}.CodeMirror-focused div.CodeMirror-cursors{visibility:visible}.CodeMirror-selected{background:#d9d9d9}.CodeMirror-focused .CodeMirror-selected{background:#d7d4f0}.CodeMirror-crosshair{cursor:crosshair}.CodeMirror-line::selection,.CodeMirror-line > span::selection,.CodeMirror-line > span > span::selection{background:#d7d4f0}.CodeMirror-line::-moz-selection,.CodeMirror-line > span::-moz-selection,.CodeMirror-line > span > span::-moz-selection{background:#d7d4f0}.cm-searching{background-color:#ffa;background-color:rgba(255, 255, 0, .4)}/* Used to force a border model for a node */.cm-force-border{padding-right:.1px}@media print{/* Hide the cursor when printing */.CodeMirror div.CodeMirror-cursors{visibility:hidden}}/* See issue #2901 */.cm-tab-wrap-hack:after{content:''}/* Help users use markselection to safely style text background */span.CodeMirror-selectedtext{background:none}
|
||||
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+9
@@ -0,0 +1,9 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"1.0.0": {
|
||||
"from": "v1.1.0-latest",
|
||||
"to": "v1.1.0-latest"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user