Add canvas element tools and categorized article editing

This commit is contained in:
2026-11-21 22:24:58 +08:00
parent 6efcdefadf
commit a5b3408358
45 changed files with 1607 additions and 660 deletions
+267 -49
View File
@@ -62,6 +62,7 @@ jQuery(function ($) {
});
}
$picker.on('studio:pick', (_event, type, callback) => openPicker(type, callback));
$picker.on('input', '[data-media-query]', renderPicker);
$picker.on('click', '[data-close-picker]', () => $picker.get(0).close());
$picker.on('click', '.picker-item', function () {
@@ -260,6 +261,17 @@ jQuery(function ($) {
const $studio = $(this);
const $frame = $studio.find('iframe');
const $window = $studio.find('.studio-frame-window');
const $layout = $studio.closest('.studio-layout');
const $settings = $layout.find('.studio-inspector');
const $sizing = $studio.find('[data-media-sizing]');
const $elementTools = $studio.find('[data-element-tools]');
const heroOrOptional = '[data-studio-field="accent"], [data-studio-field="lead"], [data-studio-part="lead"], [data-studio-action], [data-studio-nav-index]';
const bodyElements = 'a, article, blockquote, details, div, dl, dt, dd, figure, h1, h2, h3, h4, h5, h6, hr, li, ol, p, pre, table, ul';
const mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video';
const $handle = $studio.find('[data-media-handle]');
const $mediaSize = $sizing.find('[data-media-size]');
const mediaWidthClass = /^studio-media-\d+$/;
function fitPreview() {
const width = $window.width();
const height = $window.height();
@@ -273,24 +285,22 @@ jQuery(function ($) {
left: (width - viewport * scale) / 2,
transform: 'scale(' + scale + ')'
});
positionSelection();
}
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 selectedElement;
let selectedMedia;
let mediaDrag;
const selectionObserver = 'ResizeObserver' in window ? new ResizeObserver(positionSelection) : null;
if ('ResizeObserver' in window) {
new ResizeObserver(fitPreview).observe($window.get(0));
} else {
$(window).on('resize', fitPreview);
}
fitPreview();
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');
@@ -316,15 +326,20 @@ jQuery(function ($) {
let saveComplete = false;
function sectionChanges(withEdits = true) {
return sections.flatMap(({key, version, fields, source}) => {
return sections.flatMap(({key, version, fields, source, template}) => {
const changes = {};
for (const [field, {node, initial}] of Object.entries(fields)) {
const value = field === 'body' ? node.innerHTML : node.textContent;
let value = field === 'body' ? node.innerHTML : node.textContent;
if (field === 'body' && node.contains(selectedElement)) {
const copy = node.cloneNode(true);
$(copy).find('[data-studio-selected]').removeAttr('data-studio-selected');
value = copy.innerHTML;
}
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}] : [];
return Object.keys(changes).length ? [{key, version, fields: changes, ...(template ? {template} : {})}] : [];
});
}
@@ -459,6 +474,11 @@ jQuery(function ($) {
$image.attr('alt', pageInput('alt').val());
}
$settings.find('[name="image"], [name="alt"]').on('input.canvas', syncImage);
heroControls.set('remove-image', () => {
pageInput('alt').val('');
pageInput('image_scale').val(0);
pageInput('image').val('').trigger('input');
});
syncImage();
$image.attr({tabindex: '0', role: 'button', 'aria-label': '编辑首屏图片'});
heroControls.set('image', () => {
@@ -491,7 +511,7 @@ jQuery(function ($) {
}, null, true);
};
heroControls.set(index, editButton);
$button.on('click', (event) => {
$button.on('dblclick studio:properties', (event) => {
event.preventDefault();
editButton();
});
@@ -513,7 +533,8 @@ jQuery(function ($) {
const link = doc.createElement('a');
link.href = safeLink(url) ? url : '#';
link.textContent = label || url;
link.addEventListener('click', (event) => {
link.dataset.studioNavIndex = index;
$(link).on('dblclick studio:properties', (event) => {
event.preventDefault();
openProperties('本页目录链接', {label, url}, (next) => {
if (!next.label || /[|\r\n]/.test(next.label)) {
@@ -530,6 +551,14 @@ jQuery(function ($) {
}
$navigation.prop('hidden', !$navContent.children().length);
}
heroControls.set('change-nav', (index, copy) => {
const lines = navLines();
if (copy && $navContent.children().length >= 20) return null;
lines.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [lines[index]] : []));
$navInput.val(lines.join('\n'));
syncNavigation();
return $navContent.find('[data-studio-nav-index="' + (index + 1) + '"]').get(0);
});
$navInput.on('input.canvas', syncNavigation);
heroControls.set('navigation', () => {
openProperties('本页目录', {quicklinks: $navInput.val()}, ({quicklinks}) => {
@@ -592,48 +621,230 @@ jQuery(function ($) {
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});
sections.push({key: section.id, version, fields, source, template: section.dataset.studioTemplate});
}
function setMediaWidth(node, width) {
node.classList.remove(...sizeClasses);
if (availableWidths.includes(width)) node.classList.add('studio-media-' + width);
for (const token of Array.from(node.classList).filter((name) => mediaWidthClass.test(name))) {
node.classList.remove(token);
}
if (Number(width)) node.classList.add('studio-media-' + width);
else if (!node.classList.length) node.removeAttribute('class');
}
function selectMedia(node) {
selectedMedia?.removeAttribute('data-studio-selected');
selectedMedia = node;
if (!node) {
$sizing.prop('hidden', true);
function sizingTarget() {
if (!selectedMedia?.isConnected) return null;
return selectedMedia.hasAttribute('data-studio-hero-image') ? selectedMedia.parentElement : selectedMedia;
}
function frameScale() {
const frame = $frame.get(0);
return frame.getBoundingClientRect().width / frame.offsetWidth;
}
function previewBounds(node) {
const frame = $frame.get(0).getBoundingClientRect();
const container = $window.get(0);
const origin = container.getBoundingClientRect();
const bounds = node.getBoundingClientRect();
const scale = frameScale();
const x = frame.left - origin.left - container.clientLeft;
const y = frame.top - origin.top - container.clientTop;
return {
left: x + bounds.left * scale, right: x + bounds.right * scale,
top: y + bounds.top * scale, bottom: y + bounds.bottom * scale,
width: bounds.width * scale, height: bounds.height * scale,
};
}
function positionSelection() {
const container = $window.get(0);
const node = sizingTarget();
if (node) {
const bounds = previewBounds(node);
const y = (bounds.top + bounds.bottom) / 2;
const visible = bounds.width > 0 && y >= 0 && y <= container.clientHeight
&& bounds.right > 0 && bounds.right <= container.clientWidth + 1;
$handle.prop('hidden', !mediaDrag && !visible);
$handle.css({left: Math.min(bounds.right, container.clientWidth - 11), top: y});
} else {
$handle.prop('hidden', true);
}
if (!selectedElement?.isConnected) {
$elementTools.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);
const bounds = previewBounds(selectedElement);
const visible = bounds.width > 0 && bounds.height > 0 && bounds.right > 0
&& bounds.left < container.clientWidth && bounds.bottom > 0 && bounds.top < container.clientHeight;
$elementTools.prop('hidden', !visible);
if (!visible) return;
const maxX = container.clientWidth - $elementTools.outerWidth() - 5;
const height = $elementTools.outerHeight();
const above = bounds.top - height - 5;
const below = bounds.bottom + 5;
const y = above >= 5 || below + height > container.clientHeight ? above : below;
$elementTools.css({
left: Math.max(5, Math.min(bounds.left, maxX)),
top: Math.max(5, Math.min(y, container.clientHeight - height - 5)),
});
}
function currentMediaWidth(node) {
return Number(Array.from(node.classList).find((name) => mediaWidthClass.test(name))?.slice('studio-media-'.length)) || 0;
}
function showMediaWidth(width) {
$mediaSize.text(width ? width + '%' : '原始尺寸');
$handle.attr({'aria-valuenow': width || 100, 'aria-valuetext': width ? width + '%' : '原始尺寸'});
}
function editableBodyElement(node) {
const body = node.closest('[data-studio-part="body"]');
if (!body) return null;
const element = node.closest(bodyElements);
return element !== body && body.contains(element) ? element : null;
}
function selectElement(node) {
selectionObserver?.disconnect();
selectedElement?.removeAttribute('data-studio-selected');
selectedElement = node;
selectedMedia = node?.matches(mediaTargets) ? node : null;
$sizing.prop('hidden', !selectedMedia);
if (node) {
node.setAttribute('data-studio-selected', '');
const target = sizingTarget();
const nav = node.hasAttribute('data-studio-nav-index');
const inBody = node.closest('[data-studio-part="body"]') !== null;
const canCopy = inBody || (nav && $(node).siblings().length < 19);
const hasProperties = selectedMedia || node.matches('a');
$elementTools.find('[data-element-copy]').prop('hidden', !canCopy);
$elementTools.find('[data-element-properties]').prop('hidden', !hasProperties);
if (target) showMediaWidth(currentMediaWidth(target));
selectionObserver?.observe(target || node);
}
positionSelection();
}
function changeElement(copy) {
const node = selectedElement;
if (!node?.isConnected) return;
const {studioField, studioAction, studioNavIndex} = node.dataset;
const inBody = node.closest('[data-studio-part="body"]') !== null;
selectElement(null);
if (inBody) {
if (copy) {
const $clone = $(node.cloneNode(true));
$clone.find('[id]').addBack('[id]').removeAttr('id');
$(node).after($clone);
selectElement($clone.get(0));
} else {
$(node).remove();
savedRange = null;
}
} else if (studioNavIndex !== undefined) {
const next = heroControls.get('change-nav')(Number(studioNavIndex), copy);
if (copy && next) selectElement(next);
} else if (!copy) {
if (node.hasAttribute('data-studio-hero-image')) {
heroControls.get('remove-image')();
} else if (studioAction) {
pageInput('label' + studioAction).val('');
pageInput('url' + studioAction).val('').trigger('input');
} else if (studioField) {
pageInput(studioField).val('').trigger('input');
} else {
$(node).text('');
}
}
}
$elementTools.on('click', '[data-element-copy]', () => changeElement(true))
.on('click', '[data-element-delete]', () => changeElement(false))
.on('click', '[data-element-properties]', () => {
if (selectedMedia) replaceMedia();
else if (selectedElement?.matches('[data-studio-action], [data-studio-nav-index]')) {
$(selectedElement).triggerHandler('studio:properties');
} else if (selectedElement?.matches('a')) {
editResource(selectedElement);
}
}).on('keydown', (event) => {
if (event.key === 'Escape') selectElement(null);
});
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);
function measureMedia() {
const node = sizingTarget();
const width = currentMediaWidth(node);
const natural = node.getBoundingClientRect().width;
const classes = node.getAttribute('class');
setMediaWidth(node, 100);
const full = node.getBoundingClientRect();
setMediaWidth(node, 10);
const narrow = node.getBoundingClientRect();
if (classes === null) node.removeAttribute('class');
else node.setAttribute('class', classes);
const rightEdgeTravel = (full.right - narrow.right) / .9;
const available = rightEdgeTravel > full.width * .15 ? rightEdgeTravel : full.width;
return {available, initialWidth: width || Math.round(100 * natural / (full.width || natural || 1))};
}
function resizeMedia(width) {
const node = sizingTarget();
if (!node) return;
const next = width === null ? 0 : Math.round(Math.max(10, Math.min(100, width)));
if (selectedMedia.hasAttribute('data-studio-hero-image')) pageInput('image_scale').val(next);
if (next !== currentMediaWidth(node)) setMediaWidth(node, next);
showMediaWidth(next);
positionSelection();
}
$handle.on('pointerdown', function (event) {
const pointer = event.originalEvent;
if (pointer.button !== 0 || !sizingTarget()) return;
event.preventDefault();
this.focus({preventScroll: true});
mediaDrag = {...measureMedia(), x: pointer.clientX, scale: frameScale(), id: pointer.pointerId};
this.setPointerCapture(pointer.pointerId);
}).on('pointermove', (event) => {
const pointer = event.originalEvent;
if (!mediaDrag || mediaDrag.id !== pointer.pointerId || !mediaDrag.available) return;
if (pointer.clientX !== mediaDrag.x || mediaDrag.moved) {
mediaDrag.moved = true;
resizeMedia(mediaDrag.initialWidth + 100 * (pointer.clientX - mediaDrag.x) / (mediaDrag.available * mediaDrag.scale));
}
}).on('lostpointercapture', () => {
mediaDrag = null;
positionSelection();
}).on('keydown', (event) => {
if (!sizingTarget() || !['ArrowLeft', 'ArrowDown', 'ArrowRight', 'ArrowUp', 'Home', 'End'].includes(event.key)) return;
event.preventDefault();
const step = event.shiftKey ? 10 : 1;
const {initialWidth} = measureMedia();
const increase = ['ArrowRight', 'ArrowUp'].includes(event.key);
const next = {Home: 10, End: 100}[event.key] ?? initialWidth + (increase ? step : -step);
resizeMedia(next);
});
$sizing.on('click', '[data-replace-media]', replaceMedia);
$sizing.on('click', '[data-replace-media]', replaceMedia)
.on('click', '[data-reset-media]', () => resizeMedia(null));
$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;
const template = this.dataset.canvasTemplate;
if ($presets.find('[data-template-inline]').prop('checked')) {
if (template === 'articles') {
$templateStatus.text('分类文章需要作为独立区块添加。');
return;
}
if (!activeBody) {
$templateStatus.text('先在画布中选择要插入的区块正文。');
return;
@@ -658,6 +869,11 @@ jQuery(function ($) {
title.textContent = this.dataset.templateTitle;
section.setAttribute('aria-labelledby', title.id);
section.querySelector('[data-studio-part="body"]').innerHTML = markup;
if (template === 'articles') {
section.dataset.studioTemplate = template;
$('<p>', {class: 'empty-state', text: '保存页面后可在图层的区块设置中选择分类和展示方式。'})
.insertBefore($(section).find('[data-studio-part="body"]'));
}
end.before(section);
registerSection(section, null);
section.scrollIntoView({block: 'start'});
@@ -667,7 +883,7 @@ jQuery(function ($) {
$pending.prop('hidden', false);
$cancel.on('click', () => {
if (section.contains(activeBody)) selectBody(null);
if (section.contains(selectedMedia)) selectMedia(null);
if (section.contains(selectedElement)) selectElement(null);
section.remove();
sections = sections.filter(({key}) => key !== id);
$item.remove();
@@ -685,7 +901,7 @@ jQuery(function ($) {
$settings.find(':input').off('.canvas');
bindPage($doc);
selectBody(null);
selectMedia(null);
selectElement(null);
$pending.empty().prop('hidden', true);
sections = [];
$doc.find('[data-studio-section]').each((_, section) => registerSection(section));
@@ -693,30 +909,32 @@ jQuery(function ($) {
$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('selectionchange.canvas', rememberSelection).on('scroll.canvas', positionSelection);
$doc.on('click.canvas auxclick.canvas', 'a', (event) => event.preventDefault());
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();
selectBody(this.closest('[data-studio-part="body"]'));
selectMedia(this);
selectElement(this);
if (event.type === 'dblclick') replaceMedia();
});
$doc.on('click.canvas', '[data-studio-part="body"] a', function (event) {
$doc.on('click.canvas', (event) => {
const node = event.target;
const optional = node.closest?.(heroOrOptional);
selectElement(doc.getSelection()?.isCollapsed ? optional || editableBodyElement(node) : null);
});
$doc.on('dblclick.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);
if (!event.target.closest(mediaTargets)) editResource(this);
});
$doc.on('keydown.canvas', (event) => {
if (event.key === 'Escape') selectElement(null);
});
$doc.on('keydown.canvas', '[data-studio-hero-image]', function (event) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
selectMedia(this);
$width.trigger('focus');
selectElement(this);
$handle.trigger('focus');
}
});
$doc.on('beforeinput.canvas', '[contenteditable="plaintext-only"]', (event) => {