>= $e($section['title']) ?>
diff --git a/app/view/studio-templates.php b/app/view/studio-templates.php
new file mode 100644
index 0000000..a66c3a5
--- /dev/null
+++ b/app/view/studio-templates.php
@@ -0,0 +1,55 @@
+
+
+
搜索模板
+
+ 全部
+ [$category]): ?>
+ = $e($category) ?>
+
+
+
插入当前正文
+
+
+
没有找到匹配的模板。
+
+ [$category, $templates]): ?>
+
+ = $e($category) ?>
+
+ [$label, $markup]): ?>
+
+
+
+
+
+ = $e($label) ?>
+ 添加
+
+ = $markup ?>
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 添加到画布
+
+
diff --git a/public/assets/admin.css b/public/assets/admin.css
index e4442b0..f3308a3 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,116 @@
.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; z-index: 3; 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 .studio-layers button:not(.button), .studio-pending 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-workspace .studio-frame-window { height: max(25rem, 64dvh); }
+}
+
+.studio-template-search { display: grid; gap: .3rem; font-size: .9rem; font-weight: 600; }
+.studio-template-search input {
+ width: 100%;
+ min-height: 42px;
+ padding: .45rem .6rem;
+ color: var(--ink);
+ background: var(--white);
+ border: 1px solid var(--line);
+ border-radius: .5rem;
+}
+.studio-template-filters { display: flex; gap: .3rem; flex-wrap: wrap; margin-block: .25rem; }
+.studio-template-filters button {
+ min-height: 36px;
+ padding: .2rem .5rem;
+ color: var(--muted);
+ font-size: .825rem;
+ border: 1px solid var(--line);
+ border-radius: .35rem;
+ background: var(--white);
+}
+.studio-template-filters button[aria-pressed="true"] { border-color: #9bb5fa; color: var(--accent-deep); background: var(--accent-light); }
+.studio-template-group + .studio-template-group { margin-top: .9rem; }
+.studio-template-group h3 { margin: 0 0 .4rem; font-size: .9rem; font-weight: 650; }
+.studio-template-cards { display: grid; gap: .48rem; }
+.studio-template-card { min-width: 0; border: 1px solid var(--line); border-radius: .55rem; background: var(--white); }
+.studio-template-card:focus-within { border-color: var(--accent); }
+.studio-template-image {
+ display: block;
+ width: 100%;
+ padding: 0;
+ overflow: hidden;
+ border: 0;
+ border-radius: .5rem .5rem 0 0;
+ background: var(--paper);
+}
+.studio-template-image img { display: block; width: 100%; height: auto; aspect-ratio: 8 / 5; transition: transform .16s ease; }
+.studio-template-image:hover img, .studio-template-image:focus-visible img { transform: scale(1.07); }
+.studio-template-meta { display: flex; align-items: center; justify-content: space-between; gap: .3rem; padding: .3rem .38rem .3rem .55rem; font-size: .875rem; }
+.studio-template-meta .button { min-height: 33px; font-size: .8rem; flex: 0 0 auto; padding: .2rem .45rem; }
+.studio-template-peek {
+ position: fixed;
+ z-index: 2;
+ overflow: hidden;
+ pointer-events: none;
+ background: var(--white);
+ border: 1px solid #adbfdf;
+ border-radius: .65rem;
+ box-shadow: 0 14px 35px #142e5626;
+}
+.studio-template-peek img, .studio-template-dialog img { width: 100%; height: auto; aspect-ratio: 8 / 5; display: block; }
+.studio-template-peek p { padding: .5rem .8rem; margin: 0; font-size: .9rem; color: var(--ink); }
+.studio-template-dialog { width: min(90vw, 49rem); }
+.studio-template-dialog > img { border: 1px solid var(--line); border-radius: .55rem; }
+.studio-template-dialog > .actions { justify-content: flex-end; margin-top: .75rem; }
+
+@media (max-width: 54rem) {
+ .studio-template-groups { max-height: 44dvh; overflow-y: auto; padding: .2rem; }
+ .studio-template-cards { grid-template-columns: repeat(auto-fill, minmax(8.5rem, 1fr)); }
+ .studio-template-meta { flex-wrap: wrap; }
+ .studio-template-peek { display: none; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .studio-template-image img { transition: none; }
}
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..3b7e23f 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,83 @@ 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; }
+
+.rich .studio-intro { max-width: 47rem; }
+.rich .studio-intro h3, .rich .studio-cover h3 { font-size: clamp(1.75rem, 4vw, 2.8rem); }
+.rich .studio-cover { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.05fr); align-items: center; gap: clamp(1rem, 4vw, 3rem); background: var(--paper); padding: clamp(.8rem, 3vw, 2rem); border-radius: var(--radius); }
+.rich .studio-cover img { width: 100%; }
+.rich .studio-cover p { margin-bottom: .85rem; }
+.rich .studio-two-column { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; }
+.rich .studio-quick-nav { display: flex; flex-wrap: wrap; gap: .55rem 1rem; list-style: none; padding: .75rem; border: 1px solid var(--line); border-radius: .6rem; }
+.rich .studio-quick-nav a { display: inline-flex; align-items: center; min-height: 44px; padding-inline: .4rem; font-weight: 600; }
+@media (max-width: 44rem) {
+ .rich .studio-cover, .rich .studio-two-column { grid-template-columns: minmax(0, 1fr); }
+}
diff --git a/public/assets/studio.js b/public/assets/studio.js
index d8fc462..bc4a692 100644
--- a/public/assets/studio.js
+++ b/public/assets/studio.js
@@ -108,6 +108,154 @@ 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-canvas-presets]').each(function () {
+ const $gallery = $(this);
+ const $search = $gallery.find('[data-template-search]');
+ const $groups = $gallery.find('[data-template-group]');
+ const $filters = $gallery.find('[data-template-filter]');
+ const $peek = $gallery.find('[data-template-peek]');
+ const $dialog = $gallery.find('[data-template-dialog]');
+ const $use = $dialog.find('[data-template-use]');
+ let category = '';
+ let $selection;
+
+ function hidePeek() {
+ $peek.prop('hidden', true);
+ }
+
+ function filter() {
+ const query = String($search.val()).trim().toLowerCase();
+ let count = 0;
+ $groups.each(function () {
+ const $group = $(this);
+ const allowed = !category || this.dataset.templateGroup === category;
+ let groupCount = 0;
+ $group.find('[data-template-card]').each(function () {
+ const visible = allowed && this.dataset.templateSearchText.toLowerCase().includes(query);
+ $(this).prop('hidden', !visible);
+ if (visible) groupCount++;
+ });
+ $group.prop('hidden', groupCount === 0);
+ count += groupCount;
+ });
+ $gallery.find('[data-template-empty]').prop('hidden', count !== 0);
+ hidePeek();
+ }
+
+ $search.on('input', filter);
+ $filters.on('click', function () {
+ category = this.dataset.templateFilter;
+ $filters.attr('aria-pressed', 'false');
+ $(this).attr('aria-pressed', 'true');
+ filter();
+ });
+
+ $gallery.on('mouseenter focusin', '[data-template-preview]', function (event) {
+ if (event.type === 'mouseenter' && !matchMedia('(hover: hover)').matches) return;
+ const bounds = this.getBoundingClientRect();
+ const width = Math.min(430, window.innerWidth - bounds.right - 24);
+ if (width < 240) return;
+ const top = Math.max(12, Math.min(bounds.top, window.innerHeight - width * 0.625 - 56));
+ $peek.find('img').attr('src', $(this).find('img').attr('src'));
+ $peek.find('p').text(this.dataset.templateTitle);
+ $peek.css({width, top, left: bounds.right + 12}).prop('hidden', false);
+ });
+ $gallery.on('mouseleave focusout', '[data-template-preview]', hidePeek);
+ $gallery.closest('.studio-library').on('scroll', hidePeek);
+ $(window).on('scroll resize', hidePeek);
+
+ $gallery.on('click', '[data-template-preview]', function () {
+ hidePeek();
+ const $card = $(this).closest('[data-template-card]');
+ $selection = $card.find('[data-canvas-template]');
+ $dialog.find('h2').text(this.dataset.templateTitle);
+ $dialog.find('img').attr('src', $(this).find('img').attr('src'));
+ $use.prop('disabled', $selection.prop('disabled'));
+ $dialog.get(0).showModal();
+ });
+ $dialog.on('click', '[data-template-close]', () => $dialog.get(0).close());
+ $use.on('click', () => {
+ if (!$selection || $selection.prop('disabled')) return;
+ $dialog.get(0).close();
+ hidePeek();
+ $selection.trigger('click');
+ });
+ $gallery.on('studio:canvas-ready', () => {
+ if ($selection) $use.prop('disabled', $selection.prop('disabled'));
+ });
+ });
+
$('[data-preview-studio]').each(function () {
const $studio = $(this);
const $frame = $studio.find('iframe');
@@ -116,7 +264,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 +280,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 +315,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 +331,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 +344,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 +365,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 +452,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 +460,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 +476,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 +489,11 @@ jQuery(function ($) {
$url.val(url);
sync();
}, null, true);
+ };
+ heroControls.set(index, editButton);
+ $button.on('click', (event) => {
+ event.preventDefault();
+ editButton();
});
sync();
});
@@ -366,6 +531,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 +574,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.dataset.templateTitle;
+ 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 = $('
', {type: 'button', text: '取消新增:' + title.textContent});
+ const $item = $('').append($cancel).appendTo($pending);
+ $pending.prop('hidden', false);
+ $cancel.on('click', () => {
+ if (section.contains(activeBody)) selectBody(null);
+ if (section.contains(selectedMedia)) selectMedia(null);
+ section.remove();
+ sections = sections.filter(({key}) => key !== id);
+ $item.remove();
+ $pending.prop('hidden', !$pending.children().length);
+ $templateStatus.text('已取消新增区块。');
+ });
+ $templateStatus.text('已添加 ' + title.textContent + ' 区块。');
+ });
+
function attachCanvas() {
doc = $frame.get(0).contentDocument;
if (!doc?.querySelector('[data-studio-field]') || doc.documentElement.hasAttribute('data-studio-editing')) return;
@@ -411,40 +685,38 @@ jQuery(function ($) {
$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();
+ selectMedia(null);
+ $pending.empty().prop('hidden', true);
+ sections = [];
+ $doc.find('[data-studio-section]').each((_, section) => registerSection(section));
$doc.on('focusin.canvas', '[contenteditable]', function () {
selectBody(this.dataset.studioPart === 'body' ? this : null);
});
$doc.on('selectionchange.canvas', rememberSelection);
+ $doc.on('click.canvas', (event) => {
+ if (!event.target.closest?.('[data-studio-selected]')) selectMedia(null);
+ });
$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) {
+ const mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video';
+ $doc.on('click.canvas dblclick.canvas', mediaTargets, function (event) {
event.preventDefault();
event.stopPropagation();
- const node = this;
- selectBody(node.closest('[data-studio-part="body"]'));
- editResource(node);
+ selectBody(this.closest('[data-studio-part="body"]'));
+ selectMedia(this);
+ if (event.type === 'dblclick') replaceMedia();
+ });
+ $doc.on('click.canvas', '[data-studio-part="body"] a', function (event) {
+ event.preventDefault();
+ if ($(this).find('img, audio, video').length && event.target.closest('img, audio, video')) return;
+ selectBody(this.closest('[data-studio-part="body"]'));
+ editResource(this);
});
$doc.on('keydown.canvas', '[data-studio-hero-image]', function (event) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
- $(this).trigger('click');
+ selectMedia(this);
+ $width.trigger('focus');
}
});
$doc.on('beforeinput.canvas', '[contenteditable="plaintext-only"]', (event) => {
@@ -459,7 +731,9 @@ jQuery(function ($) {
}
});
$toolbar.prop('hidden', false);
- $studio.closest('.studio-layout').find('[data-canvas-jump]').prop('hidden', false);
+ $layout.find('[data-canvas-jump]').prop('hidden', false);
+ $layout.find('[data-canvas-template], [data-hero-control]').prop('disabled', false);
+ $presets.triggerHandler('studio:canvas-ready');
}
$frame.on('load', attachCanvas);
diff --git a/public/assets/template-previews/banner.webp b/public/assets/template-previews/banner.webp
new file mode 100644
index 0000000..3905501
Binary files /dev/null and b/public/assets/template-previews/banner.webp differ
diff --git a/public/assets/template-previews/cover.webp b/public/assets/template-previews/cover.webp
new file mode 100644
index 0000000..da72f63
Binary files /dev/null and b/public/assets/template-previews/cover.webp differ
diff --git a/public/assets/template-previews/cta.webp b/public/assets/template-previews/cta.webp
new file mode 100644
index 0000000..f246888
Binary files /dev/null and b/public/assets/template-previews/cta.webp differ
diff --git a/public/assets/template-previews/faq.webp b/public/assets/template-previews/faq.webp
new file mode 100644
index 0000000..97ba30e
Binary files /dev/null and b/public/assets/template-previews/faq.webp differ
diff --git a/public/assets/template-previews/features.webp b/public/assets/template-previews/features.webp
new file mode 100644
index 0000000..d547a30
Binary files /dev/null and b/public/assets/template-previews/features.webp differ
diff --git a/public/assets/template-previews/grid.webp b/public/assets/template-previews/grid.webp
new file mode 100644
index 0000000..235fd86
Binary files /dev/null and b/public/assets/template-previews/grid.webp differ
diff --git a/public/assets/template-previews/headline.webp b/public/assets/template-previews/headline.webp
new file mode 100644
index 0000000..2652960
Binary files /dev/null and b/public/assets/template-previews/headline.webp differ
diff --git a/public/assets/template-previews/image.webp b/public/assets/template-previews/image.webp
new file mode 100644
index 0000000..64857c7
Binary files /dev/null and b/public/assets/template-previews/image.webp differ
diff --git a/public/assets/template-previews/list.webp b/public/assets/template-previews/list.webp
new file mode 100644
index 0000000..a1bae43
Binary files /dev/null and b/public/assets/template-previews/list.webp differ
diff --git a/public/assets/template-previews/navigation.webp b/public/assets/template-previews/navigation.webp
new file mode 100644
index 0000000..8aa3aed
Binary files /dev/null and b/public/assets/template-previews/navigation.webp differ
diff --git a/public/assets/template-previews/quote.webp b/public/assets/template-previews/quote.webp
new file mode 100644
index 0000000..fa13e3f
Binary files /dev/null and b/public/assets/template-previews/quote.webp differ
diff --git a/public/assets/template-previews/table.webp b/public/assets/template-previews/table.webp
new file mode 100644
index 0000000..8c2c4e1
Binary files /dev/null and b/public/assets/template-previews/table.webp differ
diff --git a/public/assets/template-previews/text.webp b/public/assets/template-previews/text.webp
new file mode 100644
index 0000000..d98ca08
Binary files /dev/null and b/public/assets/template-previews/text.webp differ
diff --git a/resources/schema.sql b/resources/schema.sql
index 79ff502..c1f80b7 100644
--- a/resources/schema.sql
+++ b/resources/schema.sql
@@ -12,6 +12,7 @@ CREATE TABLE IF NOT EXISTS pages (
lead TEXT NOT NULL,
image TEXT NOT NULL,
alt TEXT NOT NULL,
+ image_scale INTEGER NOT NULL DEFAULT 0,
actions TEXT NOT NULL,
quicklinks TEXT NOT NULL,
partners TEXT NOT NULL,
diff --git a/tests/studio-browser.cjs b/tests/studio-browser.cjs
new file mode 100644
index 0000000..54a677e
--- /dev/null
+++ b/tests/studio-browser.cjs
@@ -0,0 +1,163 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
+
+const baseURL = process.env.LAYSENSE_TEST_URL || 'http://127.0.0.1:8787';
+const email = process.env.LAYSENSE_TEST_EMAIL;
+const password = process.env.LAYSENSE_TEST_PASSWORD;
+if (!email || !password) {
+ throw new Error('Set LAYSENSE_TEST_EMAIL and LAYSENSE_TEST_PASSWORD for a disposable test database.');
+}
+
+async function run(browser) {
+ const context = await browser.newContext({baseURL, viewport: {width: 1480, height: 960}, reducedMotion: 'reduce'});
+ const page = await context.newPage();
+ const errors = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.goto('/admin/login');
+ await page.locator('[name=email]').fill(email);
+ await page.locator('[name=password]').fill(password);
+ await page.locator('form button[type=submit]').click();
+ await page.waitForURL('**/admin');
+
+ const csrf = await page.locator('[name=csrf]').first().inputValue();
+ const slug = 'studio-browser-' + Date.now().toString(36);
+ async function post(path, values) {
+ const response = await context.request.post(path, {
+ form: {csrf, ...values},
+ headers: {'X-Requested-With': 'XMLHttpRequest'},
+ });
+ assert.equal(response.status(), 200, await response.text());
+ return response.json();
+ }
+
+ await post('/admin/new-page', {slug, name: '画布测试页'});
+ await post('/admin/page-blocks/' + slug, {operation: 'create', key: 'fixtures', preset: 'text'});
+ await post('/admin/pages/' + slug + '/fixtures', {
+ version: '0', title: '媒体和链接', lead: '', style: 'plain',
+ body: '
'
+ + '示例链接
'
+ + ' '
+ + ' ',
+ });
+ const editorPath = '/admin/pages/' + slug;
+ await page.goto(editorPath);
+ const version = await page.locator('#studio-page-settings [name=version]').inputValue();
+ await post(editorPath, {
+ version, name: '画布测试页', status: 'draft', title: '画布测试页',
+ description: '', heading: '画布测试页', accent: '', lead: '',
+ image: '/assets/original/home-hero.webp', alt: '首屏示例', image_scale: '0',
+ });
+ await page.reload();
+ const frame = page.frameLocator('iframe[title="可编辑页面画布"]');
+ const sizing = page.locator('[data-media-sizing]');
+ const properties = page.locator('[data-canvas-properties]');
+ const closeProperties = () => properties.locator('[data-property-close]').click();
+
+ const image = frame.locator('#fixtures img');
+ await image.click();
+ await sizing.waitFor({state: 'visible'});
+ assert.equal(await image.getAttribute('data-studio-selected'), '');
+ await sizing.locator('[data-media-width]').selectOption('50');
+ assert.match(await image.getAttribute('class'), /studio-media-50/);
+ await image.dblclick();
+ await properties.waitFor({state: 'visible'});
+ assert.equal(await properties.locator('h2').textContent(), '正文图片');
+ await properties.locator('[name=url]').fill('/assets/original/home-hero.webp');
+ await properties.locator('button[type=submit]').click();
+ assert.equal(await image.getAttribute('src'), '/assets/original/home-hero.webp');
+
+ const hero = frame.locator('[data-studio-hero-image]');
+ await page.locator('iframe[title="可编辑页面画布"]').evaluate((iframe) => iframe.contentWindow.scrollTo(0, 0));
+ await hero.click();
+ await sizing.waitFor({state: 'visible'});
+ assert.equal(await hero.getAttribute('data-studio-selected'), '');
+ await sizing.locator('[data-replace-media]').click();
+ assert.equal(await properties.locator('h2').textContent(), '首屏图片');
+ await closeProperties();
+
+ await frame.locator('#fixtures a').click();
+ await properties.waitFor({state: 'visible'});
+ assert.equal(await properties.locator('h2').textContent(), '正文链接');
+ await properties.locator('[name=url]').fill('/articles');
+ await properties.locator('button[type=submit]').click();
+ assert.equal(await frame.locator('#fixtures a').getAttribute('href'), '/articles');
+
+ for (const [tag, label] of [['video', '视频'], ['audio', '音频']]) {
+ const media = frame.locator('#fixtures ' + tag);
+ await media.dispatchEvent('dblclick');
+ await properties.waitFor({state: 'visible'});
+ assert.equal(await properties.locator('h2').textContent(), label);
+ await closeProperties();
+ }
+
+ const gallery = page.locator('[data-canvas-presets]');
+ assert.equal(await gallery.locator('[data-template-group]').count(), 6);
+ assert.equal(await gallery.locator('[data-template-card]').count(), 13);
+ const brokenPreviews = await gallery.locator('[data-template-card] img').evaluateAll(async (images) => {
+ for (const image of images) image.loading = 'eager';
+ await Promise.all(images.map((image) => image.decode()));
+ return images.filter((image) => image.naturalWidth !== 768).length;
+ });
+ assert.equal(brokenPreviews, 0);
+ await gallery.locator('[data-template-filter=cover]').click();
+ assert.equal(await gallery.locator('[data-template-card]:visible').count(), 2);
+ const cover = gallery.locator('[data-template-preview=cover]');
+ await cover.hover();
+ const peek = gallery.locator('[data-template-peek]');
+ await peek.waitFor({state: 'visible'});
+ assert((await peek.boundingBox()).width > (await cover.boundingBox()).width);
+ await cover.focus();
+ await page.keyboard.press('Enter');
+ const dialog = gallery.locator('[data-template-dialog]');
+ await dialog.waitFor({state: 'visible'});
+ assert.equal(await dialog.locator('h2').textContent(), '图文封面');
+ await dialog.locator('[data-template-use]').click();
+ await frame.locator('section[id^=block-] h2').filter({hasText: '图文封面'}).waitFor();
+
+ await gallery.locator('[data-template-filter=""]').click();
+ const search = gallery.locator('[data-template-search]');
+ await search.fill('does-not-exist');
+ await gallery.locator('[data-template-empty]').waitFor({state: 'visible'});
+ await search.fill('双栏');
+ assert.equal(await gallery.locator('[data-template-card]:visible').count(), 1);
+
+ await Promise.all([
+ page.waitForResponse((response) => response.url().endsWith(editorPath) && response.request().method() === 'POST' && response.ok()),
+ page.getByRole('button', {name: '保存页面', exact: true}).first().click(),
+ ]);
+ await page.locator('[data-save-confirmation]').waitFor({state: 'visible'});
+ await frame.locator('section[id^=block-] .studio-cover').waitFor();
+ assert.equal(await frame.locator('#fixtures a').getAttribute('href'), '/articles');
+ assert.equal(await frame.locator('#fixtures img').getAttribute('src'), '/assets/original/home-hero.webp');
+
+ const phone = await browser.newContext({
+ baseURL, viewport: {width: 390, height: 844}, isMobile: true, hasTouch: true,
+ storageState: await context.storageState(),
+ });
+ const phonePage = await phone.newPage();
+ phonePage.on('pageerror', (error) => errors.push(error.message));
+ await phonePage.goto(editorPath);
+ const phoneGallery = phonePage.locator('[data-canvas-presets]');
+ await phoneGallery.locator('[data-template-filter=cover]').tap();
+ await phoneGallery.locator('[data-template-preview=banner]').tap();
+ await phoneGallery.locator('[data-template-dialog]').waitFor({state: 'visible'});
+ assert.equal(await phoneGallery.locator('[data-template-dialog] h2').textContent(), '横幅');
+ assert.deepEqual(errors, []);
+ await phone.close();
+ await context.close();
+}
+
+(async () => {
+ const browser = await chromium.launch({executablePath: process.env.CHROMIUM_EXECUTABLE || undefined});
+ try {
+ await run(browser);
+ console.log('Passed Chromium canvas media/link interactions, template gallery, and persistence.');
+ } finally {
+ await browser.close();
+ }
+})().catch((error) => {
+ console.error(error);
+ process.exitCode = 1;
+});