diff --git a/app/Content/Database.php b/app/Content/Database.php index 06897d0..1561731 100644 --- a/app/Content/Database.php +++ b/app/Content/Database.php @@ -40,9 +40,13 @@ final class Database self::write(function (PDO $pdo) use ($root, $seed): void { $pdo->exec(file_get_contents($root . '/resources/schema.sql')); - if (!in_array('status', array_column($pdo->query('PRAGMA table_info(pages)')->fetchAll(), 'name'), true)) { + $pageColumns = array_column($pdo->query('PRAGMA table_info(pages)')->fetchAll(), 'name'); + if (!in_array('status', $pageColumns, true)) { $pdo->exec("ALTER TABLE pages ADD COLUMN status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('draft', 'published'))"); } + if (!in_array('image_scale', $pageColumns, true)) { + $pdo->exec('ALTER TABLE pages ADD COLUMN image_scale INTEGER NOT NULL DEFAULT 0'); + } $site = $pdo->prepare('INSERT OR IGNORE INTO site_settings (id, payload) VALUES (1, ?)'); $site->execute([self::json($seed['site'])]); @@ -92,6 +96,10 @@ final class Database if ($migration->rowCount() === 1) { DesignMigration::apply($pdo); } + $migration->execute(['restore_home_featured_products']); + if ($migration->rowCount() === 1) { + DesignMigration::restoreFeaturedProducts($pdo, $seed); + } }); } diff --git a/app/Content/DesignMigration.php b/app/Content/DesignMigration.php index c683f98..8237f0f 100644 --- a/app/Content/DesignMigration.php +++ b/app/Content/DesignMigration.php @@ -11,6 +11,8 @@ use PDO; final class DesignMigration { + private const DIRECTORY_SUMMARY = '

浏览来笙的建站工具、智能 DNS 和软件著作权服务。

查看产品与服务'; + public static function apply(PDO $pdo): void { $stock = json_decode(file_get_contents(dirname(__DIR__, 2) . '/resources/seed.json'), true, flags: JSON_THROW_ON_ERROR); @@ -40,7 +42,7 @@ final class DesignMigration '/assets/original/shnu-hero.webp', '', '/shnu-sc', '查看学生方案', 30]); $pdo->prepare("UPDATE sections SET body = ?, version = version + 1 WHERE page_slug = 'home' AND key = 'product' AND version = 0 AND body = ?") - ->execute(['

浏览来笙的建站工具、智能 DNS 和软件著作权服务。

查看产品与服务', $stockBody]); + ->execute([self::DIRECTORY_SUMMARY, $stockBody]); $choices = $pdo->query("SELECT page_slug, body FROM sections WHERE key = 'why' AND page_slug IN ('sc', 'shnu-sc')"); $updateChoice = $pdo->prepare("UPDATE sections SET body = ?, version = version + 1 WHERE page_slug = ? AND key = 'why'"); @@ -64,4 +66,18 @@ final class DesignMigration } } } + + public static function restoreFeaturedProducts(PDO $pdo, array $seed): void + { + $home = array_column($seed['pages'], null, 'slug')['home']; + $stockBody = Html::sanitize(array_column($home['sections'], 'body', 'key')['product']); + $doc = new DOMDocument('1.0', 'UTF-8'); + $doc->loadHTML('' . $stockBody, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET); + $projects = $doc->getElementsByTagName('article'); + $body = '
' . $doc->saveHTML($projects->item(0)) + . $doc->saveHTML($projects->item(1)) . '
'; + $pdo->prepare("UPDATE sections SET body = ?, version = version + 1 + WHERE page_slug = 'home' AND key = 'product' AND body = ?") + ->execute([Html::sanitize($body), self::DIRECTORY_SUMMARY]); + } } diff --git a/app/Content/Html.php b/app/Content/Html.php index f3d776e..b0163bf 100644 --- a/app/Content/Html.php +++ b/app/Content/Html.php @@ -8,6 +8,7 @@ use DOMDocument; use DOMElement; use DOMNode; use League\CommonMark\CommonMarkConverter; +use RuntimeException; final class Html { @@ -49,6 +50,37 @@ final class Html return str_replace(['

', '

'], ['

', '

'], $html); } + public static function applyCanvasEdits(string $body, array $edits): string + { + if (!array_is_list($edits) || count($edits) > 512) { + throw new RuntimeException('正文增量无效。'); + } + $size = strlen($body); + $cursor = 0; + $result = ''; + foreach ($edits as $edit) { + if (!is_array($edit) || !array_is_list($edit) || count($edit) !== 3) { + throw new RuntimeException('正文增量无效。'); + } + [$offset, $remove, $insert] = $edit; + if (!is_int($offset) || !is_int($remove) || !is_string($insert) + || $offset < $cursor || $offset > $size || $remove < 0 || $remove > $size - $offset) { + throw new RuntimeException('正文增量无效。'); + } + $result .= substr($body, $cursor, $offset - $cursor) . $insert; + $cursor = $offset + $remove; + if (strlen($result) > 300000) { + throw new RuntimeException('正文太长。'); + } + } + $result .= substr($body, $cursor); + if (strlen($result) > 300000 || !mb_check_encoding($result, 'UTF-8')) { + throw new RuntimeException('正文太长或编码无效。'); + } + + return $result; + } + public static function sanitize(string $html): string { $document = new DOMDocument('1.0', 'UTF-8'); diff --git a/app/Content/Repository.php b/app/Content/Repository.php index bc2d415..5f51f64 100644 --- a/app/Content/Repository.php +++ b/app/Content/Repository.php @@ -65,15 +65,19 @@ final class Repository { 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 = ?'); + image = ?, alt = ?, image_scale = ?, 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['image'], $data['alt'], $data['image_scale'], 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']); + if ($section['version'] === null) { + self::insertSection($pdo, $slug, $section['key'], $section); + } else { + self::updateSection($pdo, $slug, $section['key'], $section, $section['version']); + } } }); } @@ -97,19 +101,28 @@ final class Repository 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 { - $query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, position) - SELECT ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?'); - $query->execute([$page, $key, $title, '', $style, $body, $page]); - if ($query->rowCount() !== 1) { - throw new RuntimeException('此区块锚点已被使用。'); - } + self::insertSection($pdo, $page, $key, compact('title', 'style', 'body') + ['lead' => '']); self::touchPage($pdo, $page, structureChanged: true); }); } - public function arrangeSection(string $page, string $key, string $operation, int $version): void + private static function insertSection(PDO $pdo, string $page, string $key, array $data): void { - Database::write(function (PDO $pdo) use ($page, $key, $operation, $version): void { + $query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, position) + SELECT ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?'); + $query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $page]); + if ($query->rowCount() !== 1) { + throw new RuntimeException('此区块锚点已被使用。'); + } + } + + public function arrangeSection(string $page, string $key, string $operation, int $version, int $pageVersion): void + { + Database::write(function (PDO $pdo) use ($page, $key, $operation, $version, $pageVersion): void { + $current = $pdo->prepare('SELECT version FROM pages WHERE slug = ?'); + $current->execute([$page]); + $revision = $current->fetchColumn(); + self::checkVersion($revision !== false && (int) $revision === $pageVersion ? 1 : 0); if ($operation === 'delete') { $query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?'); $query->execute([$page, $key, $version]); @@ -118,13 +131,15 @@ final class Repository return; } - $query = $pdo->prepare('SELECT key FROM sections WHERE page_slug = ? ORDER BY position, key'); + $query = $pdo->prepare('SELECT key, version FROM sections WHERE page_slug = ? ORDER BY position, key'); $query->execute([$page]); - $keys = $query->fetchAll(PDO::FETCH_COLUMN); - $index = array_search($key, $keys, true); - if ($index === false) { + $revisions = $query->fetchAll(PDO::FETCH_KEY_PAIR); + if (!array_key_exists($key, $revisions)) { throw new RuntimeException('找不到该区块。'); } + self::checkVersion((int) $revisions[$key] === $version ? 1 : 0); + $keys = array_map('strval', array_keys($revisions)); + $index = array_search($key, $keys, true); $other = $index + ($operation === 'up' ? -1 : 1); if (!isset($keys[$other])) { return; @@ -134,7 +149,7 @@ final class Repository foreach ($keys as $position => $section) { $query->execute([$position, $page, $section]); } - self::touchPage($pdo, $page); + self::touchPage($pdo, $page, structureChanged: true); }); } diff --git a/app/Controller/AdminController.php b/app/Controller/AdminController.php index 16a0466..42e2034 100644 --- a/app/Controller/AdminController.php +++ b/app/Controller/AdminController.php @@ -192,6 +192,9 @@ class AdminController } $data['name'] = $request->post('name') === null ? $page['name'] : $this->input($request, 'name'); $data['status'] = $request->post('status') === null || $slug === 'home' ? $page['status'] : $this->input($request, 'status'); + $scale = $this->input($request, 'image_scale'); + $data['image_scale'] = $request->post('image_scale') === null ? (int) $page['image_scale'] + : (ctype_digit($scale) ? (int) $scale : -1); $data['actions'] = []; $validButtons = true; foreach ([1, 2] as $index) { @@ -211,6 +214,7 @@ class AdminController ($data['status'] === 'published' && $data['description'] === '') || mb_strlen($data['description']) > 300 || $data['heading'] === '' || mb_strlen($data['heading'] . $data['accent']) > 110 || mb_strlen($data['lead']) > 600 || mb_strlen($data['alt']) > 200 || + !in_array($data['image_scale'], [0, 25, 40, 50, 60, 75, 85, 100], true) || strlen($data['image']) > 1000 || ($data['image'] !== '' && !Html::url($data['image'], true)) || !$validButtons) { throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。'); } @@ -224,7 +228,7 @@ class AdminController } return $this->render($request, 'admin-page', [ - 'title' => '编辑 ' . $page['name'], 'page' => $page, 'error' => $error, 'saved' => $request->get('saved') === '1', + 'title' => '编辑 ' . $page['name'], 'page' => $page, 'wideAdmin' => true, 'error' => $error, 'saved' => $request->get('saved') === '1', ], $error !== '' ? 422 : 200); } @@ -269,7 +273,7 @@ class AdminController return []; } $changes = is_string($payload) ? json_decode($payload, true) : null; - if (!is_array($changes) || !array_is_list($changes) || count($changes) > count($sections)) { + if (!is_array($changes) || !array_is_list($changes) || count($changes) > count($sections) + 50) { throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。'); } $available = array_column($sections, null, 'key'); @@ -278,13 +282,21 @@ class AdminController $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 === []) { + $isNew = is_array($change) && array_key_exists('version', $change) && $version === null; + if (!is_string($key) || isset($updates[$key]) || !is_array($fields) || $fields === [] + || ($isNew ? (isset($available[$key]) || !preg_match('/^block-[a-f0-9]{32}$/D', $key)) + : (!isset($available[$key]) || !is_int($version) || $version !== (int) $available[$key]['version']))) { throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。'); } - $section = $available[$key]; - unset($available[$key]); + $section = $available[$key] ?? ['key' => $key, 'title' => '', 'lead' => '', 'body' => '', 'style' => 'plain']; foreach ($fields as $field => $value) { - if (!in_array($field, ['title', 'lead', 'body'], true) || !is_string($value)) { + if (!in_array($field, ['title', 'lead', 'body'], true)) { + throw new RuntimeException('画布内容无效。'); + } + if ($field === 'body' && is_array($value)) { + $value = Html::applyCanvasEdits($section['body'], $value); + } + if (!is_string($value)) { throw new RuntimeException('画布内容无效。'); } $section[$field] = trim($value); @@ -294,7 +306,7 @@ class AdminController $section['body'] = Html::sanitize($section['body']); } $section['version'] = $version; - $updates[] = $section; + $updates[$key] = $section; } return $updates; diff --git a/app/Controller/StudioController.php b/app/Controller/StudioController.php index 079e7c9..99219dc 100644 --- a/app/Controller/StudioController.php +++ b/app/Controller/StudioController.php @@ -16,9 +16,14 @@ use Webman\Http\UploadFile; final class StudioController extends AdminController { - private const BLOCKS = [ + public const BLOCKS = [ 'text' => ['正文', '

在这里输入区块内容。

'], - 'image' => ['图文', '

介绍图片内容,然后从媒体库插入图片。

'], + 'image' => ['图文', '

介绍主题

在这里说明图片或产品。

'], + 'banner' => ['横幅', '

用一句话介绍你的项目

简要说明项目能为访客做什么。

了解更多
'], + 'features' => ['特性卡片', '

特点一

介绍这个特点。

特点二

介绍这个特点。

特点三

介绍这个特点。

'], + 'quote' => ['引文', '

在这里填写引用或用户反馈。

'], + 'table' => ['对比表格', '
项目说明
项目一填写说明
项目二填写说明
'], + 'list' => ['步骤列表', '
  1. 填写第一步
  2. 填写第二步
  3. 填写第三步
'], 'cta' => ['行动按钮', '

说明下一步。

联系来笙

'], 'faq' => ['常见问题', '
请输入问题

请输入答案。

'], ]; @@ -86,7 +91,8 @@ final class StudioController extends AdminController if (!in_array($action, ['up', 'down', 'delete'], true)) { throw new RuntimeException('操作不可用。'); } - $repo->arrangeSection($slug, $key, $action, $this->version($request)); + $pageVersion = $this->input($request, 'page_version'); + $repo->arrangeSection($slug, $key, $action, $this->version($request), ctype_digit($pageVersion) ? (int) $pageVersion : -1); return $this->success($request, "/admin/pages/$slug#blocks"); } catch (RuntimeException $error) { diff --git a/app/view/admin-feedback.php b/app/view/admin-feedback.php index 24b64f6..62097b3 100644 --- a/app/view/admin-feedback.php +++ b/app/view/admin-feedback.php @@ -1,3 +1,3 @@ -

已保存。

+

已保存。

diff --git a/app/view/admin-layout.php b/app/view/admin-layout.php index f6bf11b..ac0dca9 100644 --- a/app/view/admin-layout.php +++ b/app/view/admin-layout.php @@ -41,7 +41,7 @@ $e = View::escape(...); -
+

从媒体库选择

diff --git a/app/view/admin-page.php b/app/view/admin-page.php index 0c5b7c8..3d98b21 100644 --- a/app/view/admin-page.php +++ b/app/view/admin-page.php @@ -1,6 +1,7 @@
-
+ +

页面画布

@@ -38,14 +95,26 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
+
-

直接编辑画布上的文字。点击图片、媒体、按钮或链接可修改属性。选中区块正文后可使用上方工具。

+

直接编辑画布文字。单击媒体调整宽度,双击替换。

编辑属性

+
@@ -59,37 +128,6 @@ $previewUrl = '/admin/pages/' . $slug . '/preview';
-
-

内容区块

-
    - $item): ?> -
  • -
    #
    -
    - - 区块设置 -
    - - - - - - -
    -
    -
  • - -
-
- - -
- - -
-
-
-

页面设置

@@ -99,21 +137,24 @@ $previewUrl = '/admin/pages/' . $slug . '/preview'; - - - - '首屏图片', 'name' => 'image', 'value' => $page['image']]) ?> - -
- 首屏按钮和页面目录 - - - - - -
+ $page['heading'], 'accent' => $page['accent'], 'lead' => $page['lead'], + 'image' => $page['image'], 'alt' => $page['alt'], 'image_scale' => $page['image_scale'], + 'quicklinks' => SiteDesign::linkText($page['quicklinks']), + ]; + foreach ([1, 2] as $index) { + $contentFields['label' . $index] = $page['actions'][$index - 1][1] ?? ''; + $contentFields['url' . $index] = $page['actions'][$index - 1][0] ?? ''; + } + ?> + $value): ?> + + + + + + diff --git a/app/view/page.php b/app/view/page.php index 1ece1de..848e266 100644 --- a/app/view/page.php +++ b/app/view/page.php @@ -25,17 +25,20 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' .

-

>>

+

>>

>

[$url, $label]): ?> - > + >
-
> +
> alt="" width="1448" height="1086" fetchpriority="high"> + + +
@@ -61,6 +64,12 @@ $field = static fn (string $name): string => $canvas ? ' data-studio-field="' . $section, 'moment' => $home && $section['key'] === 'about', 'canvas' => $canvas]) ?> + + +
diff --git a/app/view/section.php b/app/view/section.php index 115a103..21022b4 100644 --- a/app/view/section.php +++ b/app/view/section.php @@ -4,7 +4,7 @@ use App\Content\View; $e = View::escape(...); $canvas ??= false; ?> -
> +
>

>

diff --git a/public/assets/admin.css b/public/assets/admin.css index e4442b0..8b6cae3 100644 --- a/public/assets/admin.css +++ b/public/assets/admin.css @@ -54,7 +54,6 @@ .admin-form button:disabled, .admin-bar button:disabled { cursor: progress; opacity: .65; } .admin-form .ajax-feedback { margin: 0; } -.studio-layout { display: grid; grid-template-columns: minmax(0, 1.7fr) minmax(16rem, 1fr); gap: 1rem; align-items: start; } .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; } @@ -91,5 +90,53 @@ .picker-item { text-align: left; min-height: 44px; } .picker-item:hover { border-color: var(--accent); } @media (max-width: 65rem) { - .studio-layout { grid-template-columns: minmax(0, 1fr); } +} + +.admin-wrap.admin-wide { width: calc(100% - clamp(1rem, 3vw, 3rem)); } +.studio-layout { + display: grid; + align-items: start; + grid-template-columns: minmax(12rem, 15rem) minmax(0, 1fr); + grid-template-areas: "library workspace" "library settings"; + gap: .9rem; +} +.studio-library { grid-area: library; position: sticky; top: .75rem; max-height: calc(100vh - 1.5rem); overflow: auto; } +.studio-library h2 { font-size: 1.05rem; margin-bottom: .7rem; } +.studio-workspace { grid-area: workspace; min-width: 0; } +.studio-inspector { grid-area: settings; } +.studio-workspace .studio-preview { padding: clamp(.55rem, 1.25vw, 1rem); } +.studio-workspace .studio-frame-window { height: max(34rem, calc(100dvh - 16rem)); } +.studio-workspace .studio-preview h2 { font-size: 1.2rem; } +.studio-presets { display: grid; gap: .4rem; } +.studio-library :is(.studio-presets, .studio-layers) button:not(.button) { + width: 100%; + min-height: 2.75rem; + padding: .55rem .75rem; + margin: 0; + border: 1px solid var(--line); + border-radius: .45rem; + background: var(--white); + color: var(--ink); + text-align: left; +} +.studio-library button:not(.button):hover { border-color: var(--accent); color: var(--accent); } +.studio-insert-mode { margin-block: .45rem .15rem; font-size: .875rem; } +.studio-pending { padding: 0; margin: 0; list-style: none; } +.studio-pending li + li { margin-top: .3rem; } +.studio-presets [role="status"]:empty { margin: 0; } +.studio-layers { border-top: 1px solid var(--line); margin-top: .85rem; padding-top: .55rem; } +.studio-layers summary { cursor: pointer; font-weight: 620; } +.studio-layers[open] > summary { margin-bottom: .55rem; } +.studio-library .studio-layers > button + button { margin-top: .3rem; } +.studio-layers .studio-blocks li { display: grid; gap: .4rem; } +.studio-layers .studio-block-actions .button { min-height: 2.25rem; padding: .25rem .5rem; font-size: .8rem; } +.studio-media-sizing { position: absolute; z-index: 1; inset: auto .6rem .6rem auto; display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; padding: .45rem .6rem; max-width: calc(100% - 1.2rem); background: var(--accent-light); border: 1px solid var(--line); border-radius: .45rem; } +.studio-media-sizing select { margin-inline-start: .3rem; } +.studio-media-sizing .button { min-height: 2.2rem; padding: .25rem .7rem; } +@media (max-width: 54rem) { + .studio-layout { grid-template-columns: minmax(0, 1fr); grid-template-areas: "library" "workspace" "settings"; } + .studio-library { position: static; max-height: none; } + .studio-presets { grid-template-columns: repeat(auto-fit, minmax(5.35rem, 1fr)); } + .studio-insert-mode, .studio-presets [role="status"], .studio-pending { grid-column: 1 / -1; } + .studio-workspace .studio-frame-window { height: max(25rem, 64dvh); } } diff --git a/public/assets/admin.js b/public/assets/admin.js index 53e06d9..48dd3db 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -16,6 +16,18 @@ jQuery(function ($) { } }; + function clearSavedStatus() { + $('[data-save-confirmation]').prop('hidden', true); + } + + if (document.querySelector('[data-save-confirmation]')) { + const url = new URL(window.location.href); + if (url.searchParams.get('saved') === '1') { + url.searchParams.delete('saved'); + window.history.replaceState(window.history.state, '', url.href); + } + } + function refreshToken(response) { if (response?.csrf) { $('input[name="csrf"]').val(response.csrf); @@ -37,12 +49,17 @@ jQuery(function ($) { $feedback.prop('hidden', false).trigger('focus'); } + document.addEventListener('invalid', (event) => { + if (event.target.form?.method.toLowerCase() === 'post') clearSavedStatus(); + }, true); + $('form[method="post"]').on('submit', function (event) { 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; + clearSavedStatus(); const action = $form.attr('action'); const isLogin = action === '/admin/login'; const $submit = $form.find(':submit:enabled'); diff --git a/public/assets/site.css b/public/assets/site.css index f564b3d..efa686d 100644 --- a/public/assets/site.css +++ b/public/assets/site.css @@ -395,7 +395,7 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); } .hero-shnu-sc ~ #benefits .rich > ul li + li { margin-top: .35rem; } .hero-shnu-sc ~ #benefits .rich > ul li::marker { color: var(--accent); } .hero-shnu-sc ~ #benefits .rich > img { - width: 100%; + width: var(--studio-media-width, 100%); max-width: 100%; border-radius: var(--radius); box-shadow: 0 .75rem 2.25rem #101c341a; @@ -486,3 +486,71 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); } color: var(--muted); font: 400 1rem / 1.5 var(--sans); } + +.home-cursor { + display: inline-block; + width: .52em; + margin-inline-start: .08em; + font-family: var(--mono); + font-size: .7em; + animation: home-cursor-blink 1.1s steps(1, end) 5; +} +@keyframes home-cursor-blink { 50% { opacity: 0; } } + +.home-pipe-flow { + position: absolute; + inset: clamp(.45rem, 1.8vw, 1.7rem); + pointer-events: none; +} +.home-pipe-flow span { + position: absolute; + width: clamp(.3rem, .68vw, .63rem); + aspect-ratio: 1; + border-radius: 50%; + background: #e3fbff; + box-shadow: 0 0 .4rem .1rem #78d7ff, 0 0 .8rem .16rem #3882ff; + translate: -50% -50%; + animation: home-pipe-pulse 2.8s linear 2 both; +} +.home-pipe-flow span:nth-child(1) { + --pipe-start: 72% auto auto 27.4%; --pipe-turn: 64% auto auto 38.3%; --pipe-end: 59.1% auto auto 42.1%; +} +.home-pipe-flow span:nth-child(2) { + --pipe-start: 59.2% auto auto 64%; --pipe-turn: 64.2% auto auto 67.1%; --pipe-end: 70% auto auto 78.2%; + animation-delay: .35s; +} +.home-pipe-flow span:nth-child(3) { + --pipe-start: 42% auto auto 18.7%; --pipe-turn: 46.9% auto auto 23.4%; --pipe-end: 51% auto auto 29.8%; + animation-delay: .65s; +} +.home-pipe-flow span:nth-child(4) { + --pipe-start: 37% auto auto 77%; --pipe-turn: 42.5% auto auto 77%; --pipe-end: 47.7% auto auto 68.3%; + animation-delay: .9s; +} +@keyframes home-pipe-pulse { + 0%, 16% { inset: var(--pipe-start); opacity: 0; } + 21%, 67% { opacity: 1; } + 40% { inset: var(--pipe-turn); } + 72%, 100% { inset: var(--pipe-end); opacity: 0; } +} +@media (prefers-reduced-motion: reduce) { + .home-cursor { animation: none; } + .home-pipe-flow { display: none; } +} + +.studio-split { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1.5rem; align-items: center; } +.studio-split > img { width: 100%; } +.studio-banner { padding: clamp(1.25rem, 4vw, 3.25rem); border-radius: var(--radius); background: var(--accent-light); } +@media (max-width: 44rem) { .studio-split { grid-template-columns: 1fr; } } + +:where(img, video, audio, .hero-visual)[class*="studio-media-"] { max-width: 100%; } +:is(.rich, .hero-inner, .editor-preview) .studio-media-25 { --studio-media-width: 25%; width: var(--studio-media-width); } +:is(.rich, .hero-inner, .editor-preview) .studio-media-40 { --studio-media-width: 40%; width: var(--studio-media-width); } +:is(.rich, .hero-inner, .editor-preview) .studio-media-50 { --studio-media-width: 50%; width: var(--studio-media-width); } +:is(.rich, .hero-inner, .editor-preview) .studio-media-60 { --studio-media-width: 60%; width: var(--studio-media-width); } +:is(.rich, .hero-inner, .editor-preview) .studio-media-75 { --studio-media-width: 75%; width: var(--studio-media-width); } +:is(.rich, .hero-inner, .editor-preview) .studio-media-85 { --studio-media-width: 85%; width: var(--studio-media-width); } +:is(.rich, .hero-inner, .editor-preview) .studio-media-100 { --studio-media-width: 100%; width: var(--studio-media-width); } +.rich :is(img, video)[class*="studio-media-"] { height: auto; max-width: 100%; } +.hero-visual[class*="studio-media-"] { justify-self: center; } +[data-studio-editing] [data-studio-selected] { outline: 2px solid #4477f9; outline-offset: 3px; } diff --git a/public/assets/studio.js b/public/assets/studio.js index d8fc462..4b585e3 100644 --- a/public/assets/studio.js +++ b/public/assets/studio.js @@ -108,6 +108,77 @@ jQuery(function ($) { filter(); }); + function bodyEdits(original, edited) { + // Work in Unicode code points, then encode offsets in UTF-8 for PHP. + const before = Array.from(original); + const after = Array.from(edited); + const encoder = new TextEncoder(); + const anchorSize = 32; + let start = 0; + let beforeEnd = before.length; + let afterEnd = after.length; + while (start < beforeEnd && start < afterEnd && before[start] === after[start]) start++; + while (beforeEnd > start && afterEnd > start && before[beforeEnd - 1] === after[afterEnd - 1]) { + beforeEnd--; + afterEnd--; + } + if (beforeEnd === start && afterEnd === start) return []; + + const anchors = new Map(); + for (let index = start; index + anchorSize <= beforeEnd; index += anchorSize) { + const key = before.slice(index, index + anchorSize).join(''); + if (!anchors.has(key)) anchors.set(key, []); + anchors.get(key).push(index); + } + + const edits = []; + let oldIndex = start; + let newIndex = start; + let byteOffset = encoder.encode(before.slice(0, start).join('')).length; + function copy() { + const first = oldIndex; + while (oldIndex < beforeEnd && newIndex < afterEnd && before[oldIndex] === after[newIndex]) { + oldIndex++; + newIndex++; + } + byteOffset += encoder.encode(before.slice(first, oldIndex).join('')).length; + } + + function replace(oldEnd, newEnd) { + if (oldEnd === oldIndex && newEnd === newIndex) return; + const removed = encoder.encode(before.slice(oldIndex, oldEnd).join('')).length; + edits.push([byteOffset, removed, after.slice(newIndex, newEnd).join('')]); + byteOffset += removed; + oldIndex = oldEnd; + newIndex = newEnd; + } + + for (let scan = start; scan + anchorSize <= afterEnd && edits.length < 511; scan++) { + const matches = anchors.get(after.slice(scan, scan + anchorSize).join('')); + if (!matches) continue; + let low = 0; + let high = matches.length; + while (low < high) { + const middle = Math.floor((low + high) / 2); + if (matches[middle] < oldIndex) low = middle + 1; + else high = middle; + } + if (low === matches.length) continue; + let nextOld = matches[low]; + let nextNew = scan; + while (nextOld > oldIndex && nextNew > newIndex && before[nextOld - 1] === after[nextNew - 1]) { + nextOld--; + nextNew--; + } + replace(nextOld, nextNew); + copy(); + scan = newIndex - 1; + } + replace(beforeEnd, afterEnd); + + return edits; + } + $('[data-preview-studio]').each(function () { const $studio = $(this); const $frame = $studio.find('iframe'); @@ -116,7 +187,7 @@ jQuery(function ($) { const width = $window.width(); const height = $window.height(); if (!width || !height) return; - const viewport = $studio.hasClass('studio-phone') ? 390 : 1280; + const viewport = $studio.hasClass('studio-phone') ? 390 : Math.max(1280, width); const scale = Math.min(1, width / viewport); $window.addClass('has-scaled-preview'); $frame.css({ @@ -132,7 +203,17 @@ jQuery(function ($) { $(window).on('resize', fitPreview); } fitPreview(); - const $settings = $studio.closest('.studio-layout').find('.studio-inspector'); + const $layout = $studio.closest('.studio-layout'); + const $settings = $layout.find('.studio-inspector'); + const $sizing = $studio.find('[data-media-sizing]'); + const $width = $sizing.find('[data-media-width]'); + const availableWidths = Array.from($width.get(0).options, ({value}) => value).filter((value) => value !== '0'); + const sizeClasses = availableWidths.map((value) => 'studio-media-' + value); + const $presets = $layout.find('[data-canvas-presets]'); + const $templateStatus = $presets.find('[data-template-status]'); + const $pending = $presets.find('[data-template-pending]'); + const heroControls = new Map(); + let selectedMedia; $studio.on('click', '[data-preview-size]', function () { const $button = $(this); $studio.toggleClass('studio-phone', $button.data('preview-size') === 'phone'); @@ -157,12 +238,14 @@ jQuery(function ($) { let sections = []; let saveComplete = false; - function sectionChanges() { - return sections.flatMap(({key, version, fields}) => { + function sectionChanges(withEdits = true) { + return sections.flatMap(({key, version, fields, source}) => { const changes = {}; for (const [field, {node, initial}] of Object.entries(fields)) { const value = field === 'body' ? node.innerHTML : node.textContent; - if (value !== initial) changes[field] = value; + if (version === null || value !== initial) { + changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value; + } } return Object.keys(changes).length ? [{key, version, fields: changes}] : []; }); @@ -171,11 +254,11 @@ jQuery(function ($) { $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); + $layout.prop('inert', busy); $settings.prop('inert', busy); }); $(window).on('beforeunload', (event) => { - if (!saveComplete && (sectionChanges().length || JSON.stringify(settingsSnapshot()) !== savedSettings)) { + if (!saveComplete && (sectionChanges(false).length || JSON.stringify(settingsSnapshot()) !== savedSettings)) { event.preventDefault(); event.originalEvent.returnValue = ''; } @@ -184,7 +267,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', 'url', 'alt', 'poster']) { + for (const key of ['label', 'url', 'alt', 'poster', 'quicklinks']) { const visible = Object.hasOwn(values, key); $propertyForm.find('[data-property-row="' + key + '"]').prop('hidden', !visible); propertyInput(key).val(visible ? values[key] : ''); @@ -205,7 +288,7 @@ jQuery(function ($) { 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)) + if ((Object.hasOwn(result, 'url') && ((!result.url && !allowEmptyUrl) || (result.url && !safeLink(result.url, mime !== null)))) || (result.poster && !safeLink(result.poster, true))) { $propertyError.prop('hidden', false).text('请输入有效的站内地址或链接。媒体也可使用 HTTPS 地址。'); return; @@ -292,6 +375,7 @@ jQuery(function ($) { function syncImage() { const path = pageInput('image').val().trim(); const valid = safeLink(path, true); + setMediaWidth($visual.get(0), pageInput('image_scale').val()); $visual.prop('hidden', !valid).parent().toggleClass('hero-text-only', !valid); if (valid) $image.attr('src', path); else $image.removeAttr('src'); @@ -299,7 +383,8 @@ jQuery(function ($) { } $settings.find('[name="image"], [name="alt"]').on('input.canvas', syncImage); syncImage(); - $image.attr({tabindex: '0', role: 'button', 'aria-label': '编辑首屏图片'}).on('click', () => { + $image.attr({tabindex: '0', role: 'button', 'aria-label': '编辑首屏图片'}); + heroControls.set('image', () => { openProperties('首屏图片', {url: pageInput('image').val(), alt: pageInput('alt').val()}, ({url, alt}) => { pageInput('image').val(url); pageInput('alt').val(alt); @@ -314,12 +399,10 @@ jQuery(function ($) { 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); + $button.text($label.val()).attr('href', safeLink(url) ? url : '#').prop('hidden', !$label.val() && !url); } $label.add($url).on('input.canvas', sync); - $button.on('click', (event) => { - event.preventDefault(); + const editButton = () => { openProperties('首屏按钮', {label: $label.val(), url: $url.val()}, ({label, url}) => { if (Boolean(label) !== Boolean(url)) { $propertyError.prop('hidden', false).text('请同时填写按钮文案和链接,或将两项都留空。'); @@ -329,6 +412,11 @@ jQuery(function ($) { $url.val(url); sync(); }, null, true); + }; + heroControls.set(index, editButton); + $button.on('click', (event) => { + event.preventDefault(); + editButton(); }); sync(); }); @@ -366,6 +454,12 @@ jQuery(function ($) { $navigation.prop('hidden', !$navContent.children().length); } $navInput.on('input.canvas', syncNavigation); + heroControls.set('navigation', () => { + openProperties('本页目录', {quicklinks: $navInput.val()}, ({quicklinks}) => { + $navInput.val(quicklinks); + syncNavigation(); + }); + }); syncNavigation(); } @@ -403,6 +497,109 @@ jQuery(function ($) { }, (tag === 'img' ? 'image' : tag) + '/'); } + function registerSection(section, version = Number(section.dataset.studioSection)) { + const fields = {}; + for (const node of section.querySelectorAll('[data-studio-part]')) { + const part = node.dataset.studioPart; + const body = part === 'body'; + const label = {title: '区块标题', lead: '添加区块简介', body: '区块正文'}[part]; + if (body) { + node.contentEditable = 'true'; + node.setAttribute('aria-label', label); + node.dataset.studioPlaceholder = label; + } else { + configureText(node, label, part === 'lead'); + } + fields[part] = {node, initial: body ? node.innerHTML : node.textContent}; + } + const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from( + atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0) + )); + sections.push({key: section.id, version, fields, source}); + } + + function setMediaWidth(node, width) { + node.classList.remove(...sizeClasses); + if (availableWidths.includes(width)) node.classList.add('studio-media-' + width); + } + + function selectMedia(node) { + selectedMedia?.removeAttribute('data-studio-selected'); + selectedMedia = node; + if (!node) { + $sizing.prop('hidden', true); + return; + } + node.setAttribute('data-studio-selected', ''); + const width = node.hasAttribute('data-studio-hero-image') ? pageInput('image_scale').val() + : availableWidths.find((value) => node.classList.contains('studio-media-' + value)) || '0'; + $width.val(width); + $sizing.prop('hidden', false); + } + + function replaceMedia() { + if (!selectedMedia?.isConnected) return; + if (selectedMedia.hasAttribute('data-studio-hero-image')) heroControls.get('image')(); + else editResource(selectedMedia); + } + + $width.on('change', function () { + if (!selectedMedia?.isConnected) return; + const hero = selectedMedia.hasAttribute('data-studio-hero-image'); + if (hero) pageInput('image_scale').val(this.value); + setMediaWidth(hero ? selectedMedia.parentElement : selectedMedia, this.value); + }); + $sizing.on('click', '[data-replace-media]', replaceMedia); + $layout.on('click', '[data-hero-control]', function () { + heroControls.get(this.dataset.heroControl)?.(); + }); + $presets.on('mousedown', '[data-canvas-template]', (event) => event.preventDefault()); + $presets.on('click', '[data-canvas-template]', function () { + const markup = $presets.find('template[data-preset="' + this.dataset.canvasTemplate + '"]').get(0).innerHTML; + if ($presets.find('[data-template-inline]').prop('checked')) { + if (!activeBody) { + $templateStatus.text('先在画布中选择要插入的区块正文。'); + return; + } + // Insert at the saved caret without replacing any selected text. + const insertion = savedRange?.cloneRange(); + insertion?.collapse(false); + editBody(activeBody, insertion, 'insertHTML', markup); + $templateStatus.text('已插入当前正文。'); + return; + } + if (sections.filter(({version}) => version === null).length >= 50) { + $templateStatus.text('请先保存,再添加更多区块。'); + return; + } + const end = doc.querySelector('[data-studio-section-end]'); + const section = end.content.firstElementChild.cloneNode(true); + const id = 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join(''); + section.id = id; + const title = section.querySelector('[data-studio-part="title"]'); + title.id = 'heading-' + id; + title.textContent = this.textContent.trim(); + section.setAttribute('aria-labelledby', title.id); + section.querySelector('[data-studio-part="body"]').innerHTML = markup; + end.before(section); + registerSection(section, null); + section.scrollIntoView({block: 'start'}); + section.querySelector('[data-studio-part="body"]').focus({preventScroll: true}); + const $cancel = $('