Enable in-place editing for page sections and media
This commit is contained in:
+29
-19
@@ -61,30 +61,39 @@ final class Repository
|
||||
return $this->one('SELECT * FROM sections WHERE page_slug = ? AND key = ?', [$page, $key]);
|
||||
}
|
||||
|
||||
public function savePage(string $slug, array $data, int $version): void
|
||||
public function savePage(string $slug, array $data, int $version, array $sections = []): void
|
||||
{
|
||||
$query = $this->pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?,
|
||||
image = ?, alt = ?, actions = ?, quicklinks = ?, status = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?');
|
||||
$query->execute([
|
||||
$data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'],
|
||||
$data['image'], $data['alt'], Database::json($data['actions']), Database::json($data['quicklinks']),
|
||||
$data['status'], self::now(), $slug, $version,
|
||||
]);
|
||||
self::checkVersion($query->rowCount());
|
||||
Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections): void {
|
||||
$query = $pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?,
|
||||
image = ?, alt = ?, actions = ?, quicklinks = ?, status = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?');
|
||||
$query->execute([
|
||||
$data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'],
|
||||
$data['image'], $data['alt'], Database::json($data['actions']), Database::json($data['quicklinks']),
|
||||
$data['status'], self::now(), $slug, $version,
|
||||
]);
|
||||
self::checkVersion($query->rowCount());
|
||||
foreach ($sections as $section) {
|
||||
self::updateSection($pdo, $slug, $section['key'], $section, $section['version']);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function saveSection(string $page, string $key, array $data, int $version): void
|
||||
{
|
||||
Database::write(function (PDO $pdo) use ($page, $key, $data, $version): void {
|
||||
$query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, version = version + 1
|
||||
WHERE page_slug = ? AND key = ? AND version = ?');
|
||||
$query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $page, $key, $version]);
|
||||
self::checkVersion($query->rowCount());
|
||||
$query = $pdo->prepare('UPDATE pages SET updated_at = ? WHERE slug = ?');
|
||||
$query->execute([self::now(), $page]);
|
||||
self::updateSection($pdo, $page, $key, $data, $version);
|
||||
self::touchPage($pdo, $page);
|
||||
});
|
||||
}
|
||||
|
||||
private static function updateSection(PDO $pdo, string $page, string $key, array $data, int $version): void
|
||||
{
|
||||
$query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, version = version + 1
|
||||
WHERE page_slug = ? AND key = ? AND version = ?');
|
||||
$query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $page, $key, $version]);
|
||||
self::checkVersion($query->rowCount());
|
||||
}
|
||||
|
||||
public function createSection(string $page, string $key, string $title, string $style, string $body): void
|
||||
{
|
||||
Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body): void {
|
||||
@@ -94,7 +103,7 @@ final class Repository
|
||||
if ($query->rowCount() !== 1) {
|
||||
throw new RuntimeException('此区块锚点已被使用。');
|
||||
}
|
||||
self::touchPage($pdo, $page);
|
||||
self::touchPage($pdo, $page, structureChanged: true);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -105,7 +114,7 @@ final class Repository
|
||||
$query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?');
|
||||
$query->execute([$page, $key, $version]);
|
||||
self::checkVersion($query->rowCount());
|
||||
self::touchPage($pdo, $page);
|
||||
self::touchPage($pdo, $page, structureChanged: true);
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -129,9 +138,10 @@ final class Repository
|
||||
});
|
||||
}
|
||||
|
||||
private static function touchPage(PDO $pdo, string $slug): void
|
||||
private static function touchPage(PDO $pdo, string $slug, bool $structureChanged = false): void
|
||||
{
|
||||
$pdo->prepare('UPDATE pages SET updated_at = ? WHERE slug = ?')->execute([self::now(), $slug]);
|
||||
$revision = $structureChanged ? ', version = version + 1' : '';
|
||||
$pdo->prepare('UPDATE pages SET updated_at = ?' . $revision . ' WHERE slug = ?')->execute([self::now(), $slug]);
|
||||
}
|
||||
|
||||
public function articles(?string $category = null, ?string $tag = null, bool $public = true, int $limit = 30, int $offset = 0): array
|
||||
|
||||
@@ -214,7 +214,8 @@ class AdminController
|
||||
strlen($data['image']) > 1000 || ($data['image'] !== '' && !Html::url($data['image'], true)) || !$validButtons) {
|
||||
throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。');
|
||||
}
|
||||
$repo->savePage($slug, $data, $this->version($request));
|
||||
$sections = $this->canvasSections($request->post('canvas_sections', ''), $page['sections']);
|
||||
$repo->savePage($slug, $data, $this->version($request), $sections);
|
||||
|
||||
return $this->success($request, '/admin/pages/' . $slug . '?saved=1');
|
||||
} catch (RuntimeException $exception) {
|
||||
@@ -247,10 +248,7 @@ class AdminController
|
||||
];
|
||||
$section = array_replace($section, $data, ['version' => $this->version($request)]);
|
||||
try {
|
||||
if ($data['title'] === '' || mb_strlen($data['title']) > 100 || mb_strlen($data['lead']) > 500 || strlen($data['body']) > 300000
|
||||
|| !in_array($data['style'], [$savedStyle, 'plain', 'tinted'], true)) {
|
||||
throw new RuntimeException('请填写区块标题,并检查说明及正文长度。');
|
||||
}
|
||||
$this->checkSection($data, $savedStyle);
|
||||
$data['body'] = Html::sanitize($data['body']);
|
||||
$repo->saveSection($slug, $key, $data, $this->version($request));
|
||||
|
||||
@@ -265,6 +263,51 @@ class AdminController
|
||||
], $error !== '' ? 422 : 200);
|
||||
}
|
||||
|
||||
private function canvasSections(mixed $payload, array $sections): array
|
||||
{
|
||||
if ($payload === '') {
|
||||
return [];
|
||||
}
|
||||
$changes = is_string($payload) ? json_decode($payload, true) : null;
|
||||
if (!is_array($changes) || !array_is_list($changes) || count($changes) > count($sections)) {
|
||||
throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。');
|
||||
}
|
||||
$available = array_column($sections, null, 'key');
|
||||
$updates = [];
|
||||
foreach ($changes as $change) {
|
||||
$key = $change['key'] ?? null;
|
||||
$version = $change['version'] ?? null;
|
||||
$fields = $change['fields'] ?? null;
|
||||
if (!is_string($key) || !isset($available[$key]) || !is_int($version) || !is_array($fields) || $fields === []) {
|
||||
throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。');
|
||||
}
|
||||
$section = $available[$key];
|
||||
unset($available[$key]);
|
||||
foreach ($fields as $field => $value) {
|
||||
if (!in_array($field, ['title', 'lead', 'body'], true) || !is_string($value)) {
|
||||
throw new RuntimeException('画布内容无效。');
|
||||
}
|
||||
$section[$field] = trim($value);
|
||||
}
|
||||
$this->checkSection($section, $section['style']);
|
||||
if (isset($fields['body'])) {
|
||||
$section['body'] = Html::sanitize($section['body']);
|
||||
}
|
||||
$section['version'] = $version;
|
||||
$updates[] = $section;
|
||||
}
|
||||
|
||||
return $updates;
|
||||
}
|
||||
|
||||
private function checkSection(array $section, string $savedStyle): void
|
||||
{
|
||||
if ($section['title'] === '' || mb_strlen($section['title']) > 100 || mb_strlen($section['lead']) > 500
|
||||
|| strlen($section['body']) > 300000 || !in_array($section['style'], [$savedStyle, 'plain', 'tinted'], true)) {
|
||||
throw new RuntimeException('请填写区块标题,并检查说明及正文长度。');
|
||||
}
|
||||
}
|
||||
|
||||
public function preview(Request $request): Response
|
||||
{
|
||||
if ($failure = $this->guard($request)) {
|
||||
|
||||
@@ -28,7 +28,7 @@ final class SiteController
|
||||
return $this->renderPage($repo, $page);
|
||||
}
|
||||
|
||||
public function renderPage(Repository $repo, array $page, bool $preview = false): Response
|
||||
public function renderPage(Repository $repo, array $page, bool $preview = false, bool $canvas = false): Response
|
||||
{
|
||||
$slug = $page['slug'];
|
||||
$isHome = $slug === 'home';
|
||||
@@ -42,7 +42,7 @@ final class SiteController
|
||||
'socialImage' => $page['image'],
|
||||
'socialAlt' => $page['alt'],
|
||||
'articles' => $isHome ? $repo->articles(limit: 3) : [],
|
||||
'previewMode' => $preview, 'noindex' => $preview,
|
||||
'previewMode' => $preview, 'canvas' => $preview && $canvas, 'noindex' => $preview,
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ final class StudioController extends AdminController
|
||||
$repo = new Repository();
|
||||
$page = $repo->page($slug);
|
||||
|
||||
return $page ? (new SiteController())->renderPage($repo, $page, true) : $this->error($request, '找不到此页面。', 404);
|
||||
return $page ? (new SiteController())->renderPage($repo, $page, true, $request->get('canvas') === '1') : $this->error($request, '找不到此页面。', 404);
|
||||
}
|
||||
|
||||
public function blocks(Request $request, string $slug): Response
|
||||
|
||||
+36
-6
@@ -20,16 +20,44 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
|
||||
<div>
|
||||
<section class="admin-panel studio-preview" data-preview-studio aria-labelledby="studio-preview-title">
|
||||
<div class="admin-heading compact">
|
||||
<h2 id="studio-preview-title">页面预览</h2>
|
||||
<h2 id="studio-preview-title">页面画布</h2>
|
||||
<div class="preview-selector" aria-label="预览尺寸">
|
||||
<button type="button" class="button button-outline" data-preview-size="desktop" aria-pressed="true">桌面</button>
|
||||
<button type="button" class="button button-outline" data-preview-size="phone" aria-pressed="false">手机</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="studio-frame-window">
|
||||
<iframe title="当前保存的页面" src="<?= $e($previewUrl) ?>" sandbox="allow-same-origin" loading="lazy"></iframe>
|
||||
<div class="editor-toolbar studio-canvas-toolbar" data-canvas-toolbar hidden aria-label="正文工具">
|
||||
<div>
|
||||
<button type="button" data-canvas-command="heading">小标题</button>
|
||||
<button type="button" data-canvas-command="bold">粗体</button>
|
||||
<button type="button" data-canvas-command="list">列表</button>
|
||||
<button type="button" data-canvas-command="link">插入链接</button>
|
||||
<button type="button" data-canvas-command="media">插入媒体</button>
|
||||
</div>
|
||||
<button class="button button-primary" form="studio-page-settings" type="submit">保存页面</button>
|
||||
</div>
|
||||
<p class="field-note">可在画布内直接编辑标题和简介。其他改动保存后刷新预览。</p>
|
||||
<div class="studio-frame-window">
|
||||
<iframe title="可编辑页面画布" src="<?= $e($previewUrl) ?>?canvas=1" sandbox="allow-same-origin"></iframe>
|
||||
</div>
|
||||
<p class="field-note">直接编辑画布上的文字。点击图片、媒体、按钮或链接可修改属性。选中区块正文后可使用上方工具。</p>
|
||||
<dialog class="media-picker canvas-properties" data-canvas-properties aria-labelledby="canvas-properties-heading">
|
||||
<div class="admin-heading compact"><h2 id="canvas-properties-heading" data-property-heading>编辑属性</h2></div>
|
||||
<form class="admin-form" method="dialog">
|
||||
<label data-property-row="label">文案<input name="label"></label>
|
||||
<label data-property-row="url">地址<input name="url" maxlength="1000"></label>
|
||||
<label data-property-row="alt">图片替代文本<input name="alt" maxlength="200"></label>
|
||||
<label data-property-row="poster">视频封面<input name="poster" maxlength="1000"></label>
|
||||
<p class="feedback error" role="alert" data-property-error hidden></p>
|
||||
<div class="actions">
|
||||
<button type="button" class="button button-outline" data-property-pick="url">从媒体库选择</button>
|
||||
<button type="button" class="button button-outline" data-property-pick="poster">选择视频封面</button>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button type="submit" class="button button-primary">应用</button>
|
||||
<button type="button" class="button button-outline" data-property-close>取消</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
</section>
|
||||
<section class="admin-panel" id="blocks">
|
||||
<h2>内容区块</h2>
|
||||
@@ -38,7 +66,8 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
|
||||
<li>
|
||||
<div><strong><?= $e($item['title']) ?></strong><small>#<?= $e($item['key']) ?></small></div>
|
||||
<div class="actions studio-block-actions">
|
||||
<a class="button button-outline" href="/admin/pages/<?= $e($slug) ?>/<?= $e($item['key']) ?>">编辑</a>
|
||||
<button class="button button-outline" type="button" data-canvas-jump="<?= $e($item['key']) ?>" hidden>在画布编辑</button>
|
||||
<a class="button button-outline" href="/admin/pages/<?= $e($slug) ?>/<?= $e($item['key']) ?>">区块设置</a>
|
||||
<form method="post" action="/admin/page-blocks/<?= $e($slug) ?>">
|
||||
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
|
||||
<input type="hidden" name="key" value="<?= $e($item['key']) ?>">
|
||||
@@ -62,10 +91,11 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
<form class="admin-form admin-panel studio-inspector" method="post" action="/admin/pages/<?= $e($slug) ?>">
|
||||
<form id="studio-page-settings" class="admin-form admin-panel studio-inspector" method="post" action="/admin/pages/<?= $e($slug) ?>">
|
||||
<h2>页面设置</h2>
|
||||
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
|
||||
<input type="hidden" name="version" value="<?= $e($page['version']) ?>">
|
||||
<input type="hidden" name="canvas_sections" value="">
|
||||
<label>页面名称<input name="name" value="<?= $e($page['name']) ?>" required maxlength="100"></label>
|
||||
<label>SEO 标题<input name="title" value="<?= $e($page['title']) ?>" required maxlength="160"></label>
|
||||
<label>SEO 描述<textarea name="description" rows="2" maxlength="300"><?= $e($page['description']) ?></textarea></label>
|
||||
|
||||
+12
-11
@@ -5,6 +5,7 @@ use App\Content\View;
|
||||
$e = View::escape(...);
|
||||
$home = $page['slug'] === 'home';
|
||||
$service = in_array($page['slug'], ['sc', 'shnu-sc'], true);
|
||||
$field = static fn (string $name): string => $canvas ? ' data-studio-field="' . $name . '"' : '';
|
||||
?>
|
||||
<section class="hero hero-<?= $e($page['slug']) ?>" id="home" data-enter>
|
||||
<div class="wrap hero-inner<?= $page['image'] === '' ? ' hero-text-only' : '' ?>">
|
||||
@@ -17,24 +18,24 @@ $service = in_array($page['slug'], ['sc', 'shnu-sc'], true);
|
||||
</span>
|
||||
<span class="crumb-divider" aria-hidden="true">/</span>
|
||||
<span itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
|
||||
<a itemprop="item" href="/<?= $e($page['slug']) ?>" aria-current="page"><span itemprop="name"><?= $e($page['name']) ?></span></a>
|
||||
<a itemprop="item" href="/<?= $e($page['slug']) ?>" aria-current="page"><span itemprop="name"<?= $field('name') ?>><?= $e($page['name']) ?></span></a>
|
||||
<meta itemprop="position" content="2">
|
||||
</span>
|
||||
</nav>
|
||||
<?php else: ?>
|
||||
<p class="overline hero-label"><?= $e($site['footer']['name'] ?? $site['name']) ?></p>
|
||||
<?php endif ?>
|
||||
<h1><span class="hero-heading-primary" data-studio-field="heading"><?= $e($page['heading']) ?></span><?php if ($page['accent'] !== ''): ?><br><span><?= $e($page['accent']) ?></span><?php endif ?></h1>
|
||||
<p class="hero-lead" data-studio-field="lead"><?= $e($page['lead']) ?></p>
|
||||
<h1><span class="hero-heading-primary"<?= $field('heading') ?>><?= $e($page['heading']) ?></span><?php if ($canvas): ?><span class="studio-accent"<?= $field('accent') ?>><?= $e($page['accent']) ?></span><?php elseif ($page['accent'] !== ''): ?><br><span><?= $e($page['accent']) ?></span><?php endif ?></h1>
|
||||
<p class="hero-lead"<?= $field('lead') ?>><?= $e($page['lead']) ?></p>
|
||||
<div class="actions hero-actions">
|
||||
<?php foreach ($page['actions'] as $index => [$url, $label]): ?>
|
||||
<a class="button <?= $index ? 'button-outline' : 'button-primary' ?>" href="<?= $e($home && $url === '/#product' ? '/services' : $url) ?>"><?= $e($label) ?></a>
|
||||
<?php foreach ($canvas ? array_pad($page['actions'], 2, ['', '']) : $page['actions'] as $index => [$url, $label]): ?>
|
||||
<a class="button <?= $index ? 'button-outline' : 'button-primary' ?>" href="<?= $e($home && $url === '/#product' ? '/services' : $url) ?>"<?= $canvas ? ' data-studio-action="' . ($index + 1) . '"' : '' ?><?= $label === '' && $url === '' ? ' hidden' : '' ?>><?= $e($label) ?></a>
|
||||
<?php endforeach ?>
|
||||
</div>
|
||||
</div>
|
||||
<?php if ($page['image'] !== ''): ?>
|
||||
<div class="hero-visual <?= $home ? 'hero-illustration' : ($service ? 'hero-service-art' : 'app-frame') ?>" data-visual>
|
||||
<img src="<?= $e($page['image']) ?>" alt="<?= $e($page['alt']) ?>" width="1448" height="1086" fetchpriority="high">
|
||||
<?php if ($canvas || $page['image'] !== ''): ?>
|
||||
<div class="hero-visual <?= $home ? 'hero-illustration' : ($service ? 'hero-service-art' : 'app-frame') ?>" data-visual<?= $page['image'] === '' ? ' hidden' : '' ?>>
|
||||
<img<?= $page['image'] === '' ? '' : ' src="' . $e($page['image']) . '"' ?> alt="<?= $e($page['alt']) ?>" width="1448" height="1086" fetchpriority="high"<?= $canvas ? ' data-studio-hero-image' : '' ?>>
|
||||
</div>
|
||||
<?php endif ?>
|
||||
</div>
|
||||
@@ -48,8 +49,8 @@ $service = in_array($page['slug'], ['sc', 'shnu-sc'], true);
|
||||
</div>
|
||||
<?php endif ?>
|
||||
</section>
|
||||
<?php if ($page['quicklinks']): ?>
|
||||
<nav class="section-nav" aria-label="本页目录">
|
||||
<?php if ($canvas || $page['quicklinks']): ?>
|
||||
<nav class="section-nav" aria-label="本页目录"<?= $canvas ? ' data-studio-navigation' : '' ?><?= !$page['quicklinks'] ? ' hidden' : '' ?>>
|
||||
<div class="wrap section-nav-inner">
|
||||
<?php foreach ($page['quicklinks'] as [$url, $label]): ?>
|
||||
<a href="<?= $e($url) ?>"><?= $e($label) ?></a>
|
||||
@@ -58,7 +59,7 @@ $service = in_array($page['slug'], ['sc', 'shnu-sc'], true);
|
||||
</nav>
|
||||
<?php endif ?>
|
||||
<?php foreach ($page['sections'] as $section): ?>
|
||||
<?= View::fragment('section', ['section' => $section, 'moment' => $home && $section['key'] === 'about']) ?>
|
||||
<?= View::fragment('section', ['section' => $section, 'moment' => $home && $section['key'] === 'about', 'canvas' => $canvas]) ?>
|
||||
<?php endforeach ?>
|
||||
<?php if ($home): ?>
|
||||
<section class="section home-news" id="blog" aria-labelledby="updates-heading">
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
use App\Content\View;
|
||||
|
||||
$e = View::escape(...);
|
||||
$canvas ??= false;
|
||||
?>
|
||||
<section class="section section-<?= $e($section['style']) ?>" id="<?= $e($section['key']) ?>" aria-labelledby="heading-<?= $e($section['key']) ?>" <?= $moment ? 'data-moment="iris-opens"' : '' ?>>
|
||||
<section class="section section-<?= $e($section['style']) ?>" id="<?= $e($section['key']) ?>" aria-labelledby="heading-<?= $e($section['key']) ?>" <?= $moment ? 'data-moment="iris-opens"' : '' ?><?= $canvas ? ' data-studio-section="' . $e($section['version']) . '"' : '' ?>>
|
||||
<div class="wrap">
|
||||
<div class="section-heading">
|
||||
<h2 id="heading-<?= $e($section['key']) ?>"><?= $e($section['title']) ?></h2>
|
||||
<?php if ($section['lead']): ?><p><?= $e($section['lead']) ?></p><?php endif ?>
|
||||
<h2 id="heading-<?= $e($section['key']) ?>"<?= $canvas ? ' data-studio-part="title"' : '' ?>><?= $e($section['title']) ?></h2>
|
||||
<?php if ($canvas || $section['lead']): ?><p<?= $canvas ? ' data-studio-part="lead"' : '' ?>><?= $e($section['lead']) ?></p><?php endif ?>
|
||||
</div>
|
||||
<div class="rich"><?= $section['body'] ?></div>
|
||||
<div class="rich"<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $section['body'] ?></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -58,6 +58,8 @@
|
||||
.studio-frame-window { position: relative; height: min(67vh, 39rem); overflow: hidden; margin-bottom: .8rem; border: 1px solid var(--line); border-radius: .55rem; background: var(--paper); }
|
||||
.studio-frame-window iframe { display: block; width: 100%; height: 100%; border: 0; background: white; }
|
||||
.studio-frame-window.has-scaled-preview iframe { position: absolute; top: 0; transform-origin: 0 0; }
|
||||
.studio-canvas-toolbar { margin-bottom: .55rem; }
|
||||
.studio-canvas-toolbar button:disabled { opacity: .5; cursor: default; }
|
||||
.preview-selector { display: flex; gap: .35rem; flex-wrap: wrap; }
|
||||
.preview-selector [aria-pressed="true"] { background: var(--accent-light); color: var(--accent-deep); }
|
||||
.studio-inspector details label { margin-top: .7rem; }
|
||||
@@ -81,6 +83,7 @@
|
||||
.media-card .media-archive { display: flex; align-items: center; }
|
||||
.media-card .media-archive input { width: auto; min-height: 0; }
|
||||
.media-picker { max-width: min(92vw, 52rem); max-height: 86vh; width: 100%; padding: 1.25rem; border: 1px solid var(--line); border-radius: var(--radius); color: var(--ink); }
|
||||
.media-picker.canvas-properties { max-width: min(92vw, 32rem); }
|
||||
.media-picker::backdrop { background: #101c3488; }
|
||||
.media-picker label { display: grid; gap: .35rem; }
|
||||
.media-picker input { padding: .55rem .75rem; border: 1px solid var(--line); border-radius: .4rem; }
|
||||
|
||||
@@ -49,10 +49,12 @@ jQuery(function ($) {
|
||||
const multipart = $form.attr('enctype') === 'multipart/form-data';
|
||||
$form.attr('aria-busy', 'true').children('.ajax-feedback').prop('hidden', true);
|
||||
$submit.prop('disabled', true);
|
||||
$form.triggerHandler('studio:busy', [true]);
|
||||
|
||||
function finish() {
|
||||
$form.removeAttr('aria-busy');
|
||||
$submit.prop('disabled', false);
|
||||
$form.triggerHandler('studio:busy', [false]);
|
||||
}
|
||||
|
||||
function submit(canRetryLogin) {
|
||||
@@ -71,11 +73,12 @@ jQuery(function ($) {
|
||||
dataType: 'json'
|
||||
}).done(function (response) {
|
||||
if (response.redirect) {
|
||||
$form.triggerHandler('studio:saved');
|
||||
window.location.assign(response.redirect);
|
||||
return;
|
||||
}
|
||||
formError($form, '未收到保存结果,请刷新页面确认。');
|
||||
finish();
|
||||
formError($form, '未收到保存结果,请刷新页面确认。');
|
||||
}).fail(function (request) {
|
||||
const response = request.responseJSON;
|
||||
refreshToken(response);
|
||||
@@ -83,8 +86,8 @@ jQuery(function ($) {
|
||||
submit(false);
|
||||
return;
|
||||
}
|
||||
formError($form, response?.message || '请求未完成,请稍后重试。', request.status);
|
||||
finish();
|
||||
formError($form, response?.message || '请求未完成,请稍后重试。', request.status);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+13
-1
@@ -473,4 +473,16 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); }
|
||||
.copyright-service #go .contact-panel img { position: static; transform: none; width: 7rem; }
|
||||
}
|
||||
.hero h1 .hero-heading-primary { color: inherit; }
|
||||
[data-studio-field][contenteditable] { min-height: 1em; outline: 1px dashed #7896d5; outline-offset: 3px; }
|
||||
.studio-accent { display: block; }
|
||||
[data-studio-editing] [contenteditable], [data-studio-editing] [data-studio-action],
|
||||
[data-studio-editing] [data-studio-navigation] a, [data-studio-editing] [data-studio-hero-image] {
|
||||
outline: 1px dashed #7896d5;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
[data-studio-editing] [contenteditable]:focus { outline: 2px solid #4477f9; }
|
||||
[data-studio-editing] :is([data-studio-action], [data-studio-navigation] a, [data-studio-hero-image], .rich :is(img, video, audio)) { cursor: pointer; }
|
||||
[data-studio-editing] [data-studio-placeholder]:empty::before {
|
||||
content: attr(data-studio-placeholder);
|
||||
color: var(--muted);
|
||||
font: 400 1rem / 1.5 var(--sans);
|
||||
}
|
||||
|
||||
+351
-29
@@ -9,6 +9,26 @@ jQuery(function ($) {
|
||||
let mediaType = '';
|
||||
let pickerRequest;
|
||||
|
||||
function safeLink(value, media = false) {
|
||||
return value !== '' && !/[\u0000-\u0020\u007f\\]/.test(value)
|
||||
&& (/^\/(?!\/)/.test(value) || (media ? /^https:\/\//i : /^(https?:\/\/|mailto:|tel:|#\S)/i).test(value));
|
||||
}
|
||||
|
||||
function mediaMarkup(file) {
|
||||
let $node;
|
||||
if (file.mime.startsWith('image/')) {
|
||||
const alt = window.prompt('图片替代文本(装饰图可留空)', file.label);
|
||||
if (alt === null) return '';
|
||||
$node = $('<img>', {src: file.url, alt, loading: 'lazy'});
|
||||
} else if (file.mime.startsWith('video/') || file.mime.startsWith('audio/')) {
|
||||
const tag = file.mime.startsWith('video/') ? '<video>' : '<audio>';
|
||||
$node = $(tag, {src: file.url, controls: true, preload: 'metadata'});
|
||||
} else {
|
||||
$node = $('<a>', {href: file.url}).text(file.label);
|
||||
}
|
||||
return $node.prop('outerHTML');
|
||||
}
|
||||
|
||||
function renderPicker() {
|
||||
const query = String($picker.find('[data-media-query]').val() || '').trim().toLowerCase();
|
||||
const results = files.filter((file) => file.mime.startsWith(mediaType)
|
||||
@@ -120,20 +140,338 @@ jQuery(function ($) {
|
||||
$button.attr('aria-pressed', 'true');
|
||||
fitPreview();
|
||||
});
|
||||
function attachCanvas() {
|
||||
const $doc = $frame.contents();
|
||||
for (const field of ['heading', 'lead']) {
|
||||
const $target = $doc.find('[data-studio-field="' + field + '"]');
|
||||
const $input = $settings.find('[name="' + field + '"]');
|
||||
$target.text($input.val());
|
||||
$target.attr({contenteditable: 'plaintext-only', spellcheck: 'false', 'aria-label': field === 'heading' ? '编辑首屏标题' : '编辑首屏简介'});
|
||||
$target.on('input.studio', () => $input.val($target.text()));
|
||||
$input.off('input.studio').on('input.studio', () => $target.text($input.val()));
|
||||
}
|
||||
$doc.on('click.studio', 'a', (event) => event.preventDefault());
|
||||
const $toolbar = $studio.find('[data-canvas-toolbar]');
|
||||
const $commands = $toolbar.find('[data-canvas-command]');
|
||||
const $properties = $studio.find('[data-canvas-properties]');
|
||||
const $propertyForm = $properties.find('form');
|
||||
const $propertyError = $properties.find('[data-property-error]');
|
||||
const propertyInput = (name) => $propertyForm.find('[name="' + name + '"]');
|
||||
const pageInput = (name) => $settings.find('[name="' + name + '"]');
|
||||
const settingsSnapshot = () => $settings.serializeArray()
|
||||
.filter(({name}) => name !== 'csrf' && name !== 'canvas_sections');
|
||||
const savedSettings = JSON.stringify(settingsSnapshot());
|
||||
let dialogAction;
|
||||
let doc;
|
||||
let activeBody;
|
||||
let savedRange;
|
||||
let sections = [];
|
||||
let saveComplete = false;
|
||||
|
||||
function sectionChanges() {
|
||||
return sections.flatMap(({key, version, fields}) => {
|
||||
const changes = {};
|
||||
for (const [field, {node, initial}] of Object.entries(fields)) {
|
||||
const value = field === 'body' ? node.innerHTML : node.textContent;
|
||||
if (value !== initial) changes[field] = value;
|
||||
}
|
||||
return Object.keys(changes).length ? [{key, version, fields: changes}] : [];
|
||||
});
|
||||
}
|
||||
|
||||
$settings.on('studio:sync', () => pageInput('canvas_sections').val(JSON.stringify(sectionChanges())));
|
||||
$settings.on('studio:saved', () => { saveComplete = true; });
|
||||
$settings.on('studio:busy', (_event, busy) => {
|
||||
$studio.prop('inert', busy);
|
||||
$settings.prop('inert', busy);
|
||||
});
|
||||
$(window).on('beforeunload', (event) => {
|
||||
if (!saveComplete && (sectionChanges().length || JSON.stringify(settingsSnapshot()) !== savedSettings)) {
|
||||
event.preventDefault();
|
||||
event.originalEvent.returnValue = '';
|
||||
}
|
||||
});
|
||||
|
||||
function openProperties(heading, values, apply, mime = null, allowEmptyUrl = false) {
|
||||
$properties.find('[data-property-heading]').text(heading);
|
||||
$propertyError.prop('hidden', true);
|
||||
for (const key of ['label', 'url', 'alt', 'poster']) {
|
||||
const visible = Object.hasOwn(values, key);
|
||||
$propertyForm.find('[data-property-row="' + key + '"]').prop('hidden', !visible);
|
||||
propertyInput(key).val(visible ? values[key] : '');
|
||||
}
|
||||
$properties.find('[data-property-pick="url"]').prop('hidden', mime === null);
|
||||
$properties.find('[data-property-pick="poster"]').prop('hidden', !Object.hasOwn(values, 'poster'));
|
||||
dialogAction = {values, apply, mime, allowEmptyUrl};
|
||||
$properties.get(0).showModal();
|
||||
}
|
||||
|
||||
$properties.on('click', '[data-property-close]', () => $properties.get(0).close());
|
||||
$properties.on('click', '[data-property-pick]', function () {
|
||||
const field = this.dataset.propertyPick;
|
||||
openPicker(field === 'poster' ? 'image/' : dialogAction.mime,
|
||||
(file) => propertyInput(field).val(file.url).trigger('focus'));
|
||||
});
|
||||
$propertyForm.on('submit', (event) => {
|
||||
event.preventDefault();
|
||||
const {values, apply, mime, allowEmptyUrl} = dialogAction;
|
||||
const result = Object.fromEntries(Object.keys(values).map((field) => [field, propertyInput(field).val().trim()]));
|
||||
if ((!result.url && !allowEmptyUrl) || (result.url && !safeLink(result.url, mime !== null))
|
||||
|| (result.poster && !safeLink(result.poster, true))) {
|
||||
$propertyError.prop('hidden', false).text('请输入有效的站内地址或链接。媒体也可使用 HTTPS 地址。');
|
||||
return;
|
||||
}
|
||||
if (apply(result) !== false) $properties.get(0).close();
|
||||
});
|
||||
|
||||
function rememberSelection() {
|
||||
const selection = doc.getSelection();
|
||||
if (selection.rangeCount && activeBody?.contains(selection.anchorNode) && activeBody.contains(selection.focusNode)) {
|
||||
savedRange = selection.getRangeAt(0).cloneRange();
|
||||
}
|
||||
}
|
||||
|
||||
function selectBody(body) {
|
||||
if (body !== activeBody) {
|
||||
activeBody = body;
|
||||
savedRange = null;
|
||||
}
|
||||
$commands.prop('disabled', !activeBody);
|
||||
}
|
||||
|
||||
function editBody(body, range, command, value) {
|
||||
if (!body?.isConnected) return;
|
||||
body.focus();
|
||||
const selection = doc.getSelection();
|
||||
if (!range || !body.contains(range.commonAncestorContainer)) {
|
||||
range = doc.createRange();
|
||||
range.selectNodeContents(body);
|
||||
range.collapse(false);
|
||||
}
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
doc.execCommand(command, false, value);
|
||||
rememberSelection();
|
||||
}
|
||||
|
||||
$toolbar.on('mousedown', '[data-canvas-command]', (event) => event.preventDefault());
|
||||
$toolbar.on('click', '[data-canvas-command]', function () {
|
||||
const command = this.dataset.canvasCommand;
|
||||
const body = activeBody;
|
||||
const range = savedRange?.cloneRange();
|
||||
const edit = (action, value) => editBody(body, range, action, value);
|
||||
if (command === 'media') {
|
||||
openPicker('', (file) => {
|
||||
const markup = mediaMarkup(file);
|
||||
if (markup) edit('insertHTML', markup);
|
||||
});
|
||||
} else if (command === 'link') {
|
||||
openProperties('插入链接', {label: range?.toString() || '', url: ''}, ({label, url}) => {
|
||||
queueMicrotask(() => {
|
||||
if (range && !range.collapsed && label === range.toString()) {
|
||||
edit('createLink', url);
|
||||
} else {
|
||||
edit('insertHTML', $('<a>', {href: url}).text(label || url).prop('outerHTML'));
|
||||
}
|
||||
});
|
||||
});
|
||||
} else {
|
||||
const commands = {heading: ['formatBlock', 'h3'], bold: ['bold'], list: ['insertUnorderedList']};
|
||||
edit(...commands[command]);
|
||||
}
|
||||
});
|
||||
|
||||
function configureText(node, label, placeholder = false) {
|
||||
node.contentEditable = 'plaintext-only';
|
||||
node.setAttribute('aria-label', label);
|
||||
if (placeholder) node.dataset.studioPlaceholder = label;
|
||||
}
|
||||
|
||||
function bindPage($doc) {
|
||||
const labels = {name: '页面名称', heading: '首屏标题', accent: '标题第二行', lead: '首屏简介'};
|
||||
$doc.find('[data-studio-field]').each(function () {
|
||||
const field = this.dataset.studioField;
|
||||
const $target = $(this);
|
||||
const $input = pageInput(field);
|
||||
configureText(this, labels[field], ['accent', 'lead'].includes(field));
|
||||
$target.text($input.val()).on('input', () => $input.val($target.text()));
|
||||
$input.on('input.canvas', () => $target.text($input.val()));
|
||||
});
|
||||
|
||||
const $image = $doc.find('[data-studio-hero-image]');
|
||||
const $visual = $image.parent();
|
||||
function syncImage() {
|
||||
const path = pageInput('image').val().trim();
|
||||
const valid = safeLink(path, true);
|
||||
$visual.prop('hidden', !valid).parent().toggleClass('hero-text-only', !valid);
|
||||
if (valid) $image.attr('src', path);
|
||||
else $image.removeAttr('src');
|
||||
$image.attr('alt', pageInput('alt').val());
|
||||
}
|
||||
$settings.find('[name="image"], [name="alt"]').on('input.canvas', syncImage);
|
||||
syncImage();
|
||||
$image.attr({tabindex: '0', role: 'button', 'aria-label': '编辑首屏图片'}).on('click', () => {
|
||||
openProperties('首屏图片', {url: pageInput('image').val(), alt: pageInput('alt').val()}, ({url, alt}) => {
|
||||
pageInput('image').val(url);
|
||||
pageInput('alt').val(alt);
|
||||
syncImage();
|
||||
}, 'image/', true);
|
||||
});
|
||||
|
||||
$doc.find('[data-studio-action]').each(function () {
|
||||
const $button = $(this);
|
||||
const index = this.dataset.studioAction;
|
||||
const $label = pageInput('label' + index);
|
||||
const $url = pageInput('url' + index);
|
||||
function sync() {
|
||||
const url = $url.val().trim();
|
||||
const target = url === '/#product' && $doc.find('.hero-home').length ? '/services' : url;
|
||||
$button.text($label.val()).attr('href', safeLink(target) ? target : '#').prop('hidden', !$label.val() && !url);
|
||||
}
|
||||
$label.add($url).on('input.canvas', sync);
|
||||
$button.on('click', (event) => {
|
||||
event.preventDefault();
|
||||
openProperties('首屏按钮', {label: $label.val(), url: $url.val()}, ({label, url}) => {
|
||||
if (Boolean(label) !== Boolean(url)) {
|
||||
$propertyError.prop('hidden', false).text('请同时填写按钮文案和链接,或将两项都留空。');
|
||||
return false;
|
||||
}
|
||||
$label.val(label);
|
||||
$url.val(url);
|
||||
sync();
|
||||
}, null, true);
|
||||
});
|
||||
sync();
|
||||
});
|
||||
|
||||
const $navigation = $doc.find('[data-studio-navigation]');
|
||||
const $navContent = $navigation.find('.section-nav-inner');
|
||||
const $navInput = pageInput('quicklinks');
|
||||
const navLines = () => $navInput.val().split(/\r\n|[\n\r\v\f\u0085\u2028\u2029]/);
|
||||
function syncNavigation() {
|
||||
const lines = navLines();
|
||||
$navContent.empty();
|
||||
for (const [index, line] of lines.entries()) {
|
||||
if (!line.trim()) continue;
|
||||
const separator = line.indexOf('|');
|
||||
const label = (separator < 0 ? line : line.slice(0, separator)).trim();
|
||||
const url = separator < 0 ? '' : line.slice(separator + 1).trim();
|
||||
const link = doc.createElement('a');
|
||||
link.href = safeLink(url) ? url : '#';
|
||||
link.textContent = label || url;
|
||||
link.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
openProperties('本页目录链接', {label, url}, (next) => {
|
||||
if (!next.label || /[|\r\n]/.test(next.label)) {
|
||||
$propertyError.prop('hidden', false).text('请填写目录文案,文案不能包含竖线。');
|
||||
return false;
|
||||
}
|
||||
const updated = navLines();
|
||||
updated[index] = next.label + ' | ' + next.url;
|
||||
$navInput.val(updated.join('\n'));
|
||||
syncNavigation();
|
||||
});
|
||||
});
|
||||
$navContent.append(link);
|
||||
}
|
||||
$navigation.prop('hidden', !$navContent.children().length);
|
||||
}
|
||||
$navInput.on('input.canvas', syncNavigation);
|
||||
syncNavigation();
|
||||
}
|
||||
|
||||
function editResource(node) {
|
||||
const tag = node.localName;
|
||||
if (tag === 'a') {
|
||||
const onlyChild = node.firstElementChild;
|
||||
const text = node.childElementCount === 0 ? node : (
|
||||
node.childElementCount === 1 && onlyChild.matches('span, strong, b, em, i, small')
|
||||
&& !onlyChild.childElementCount && node.textContent.trim() === onlyChild.textContent.trim() ? onlyChild : null
|
||||
);
|
||||
const values = text ? {label: text.textContent, url: node.getAttribute('href') || ''} : {url: node.getAttribute('href') || ''};
|
||||
openProperties('正文链接', values, ({label, url}) => {
|
||||
node.setAttribute('href', url);
|
||||
if (text && label !== values.label) text.textContent = label;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const source = tag === 'img' ? node : (node.hasAttribute('src') ? node : node.querySelector('source') || node);
|
||||
const values = {url: source.getAttribute('src') || ''};
|
||||
if (tag === 'img') values.alt = node.getAttribute('alt') || '';
|
||||
if (tag === 'video') values.poster = node.getAttribute('poster') || '';
|
||||
openProperties({img: '正文图片', video: '视频', audio: '音频'}[tag], values, ({url, alt, poster}) => {
|
||||
if (url !== values.url) {
|
||||
source.setAttribute('src', url);
|
||||
if (source !== node) source.removeAttribute('type');
|
||||
if (tag !== 'img') node.load();
|
||||
}
|
||||
if (alt !== undefined && alt !== values.alt) node.setAttribute('alt', alt);
|
||||
if (poster !== undefined && poster !== values.poster) {
|
||||
if (poster) node.setAttribute('poster', poster);
|
||||
else node.removeAttribute('poster');
|
||||
}
|
||||
}, (tag === 'img' ? 'image' : tag) + '/');
|
||||
}
|
||||
|
||||
function attachCanvas() {
|
||||
doc = $frame.get(0).contentDocument;
|
||||
if (!doc?.querySelector('[data-studio-field]') || doc.documentElement.hasAttribute('data-studio-editing')) return;
|
||||
doc.documentElement.setAttribute('data-studio-editing', '');
|
||||
const $doc = $(doc);
|
||||
$settings.find(':input').off('.canvas');
|
||||
bindPage($doc);
|
||||
selectBody(null);
|
||||
sections = $doc.find('[data-studio-section]').map(function () {
|
||||
const fields = {};
|
||||
$(this).find('[data-studio-part]').each(function () {
|
||||
const part = this.dataset.studioPart;
|
||||
const body = part === 'body';
|
||||
const label = {title: '区块标题', lead: '添加区块简介', body: '区块正文'}[part];
|
||||
if (body) {
|
||||
this.contentEditable = 'true';
|
||||
this.setAttribute('aria-label', label);
|
||||
this.dataset.studioPlaceholder = label;
|
||||
} else {
|
||||
configureText(this, label, part === 'lead');
|
||||
}
|
||||
fields[part] = {node: this, initial: body ? this.innerHTML : this.textContent};
|
||||
});
|
||||
return {key: this.id, version: Number(this.dataset.studioSection), fields};
|
||||
}).get();
|
||||
|
||||
$doc.on('focusin.canvas', '[contenteditable]', function () {
|
||||
selectBody(this.dataset.studioPart === 'body' ? this : null);
|
||||
});
|
||||
$doc.on('selectionchange.canvas', rememberSelection);
|
||||
$doc.on('click.canvas auxclick.canvas', 'a', (event) => event.preventDefault());
|
||||
$doc.on('click.canvas', '[data-studio-part="body"] a, [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video', function (event) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const node = this;
|
||||
selectBody(node.closest('[data-studio-part="body"]'));
|
||||
editResource(node);
|
||||
});
|
||||
$doc.on('keydown.canvas', '[data-studio-hero-image]', function (event) {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
$(this).trigger('click');
|
||||
}
|
||||
});
|
||||
$doc.on('beforeinput.canvas', '[contenteditable="plaintext-only"]', (event) => {
|
||||
if (event.originalEvent?.inputType === 'insertParagraph' || event.originalEvent?.inputType === 'insertLineBreak') {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
$doc.on('paste.canvas drop.canvas', '[contenteditable]', (event) => {
|
||||
event.preventDefault();
|
||||
if (event.type === 'paste') {
|
||||
doc.execCommand('insertText', false, event.originalEvent.clipboardData.getData('text/plain'));
|
||||
}
|
||||
});
|
||||
$toolbar.prop('hidden', false);
|
||||
$studio.closest('.studio-layout').find('[data-canvas-jump]').prop('hidden', false);
|
||||
}
|
||||
|
||||
$frame.on('load', attachCanvas);
|
||||
if ($frame.contents().find('[data-studio-field]').length) attachCanvas();
|
||||
$studio.closest('.studio-layout').on('click', '[data-canvas-jump]', function () {
|
||||
const section = doc?.getElementById(this.dataset.canvasJump);
|
||||
const body = section?.querySelector('[data-studio-part="body"]');
|
||||
if (!body) return;
|
||||
$studio.get(0).scrollIntoView({block: 'start'});
|
||||
section.scrollIntoView({block: 'start'});
|
||||
body.focus({preventScroll: true});
|
||||
});
|
||||
});
|
||||
|
||||
$('[data-rich-canvas]').each(function () {
|
||||
@@ -169,11 +507,6 @@ jQuery(function ($) {
|
||||
document.execCommand(command, false, value);
|
||||
}
|
||||
|
||||
function safeLink(value) {
|
||||
return value && !/[\u0000-\u0020\\]/.test(value)
|
||||
&& (/^(https?:\/\/|mailto:|tel:|#\S)/i.test(value) || /^\/(?!\/)/.test(value));
|
||||
}
|
||||
|
||||
$canvas.on('click', 'a', (event) => event.preventDefault());
|
||||
$canvas.on('keyup mouseup focusout input', function () {
|
||||
const selection = window.getSelection();
|
||||
@@ -212,19 +545,8 @@ jQuery(function ($) {
|
||||
|
||||
$editor.on('click', '[data-rich-media]', function () {
|
||||
openPicker('', (file) => {
|
||||
const mime = file.mime;
|
||||
let $node;
|
||||
if (mime.startsWith('image/')) {
|
||||
const alt = window.prompt('图片替代文本(装饰图可留空)', file.label);
|
||||
if (alt === null) return;
|
||||
$node = $('<img>', {src: file.url, alt, loading: 'lazy'});
|
||||
} else if (mime.startsWith('video/') || mime.startsWith('audio/')) {
|
||||
const tag = mime.startsWith('video/') ? '<video>' : '<audio>';
|
||||
$node = $(tag, {src: file.url, controls: true, preload: 'metadata'});
|
||||
} else {
|
||||
$node = $('<a>', {href: file.url}).text(file.label);
|
||||
}
|
||||
edit('insertHTML', $node.prop('outerHTML'));
|
||||
const markup = mediaMarkup(file);
|
||||
if (markup) edit('insertHTML', markup);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user