Enable in-place editing for page sections and media

This commit is contained in:
2026-11-21 21:06:34 +09:00
parent a910f03929
commit faba214971
11 changed files with 505 additions and 80 deletions
+3
View File
@@ -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; }
+5 -2
View File
@@ -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
View File
@@ -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
View File
@@ -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);
});
});