Add live canvas layers, element styles and undo history

This commit is contained in:
2026-11-23 19:36:55 +08:00
parent bd1890c0dd
commit 3e842aa35c
21 changed files with 906 additions and 104 deletions
+596 -54
View File
@@ -308,7 +308,7 @@ jQuery(function ($) {
const buttonClasses = {solid: 'button-primary', outline: 'button-outline', underline: 'button-underline', plain: 'button-plain'};
const alignmentClasses = alignments.map((value) => 'studio-align-' + value);
const canvasFields = '[data-studio-field="heading"], [data-studio-field="accent"], [data-studio-field="lead"], [data-studio-part="title"], [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, progress, table, ul';
const bodyElements = 'a, article, blockquote, button, details, div, dl, dt, dd, figure, figcaption, h1, h2, h3, h4, h5, h6, hr, li, ol, p, pre, progress, section, summary, 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]');
@@ -352,6 +352,14 @@ jQuery(function ($) {
});
const $toolbar = $studio.find('[data-canvas-toolbar]');
const $commands = $toolbar.find('[data-canvas-command]');
const $format = $toolbar.find('[data-canvas-format]');
const $fontSize = $toolbar.find('[data-canvas-font-size]');
const $spacing = $studio.find('[data-canvas-spacing]');
const $spacingForm = $spacing.find('form');
const $layers = $layout.find('[data-canvas-layers]');
const $history = $toolbar.find('[data-canvas-history]');
const stylePattern = /^studio-style-([a-z]+)-(.+)$/;
const formatOptions = {weight: ['bold', 'normal'], slant: ['italic', 'normal'], strike: ['on', 'off']};
const $properties = $studio.find('[data-canvas-properties]');
const $propertyForm = $properties.find('form');
const $propertyError = $properties.find('[data-property-error]');
@@ -363,17 +371,134 @@ jQuery(function ($) {
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());
.filter(({name}) => !['csrf', 'canvas_sections', 'canvas_order'].includes(name));
let savedSettings = JSON.stringify(settingsSnapshot());
let dialogAction;
let doc;
let activeBody;
let savedRange;
let textRange;
let textHost;
let sections = [];
let initialOrder;
let saveComplete = false;
let syncPageFromInputs;
let spacingTarget;
function classesOf(node, textOnly = false) {
const result = {};
for (const name of node.classList) {
const prefix = name.match(stylePattern)?.[1];
if (prefix && (!textOnly || prefix === 'size' || Object.hasOwn(formatOptions, prefix))) result[prefix] = name;
}
return result;
}
function putStyle(node, property, value) {
const current = classesOf(node)[property];
if (current) node.classList.remove(current);
if (value !== '') node.classList.add('studio-style-' + property + '-' + value);
}
function readRuns(node) {
const runs = [];
function visit(parent, styles) {
for (const child of parent.childNodes) {
if (child.nodeType === 1 && child.localName !== 'br') {
visit(child, {...styles, ...classesOf(child, true)});
continue;
}
const text = child.nodeType === 3 ? child.data : child.localName === 'br' ? '\n' : '';
if (!text) continue;
const tokens = Object.values(styles).join(' ');
const last = runs.at(-1);
if (last?.[1] === tokens) last[0] += text;
else runs.push([text, tokens]);
}
}
visit(node, {});
return runs;
}
function plainText(node) {
return readRuns(node).map(([text]) => text).join('').trim();
}
function paintText(node, value, runs) {
const display = runs?.map(([text]) => text).join('').trim() === value ? runs : [[value, '']];
node.replaceChildren();
for (const [text, tokens] of display) {
const parent = tokens ? doc.createElement('span') : node;
if (tokens) {
parent.className = tokens;
node.append(parent);
}
text.split('\n').forEach((line, index) => {
if (index) parent.append(doc.createElement('br'));
if (line) parent.append(line);
});
}
}
function presentationOf(node, text = false) {
const classes = Object.values(classesOf(node)).join(' ');
const runs = text ? readRuns(node).filter(([part]) => part !== '') : [];
const formatted = runs.some(([part, tokens]) => tokens || part.includes('\n'));
return classes || formatted ? {classes, runs: formatted ? runs : []} : null;
}
function sectionPresentation({node, fields}) {
const presentation = {};
for (const [role, element] of Object.entries({section: node, title: fields.title.node, lead: fields.lead.node, body: fields.body.node})) {
const style = presentationOf(element, role === 'title' || role === 'lead');
if (style) presentation[role] = style;
}
return presentation;
}
function cleanBody(node) {
if (!node.contains(selectedElement) || node === selectedElement) return node.innerHTML;
const copy = node.cloneNode(true);
$(copy).find('[data-studio-selected]').removeAttr('data-studio-selected');
return copy.innerHTML;
}
function pagePresentation() {
return JSON.parse(pageInput('canvas_presentation').val());
}
function syncPagePresentation() {
const result = {};
$(doc).find('[data-studio-style-field]').each(function () {
const role = this.dataset.studioStyleField;
const style = presentationOf(this, this.hasAttribute('data-studio-field') || role.startsWith('action-'));
if (style) result[role] = style;
});
pageInput('canvas_presentation').val(JSON.stringify(result));
}
function remapPageStyles(prefix, indexes) {
syncPagePresentation();
const available = pagePresentation();
const next = Object.fromEntries(Object.entries(available).filter(([key]) => !key.startsWith(prefix + '-')));
indexes.forEach((old, index) => {
if (available[prefix + '-' + old]) next[prefix + '-' + index] = available[prefix + '-' + old];
});
pageInput('canvas_presentation').val(JSON.stringify(next));
}
function setPageStyle(node, style) {
node.classList.remove(...Object.values(classesOf(node)));
if (style?.classes) node.classList.add(...style.classes.split(' '));
}
function canvasOrder() {
return JSON.stringify(sections.filter(({fixed}) => !fixed).map(({key}) => key));
}
function sectionChanges(withEdits = true) {
const edits = sections.flatMap(({key, version, fields, source, template, copyOf, feed, initialFeed}) => {
const edits = sections.flatMap((entry) => {
const {key, version, fields, source, template, copyOf, feed, initialFeed, initialPresentation} = entry;
const changes = {};
const aligned = {};
let alignmentChanged = false;
@@ -383,36 +508,40 @@ jQuery(function ($) {
if (value) aligned[field] = value;
if (value !== initialAlignment) alignmentChanged = true;
}
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;
}
const value = field === 'body' ? cleanBody(node) : plainText(node);
if (version === null || value !== initial) {
changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value;
}
}
const feedChanged = feed && (version === null || JSON.stringify(feed) !== initialFeed);
if (!Object.keys(changes).length && !alignmentChanged && !feedChanged) return [];
const presentation = sectionPresentation(entry);
const presentationChanged = JSON.stringify(presentation) !== initialPresentation;
if (!Object.keys(changes).length && !alignmentChanged && !feedChanged && !presentationChanged) return [];
const edit = {key, version, fields: changes};
if (alignmentChanged || (version === null && Object.keys(aligned).length)) edit.alignments = aligned;
if (template) edit.template = template;
if (copyOf) edit.copyOf = copyOf;
if (feedChanged) edit.feed = feed;
if (presentationChanged || version === null && Object.keys(presentation).length) edit.presentation = presentation;
return [edit];
});
return [...edits, ...deletedSections];
}
$settings.on('studio:sync', () => pageInput('canvas_sections').val(JSON.stringify(sectionChanges())));
$settings.on('studio:sync', () => {
if (!doc || initialOrder === undefined) return;
syncPagePresentation();
pageInput('canvas_sections').val(JSON.stringify(sectionChanges()));
pageInput('canvas_order').val(canvasOrder() === initialOrder ? '' : canvasOrder());
});
$settings.on('studio:saved', () => { saveComplete = true; });
$settings.on('studio:busy', (_event, busy) => {
$layout.prop('inert', busy);
$settings.prop('inert', busy);
});
$(window).on('beforeunload', (event) => {
if (!saveComplete && (sectionChanges(false).length || JSON.stringify(settingsSnapshot()) !== savedSettings)) {
if (!saveComplete && (sectionChanges(false).length || initialOrder !== undefined && canvasOrder() !== initialOrder
|| JSON.stringify(settingsSnapshot()) !== savedSettings)) {
event.preventDefault();
event.originalEvent.returnValue = '';
}
@@ -452,8 +581,18 @@ jQuery(function ($) {
function rememberSelection() {
const selection = doc.getSelection();
if (selection.rangeCount && activeBody?.contains(selection.anchorNode) && activeBody.contains(selection.focusNode)) {
savedRange = selection.getRangeAt(0).cloneRange();
if (!selection.rangeCount) return;
const anchor = selection.anchorNode;
const host = (anchor.nodeType === 1 ? anchor : anchor.parentElement)?.closest('[contenteditable="true"]');
if (host?.contains(selection.focusNode)) {
textHost = host;
textRange = selection.getRangeAt(0).cloneRange();
if (host === activeBody) savedRange = textRange.cloneRange();
syncFormatControls();
} else if (textRange) {
textRange = null;
textHost = null;
syncFormatControls();
}
}
@@ -480,6 +619,144 @@ jQuery(function ($) {
rememberSelection();
}
function styleTarget(node) {
if (!node || node.closest('[data-studio-dynamic]') && !node.hasAttribute('data-studio-dynamic')) return null;
if (node.hasAttribute('data-studio-hero-image')) return node.parentElement;
return node.matches('[data-studio-section], [data-studio-style-field], [data-studio-part]')
|| node.closest('[data-studio-part="body"]') ? node : null;
}
function parentElement(node) {
const parent = node?.parentElement;
if (!parent || node.hasAttribute('data-studio-dynamic')) return null;
return editableBodyElement(parent)
|| parent.closest('[data-studio-part="body"], [data-studio-section], [data-studio-style-field]');
}
function formatTarget() {
if (textRange?.commonAncestorContainer.isConnected && textHost?.contains(textRange.commonAncestorContainer)) {
if (!textRange.collapsed) return textHost;
if (!selectedElement && doc.activeElement === textHost) {
const anchor = textRange.startContainer;
return styleTarget(editableBodyElement(anchor.parentElement || textHost) || textHost);
}
}
return styleTarget(selectedElement);
}
function formatState(node, property) {
const computed = doc.defaultView.getComputedStyle(node.nodeType === 1 ? node : node.parentElement);
if (property === 'weight') return Number(computed.fontWeight) >= 600 || computed.fontWeight === 'bold';
if (property === 'slant') return computed.fontStyle !== 'normal';
for (let element = node.nodeType === 1 ? node : node.parentElement; element; element = element.parentElement) {
if (classesOf(element).strike === 'studio-style-strike-off') return false;
if (doc.defaultView.getComputedStyle(element).textDecorationLine.includes('line-through')) return true;
}
return false;
}
function selectedText() {
if (!textRange || textRange.collapsed || !textHost?.contains(textRange.commonAncestorContainer) || !textHost?.isConnected) return [];
const nodes = [];
const walker = doc.createTreeWalker(textHost, 4);
while (walker.nextNode()) {
const node = walker.currentNode;
if (!textRange.intersectsNode(node)) continue;
const start = node === textRange.startContainer ? textRange.startOffset : 0;
const end = node === textRange.endContainer ? textRange.endOffset : node.length;
if (end > start) nodes.push({node, start, end});
}
return nodes;
}
function syncFormatControls() {
const target = doc && formatTarget();
$format.add($fontSize).prop('disabled', !target);
const sample = target && (selectedText()[0]?.node || target);
const size = sample ? doc.defaultView.getComputedStyle(sample.nodeType === 1 ? sample : sample.parentElement).fontSize : '';
if (!$fontSize.is(':focus')) $fontSize.val(size ? Math.round(parseFloat(size)) : '');
$format.each(function () {
$(this).attr('aria-pressed', String(Boolean(sample) && formatState(sample, this.dataset.canvasFormat)));
});
}
function applyTextStyle(property, value) {
const target = formatTarget();
if (!target) return;
const nodes = selectedText();
if (property !== 'size') {
const hasFormat = nodes.length ? nodes.every(({node}) => formatState(node, property)) : formatState(target, property);
value = formatOptions[property][Number(hasFormat)];
}
if (!nodes.length) {
putStyle(target, property, value);
} else if (value !== '') {
const spans = [];
for (const {node, start, end} of nodes) {
const parent = node.parentElement;
if (start === 0 && end === node.length && parent.matches('span') && parent.childNodes.length === 1 && parent !== textHost) {
putStyle(parent, property, value);
spans.push(parent);
continue;
}
if (end < node.length) node.splitText(end);
const piece = start > 0 ? node.splitText(start) : node;
const span = doc.createElement('span');
putStyle(span, property, value);
piece.before(span);
span.append(piece);
spans.push(span);
}
const range = doc.createRange();
range.setStart(spans[0].firstChild, 0);
range.setEnd(spans.at(-1).lastChild, spans.at(-1).lastChild.length);
doc.getSelection().removeAllRanges();
doc.getSelection().addRange(range);
textRange = range;
if (textHost === activeBody) savedRange = range.cloneRange();
}
syncFormatControls();
positionSelection();
}
$toolbar.on('mousedown', '[data-canvas-format]', (event) => event.preventDefault());
$format.on('click', function () { applyTextStyle(this.dataset.canvasFormat); });
$fontSize.on('change', function () {
if (this.validity.valid) applyTextStyle('size', this.value);
}).on('keydown', function (event) {
if (event.key === 'Enter') {
event.preventDefault();
this.blur();
}
});
$elementTools.on('click', '[data-element-spacing]', () => {
spacingTarget = styleTarget(selectedElement);
if (!spacingTarget) return;
const styles = classesOf(spacingTarget);
$spacingForm.find('input').each(function () {
this.value = styles[this.name]?.slice(('studio-style-' + this.name + '-').length) || '';
});
$spacing.get(0).showModal();
});
$elementTools.on('click', '[data-element-parent]', () => {
const parent = parentElement(selectedElement);
if (!parent) return;
doc.getSelection().removeAllRanges();
textRange = null;
textHost = null;
selectElement(parent);
});
$spacing.on('click', '[data-spacing-close]', () => $spacing.get(0).close());
$spacingForm.on('submit', (event) => {
event.preventDefault();
if (spacingTarget?.isConnected) {
$spacingForm.find('input').each(function () { putStyle(spacingTarget, this.name, this.value); });
}
$spacing.get(0).close();
positionSelection();
});
$toolbar.on('mousedown', '[data-canvas-command]', (event) => event.preventDefault());
$toolbar.on('click', '[data-canvas-command]', function () {
const command = this.dataset.canvasCommand;
@@ -502,13 +779,13 @@ jQuery(function ($) {
});
});
} else {
const commands = {heading: ['formatBlock', 'h3'], bold: ['bold'], list: ['insertUnorderedList']};
const commands = {heading: ['formatBlock', 'h3'], list: ['insertUnorderedList']};
edit(...commands[command]);
}
});
function configureText(node, label, placeholder = false) {
node.contentEditable = 'plaintext-only';
function configureText(node, label, placeholder = false, rich = true) {
node.contentEditable = rich ? 'true' : 'plaintext-only';
node.setAttribute('aria-label', label);
if (placeholder) node.dataset.studioPlaceholder = label;
}
@@ -528,9 +805,11 @@ jQuery(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()));
configureText(this, labels[field], ['accent', 'lead'].includes(field), field !== 'name');
$target.on('input', () => $input.val(plainText(this)));
$input.on('input.canvas', () => {
if ($input.val() !== plainText(this)) paintText(this, $input.val());
});
});
const $image = $doc.find('[data-studio-hero-image]');
@@ -562,16 +841,28 @@ jQuery(function ($) {
const $heroActions = $doc.find('.hero-actions');
const $actionsInput = pageInput('hero_actions');
let actions = JSON.parse($actionsInput.val()).map(([url, label, style, blank], index) => [
const readActions = () => JSON.parse($actionsInput.val()).map(([url, label, style, blank], index) => [
url, label, style || (index ? 'outline' : 'solid'), Boolean(blank),
]);
let actions = readActions();
function syncActions() {
$actionsInput.val(JSON.stringify(actions));
const presentation = pagePresentation();
$heroActions.empty();
for (const [index, [url, label, style, blank]] of actions.entries()) {
$('<a>', {href: url, class: 'button ' + buttonClasses[style], 'data-studio-action': index, text: label})
const role = 'action-' + index;
const $action = $('<a>', {href: url, class: 'button ' + buttonClasses[style],
'data-studio-action': index, 'data-studio-style-field': role})
.attr(blank ? {target: '_blank', rel: 'noopener noreferrer'} : {}).appendTo($heroActions);
const node = $action.get(0);
configureText(node, '首屏按钮文案');
setPageStyle(node, presentation[role]);
paintText(node, label, presentation[role]?.runs);
$action.on('input', () => {
actions[index][1] = plainText(node);
$actionsInput.val(JSON.stringify(actions));
});
}
}
function editAction(index) {
@@ -595,6 +886,9 @@ jQuery(function ($) {
heroControls.set('edit-action', editAction);
heroControls.set('change-action', (index, copy) => {
if (copy && actions.length >= 8) return null;
const order = actions.map((_, position) => position);
order.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [index] : []));
remapPageStyles('action', order);
actions.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [[...actions[index]]] : []));
syncActions();
return $heroActions.children().get(index + 1);
@@ -611,6 +905,7 @@ jQuery(function ($) {
const navLines = () => $navInput.val().split(/\r\n|[\n\r\v\f\u0085\u2028\u2029]/);
function syncNavigation() {
const lines = navLines();
const presentation = pagePresentation();
$navContent.empty();
for (const [index, line] of lines.entries()) {
if (!line.trim()) continue;
@@ -621,6 +916,8 @@ jQuery(function ($) {
link.href = safeLink(url) ? url : '#';
link.textContent = label || url;
link.dataset.studioNavIndex = index;
link.dataset.studioStyleField = 'nav-' + $navContent.children().length;
setPageStyle(link, presentation[link.dataset.studioStyleField]);
$(link).on('dblclick studio:properties', (event) => {
event.preventDefault();
openProperties('本页目录链接', {label, url}, (next) => {
@@ -641,6 +938,10 @@ jQuery(function ($) {
heroControls.set('change-nav', (index, copy) => {
const lines = navLines();
if (copy && $navContent.children().length >= 20) return null;
const ordinal = $navContent.find('[data-studio-nav-index="' + index + '"]').index();
const order = $navContent.children().get().map((_, position) => position);
order.splice(ordinal + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [ordinal] : []));
remapPageStyles('nav', order);
lines.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [lines[index]] : []));
$navInput.val(lines.join('\n'));
syncNavigation();
@@ -649,11 +950,15 @@ jQuery(function ($) {
$navInput.on('input.canvas', syncNavigation);
heroControls.set('remove-section-links', (key) => {
const anchor = '#' + key;
const navOrder = $navContent.children().get().flatMap((link, index) => link.getAttribute('href') === anchor ? [] : [index]);
const actionOrder = actions.flatMap(([url], index) => url === anchor ? [] : [index]);
remapPageStyles('nav', navOrder);
$navInput.val(navLines().filter((line) => {
const separator = line.indexOf('|');
return separator < 0 || line.slice(separator + 1).trim() !== anchor;
}).join('\n'));
syncNavigation();
remapPageStyles('action', actionOrder);
actions = actions.filter(([url]) => url !== anchor);
syncActions();
});
@@ -664,6 +969,28 @@ jQuery(function ($) {
});
});
syncNavigation();
syncPageFromInputs = () => {
const presentation = pagePresentation();
$doc.find('[data-studio-field]').each(function () {
const field = this.dataset.studioField;
paintText(this, pageInput(field).val(), presentation[field]?.runs);
});
$doc.find('[data-studio-style-field]').each(function () {
setPageStyle(this, presentation[this.dataset.studioStyleField]);
});
const values = JSON.parse(pageInput('alignments').val());
$doc.find('[data-studio-align-field]').each(function () {
this.classList.remove(...alignmentClasses);
if (values[this.dataset.studioAlignField]) this.classList.add('studio-align-' + values[this.dataset.studioAlignField]);
});
Object.keys(visibilityTargets).forEach((area) => pageInput('show_' + area).triggerHandler('change.canvas'));
pageInput('palette_id').triggerHandler('change.canvas');
actions = readActions();
syncActions();
syncNavigation();
syncImage();
};
syncPageFromInputs();
}
function editResource(node) {
@@ -748,12 +1075,14 @@ jQuery(function ($) {
} else if (!feed && !node.hidden) {
configureText(node, label, part === 'lead');
}
fields[part] = {node, initial: body ? node.innerHTML : node.textContent, initialAlignment: body ? '' : getAlignment(node)};
fields[part] = {node, initial: body ? node.innerHTML : plainText(node), initialAlignment: body ? '' : getAlignment(node)};
}
const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from(
atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0)
));
const entry = {node: section, key: section.id, version, fields, source, feed, initialFeed: JSON.stringify(feed), ...metadata};
const entry = {node: section, key: section.id, version, fields, source, feed, initialFeed: JSON.stringify(feed),
parent: section.parentNode, fixed: section.classList.contains('hero-directory-slot'), ...metadata};
entry.initialPresentation = JSON.stringify(sectionPresentation(entry));
sections.push(entry);
return entry;
}
@@ -849,7 +1178,7 @@ jQuery(function ($) {
if (!node) return null;
const hero = node.closest('[data-studio-align-field]');
if (hero) return hero;
return node.matches('[data-studio-part="title"], [data-studio-part="lead"]') || node.closest('[data-studio-part="body"]')
return node.matches('[data-studio-part="title"], [data-studio-part="lead"]') || node.parentElement?.closest('[data-studio-part="body"]')
? node : null;
}
@@ -862,37 +1191,45 @@ jQuery(function ($) {
function selectElement(node) {
selectionObserver?.disconnect();
selectedElement?.removeAttribute('data-studio-selected');
if (node && textHost && !node.contains(textHost) && !textHost.contains(node)) {
textHost = null;
textRange = null;
}
selectedElement = node;
const dynamic = node?.hasAttribute('data-studio-dynamic');
$elementTools.toggleClass('is-module', Boolean(dynamic)).find('[data-element-module-settings]').prop('hidden', !dynamic);
$elementTools.find('[data-element-spacing]').prop('hidden', !styleTarget(node));
$elementTools.find('[data-element-parent]').prop('hidden', !parentElement(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 inBody = Boolean(node.parentElement?.closest('[data-studio-part="body"]'));
const action = node.hasAttribute('data-studio-action');
const canCopy = dynamic || inBody || (nav && $(node).siblings().length < 19) || (action && $(node).siblings().length < 7);
const hasProperties = !dynamic && (selectedMedia || node.matches('a, progress'));
const aligned = dynamic ? null : alignmentTarget(node);
syncAlignmentButtons(aligned);
$elementTools.find('[data-element-copy]').prop('hidden', !canCopy);
const sectionRoot = node.hasAttribute('data-studio-section');
const deleteLabel = node.dataset.studioField === 'heading' ? '删除首屏'
: node.dataset.studioPart === 'title' ? '删除区块' : '删除';
: node.dataset.studioPart === 'title' || sectionRoot ? '删除区块' : '删除';
$elementTools.find('[data-element-delete]').attr({'aria-label': deleteLabel, title: deleteLabel})
.prop('hidden', !dynamic && !inBody && !selectedMedia && !node.matches(canvasFields));
.prop('hidden', !sectionRoot && !inBody && !selectedMedia && !node.matches(canvasFields));
$elementTools.find('[data-element-properties]').prop('hidden', !hasProperties);
if (target) showMediaWidth(currentMediaWidth(target));
selectionObserver?.observe(target || aligned || node);
}
syncFormatControls();
positionSelection();
}
function changeElement(copy) {
const node = selectedElement;
if (!node?.isConnected) return;
if (node.hasAttribute('data-studio-dynamic')) {
if (node.hasAttribute('data-studio-section')) {
changeModule(sections.find((section) => section.node === node), copy);
return;
}
@@ -906,7 +1243,7 @@ jQuery(function ($) {
changeModule(sections.find((section) => section.node === node.closest('[data-studio-section]')), false);
return;
}
const inBody = node.closest('[data-studio-part="body"]') !== null;
const inBody = Boolean(node.parentElement?.closest('[data-studio-part="body"]'));
selectElement(null);
if (inBody) {
if (copy) {
@@ -1001,6 +1338,7 @@ jQuery(function ($) {
fields.title.node.textContent = title;
fields.lead.node.textContent = moduleInput('module_lead').val().trim();
noteModule(node, '模块设置将在保存页面后更新。');
refreshLayerTitle(editedModule);
$moduleDialog.get(0).close();
positionSelection();
});
@@ -1009,13 +1347,70 @@ jQuery(function ($) {
return 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('');
}
function addPending(section) {
const $button = $('<button>', {type: 'button', text: '取消新增:' + section.fields.title.node.textContent});
section.$pending = $('<li>').append($button).appendTo($pending);
$pending.prop('hidden', false);
$button.on('click', () => removeSection(section));
function refreshLayerTitle(section) {
const title = plainText(section.fields.title.node) || '未命名区块';
$layers.children().filter((_, node) => node.dataset.layerKey === section.key).find('[data-layer-title]').text(title);
}
function renderLayers() {
const eligible = sections.filter(({fixed}) => !fixed);
const button = (label, operation, disabled = false) => $('<button>', {
type: 'button', class: 'button button-outline', text: label, 'data-layer-operation': operation, disabled
});
$layers.empty();
$pending.empty();
for (const entry of sections) {
const {key, fixed, version} = entry;
const index = eligible.indexOf(entry);
const $row = $('<li>', {'data-layer-key': key}).appendTo($layers);
const $label = $('<div>').append($('<strong>', {
'data-layer-title': '', text: plainText(entry.fields.title.node) || '未命名区块'
})).appendTo($row);
if (fixed || version === null) $label.append($('<small>').text(fixed ? '首屏目录' : '待保存'));
const $actions = $('<div>', {class: 'actions studio-block-actions'}).appendTo($row);
$actions.append(button('定位', 'jump'), button('上移', 'up', fixed || index === 0),
button('下移', 'down', fixed || index === eligible.length - 1), button('删除', 'delete'));
if (version !== null) {
$('<a>', {class: 'button button-outline', href: $settings.attr('action') + '/' + key, text: '区块设置'}).appendTo($actions);
} else {
const $cancel = $('<button>', {type: 'button', text: '取消新增:' + plainText(entry.fields.title.node)});
$('<li>').append($cancel).appendTo($pending);
$cancel.on('click', () => removeSection(entry));
}
}
$layout.find('[data-layers-empty]').prop('hidden', sections.length > 0);
$pending.prop('hidden', !$pending.children().length);
}
$layers.on('click', '[data-layer-operation]', function () {
const entry = sections.find(({key}) => key === this.closest('[data-layer-key]').dataset.layerKey);
if (!entry) return;
const operation = this.dataset.layerOperation;
if (operation === 'delete') {
changeModule(entry, false);
} else if (operation === 'jump') {
doc.getSelection().removeAllRanges();
textRange = null;
selectBody(entry.feed ? null : entry.fields.body.node);
$studio.get(0).scrollIntoView({block: 'start'});
entry.node.scrollIntoView({block: 'start'});
selectElement(entry.node);
} else {
const eligible = sections.filter(({fixed}) => !fixed);
const other = eligible[eligible.indexOf(entry) + (operation === 'up' ? -1 : 1)];
if (!other || entry.fixed) return;
if (operation === 'up') other.node.before(entry.node);
else other.node.after(entry.node);
const index = sections.indexOf(entry);
const swap = sections.indexOf(other);
[sections[index], sections[swap]] = [sections[swap], sections[index]];
renderLayers();
$layers.children().filter((_, node) => node.dataset.layerKey === entry.key)
.find('[data-layer-operation="' + operation + '"]:enabled, [data-layer-operation="jump"]').last().trigger('focus');
positionSelection();
}
});
function removeSection(section) {
if (section.node.contains(activeBody)) selectBody(null);
if (section.node.contains(selectedElement)) selectElement(null);
@@ -1023,8 +1418,7 @@ jQuery(function ($) {
section.node.remove();
sections = sections.filter((entry) => entry !== section);
heroControls.get('remove-section-links')(section.key);
section.$pending?.remove();
$pending.prop('hidden', !$pending.children().length);
renderLayers();
}
function scopeTemplateIds(root, prefix, oldKey = '') {
@@ -1065,8 +1459,8 @@ jQuery(function ($) {
clone.dataset.studioFeed = JSON.stringify(section.feed);
doc.querySelector('[data-studio-section-end]').before(clone);
const copyOf = section.copyOf || (section.version === null ? null : {key: section.key, version: section.version});
const entry = registerSection(clone, null, {template: copyOf ? null : section.template, copyOf});
addPending(entry);
registerSection(clone, null, {template: copyOf ? null : section.template, copyOf});
renderLayers();
noteModule(clone, '模块副本将在保存页面后生效。');
clone.scrollIntoView({block: 'start'});
selectElement(clone);
@@ -1222,13 +1616,127 @@ jQuery(function ($) {
}
end.before(section);
const entry = registerSection(section, null, {template});
addPending(entry);
renderLayers();
section.scrollIntoView({block: 'start'});
if (feed) selectElement(section);
else entry.fields.body.node.focus({preventScroll: true});
$templateStatus.text('已添加 ' + title.textContent + ' 区块。');
});
const history = [];
let historyIndex = 0;
let historyObserver;
let lastHistoryGroup;
let lastHistoryTime = 0;
function syncHistoryButtons() {
$history.filter('[data-canvas-history="undo"]').prop('disabled', historyIndex === 0);
$history.filter('[data-canvas-history="redo"]').prop('disabled', historyIndex >= history.length - 1);
}
function captureHistory(group = null) {
if (initialOrder === undefined) return;
syncPagePresentation();
const state = {
settings: settingsSnapshot(),
sections: sections.map((entry) => ({
entry, key: entry.key, classes: entry.node.className, feed: entry.feed,
note: entry.node.querySelector('[data-studio-module-note]')?.textContent ?? null,
parts: Object.fromEntries(Object.entries(entry.fields).map(([name, {node}]) =>
[name, [node.className, name === 'body' ? cleanBody(node) : node.innerHTML]])),
})),
deleted: [...deletedSections],
};
const key = JSON.stringify(state, (name, value) => name === 'entry' ? undefined : value);
if (history[historyIndex]?.key === key) return;
const time = performance.now();
history.splice(historyIndex + 1);
if (group && group === lastHistoryGroup && historyIndex > 0 && (group === mediaDrag || time - lastHistoryTime < 750)) {
history[historyIndex] = {state, key};
} else {
history.push({state, key});
}
// Keep a useful undo step even when a single page exceeds the normal history budget.
let size = history.reduce((sum, item) => sum + item.key.length, 0);
while (history.length > 2 && (history.length > 41 || size > 6_000_000)) {
size -= history.shift().key.length;
}
historyIndex = history.length - 1;
lastHistoryGroup = group;
lastHistoryTime = time;
syncHistoryButtons();
}
function stepHistory(direction) {
if (initialOrder === undefined) return false;
if (direction < 0) captureHistory();
const next = history[historyIndex + direction];
if (!next) return false;
historyIndex += direction;
lastHistoryGroup = null;
const {state} = next;
doc.getSelection().removeAllRanges();
textRange = null;
textHost = null;
selectBody(null);
selectElement(null);
const desired = new Set(state.sections.map(({entry}) => entry));
for (const entry of sections) {
if (!desired.has(entry)) entry.node.remove();
}
const end = doc.querySelector('[data-studio-section-end]');
const followingFixed = new Map();
for (const {entry, classes, parts, feed, note} of [...state.sections].reverse()) {
const {node, fields} = entry;
node.className = classes;
entry.feed = feed;
for (const [field, [fieldClasses, markup]] of Object.entries(parts)) {
const element = fields[field].node;
element.className = fieldClasses;
const current = element.innerHTML;
if (current !== markup) element.innerHTML = markup;
}
if (note === null) node.querySelector('[data-studio-module-note]')?.remove();
else noteModule(node, note);
if (entry.fixed) {
const following = followingFixed.get(entry.parent);
if (following) following.before(node);
else entry.parent.append(node);
followingFixed.set(entry.parent, node);
} else {
const following = followingFixed.get(end) || end;
following.before(node);
followingFixed.set(end, node);
}
}
sections = state.sections.map(({entry}) => entry);
deletedSections = [...state.deleted];
for (const {name, value} of state.settings) {
pageInput(name).val(value);
}
syncPageFromInputs();
renderLayers();
historyObserver?.takeRecords();
syncHistoryButtons();
$studio.find('[data-canvas-status]').text(direction < 0 ? '已撤销。' : '已重做。');
return true;
}
function historyShortcut(event) {
if (!(event.ctrlKey || event.metaKey) || event.altKey || event.target.closest?.('dialog, [type="search"]')) return;
const key = event.key.toLowerCase();
if (key !== 'z' && key !== 'y') return;
event.preventDefault();
stepHistory(key === 'y' || event.shiftKey ? 1 : -1);
}
$history.on('click', function () { stepHistory(this.dataset.canvasHistory === 'undo' ? -1 : 1); });
$layout.on('keydown.canvasHistory', historyShortcut);
$settings.on('input change', ':input', function (event) {
const group = event.type === 'input' && this.matches('input:not([type=hidden]), textarea') ? this : null;
captureHistory(group);
});
function attachCanvas() {
doc = $frame.get(0).contentDocument;
if (!doc?.querySelector('[data-studio-field]') || doc.documentElement.hasAttribute('data-studio-editing')) return;
@@ -1238,15 +1746,28 @@ jQuery(function ($) {
bindPage($doc);
selectBody(null);
selectElement(null);
$pending.empty().prop('hidden', true);
sections = [];
deletedSections = [];
$doc.find('[data-studio-section]').each((_, section) => registerSection(section));
renderLayers();
initialOrder = canvasOrder();
syncPagePresentation();
savedSettings = JSON.stringify(settingsSnapshot());
history.length = 0;
historyIndex = 0;
lastHistoryGroup = null;
captureHistory();
historyObserver?.disconnect();
historyObserver = new MutationObserver(() => captureHistory(mediaDrag || null));
historyObserver.observe(doc.querySelector('#main-content'), {
subtree: true, childList: true, characterData: true, attributes: true,
attributeFilter: ['class', 'href', 'target', 'rel', 'hidden', 'src', 'poster', 'alt', 'value', 'max'],
});
$doc.on('focusin.canvas', '[contenteditable]', function () {
selectBody(this.dataset.studioPart === 'body' ? this : null);
});
$doc.on('selectionchange.canvas', rememberSelection).on('scroll.canvas', positionSelection);
$doc.on('selectionchange.canvas mouseup.canvas keyup.canvas', rememberSelection).on('scroll.canvas', positionSelection);
$doc.on('click.canvas auxclick.canvas', 'a', (event) => event.preventDefault());
$doc.on('click.canvas dblclick.canvas', mediaTargets, function (event) {
event.preventDefault();
@@ -1270,7 +1791,8 @@ jQuery(function ($) {
return;
}
const field = node.closest?.(canvasFields);
selectElement(doc.getSelection()?.isCollapsed ? field || editableBodyElement(node) : null);
selectElement(doc.getSelection()?.isCollapsed ? field || editableBodyElement(node)
|| node.closest?.('[data-studio-part="body"], [data-studio-section], [data-studio-style-field]') : null);
});
$doc.on('dblclick.canvas', '[data-studio-part="body"] a', function (event) {
event.preventDefault();
@@ -1278,6 +1800,7 @@ jQuery(function ($) {
});
$doc.on('keydown.canvas', (event) => {
if (event.key === 'Escape') selectElement(null);
historyShortcut(event);
});
$doc.on('keydown.canvas', '[data-studio-dynamic]', function (event) {
if ((event.key === 'Enter' || event.key === ' ') && event.target === this) {
@@ -1299,6 +1822,35 @@ jQuery(function ($) {
event.preventDefault();
}
});
$doc.on('keydown.canvas', '[contenteditable="true"]', function (event) {
if (event.key === 'Enter' && !event.originalEvent?.isComposing && !event.ctrlKey && !event.metaKey && !event.altKey) {
event.preventDefault();
doc.execCommand('insertLineBreak');
}
});
$doc.on('beforeinput.canvas', '[contenteditable]', function (event) {
const kind = event.originalEvent?.inputType;
if (kind === 'historyUndo' || kind === 'historyRedo') {
event.preventDefault();
stepHistory(kind === 'historyUndo' ? -1 : 1);
return;
}
const style = {formatBold: 'weight', formatItalic: 'slant', formatStrikeThrough: 'strike'}[kind];
if (style && this.contentEditable === 'true') {
event.preventDefault();
rememberSelection();
applyTextStyle(style);
}
}).on('input.canvas', '[contenteditable]', function (event) {
rememberSelection();
if (this.dataset.studioPart === 'title') {
const entry = sections.find(({node}) => node === this.closest('[data-studio-section]'));
if (entry) refreshLayerTitle(entry);
}
const type = event.originalEvent?.inputType;
const typing = ['insertText', 'insertCompositionText', 'deleteContentBackward', 'deleteContentForward'].includes(type);
captureHistory(typing ? this : null);
});
$doc.on('paste.canvas drop.canvas', '[contenteditable]', (event) => {
event.preventDefault();
if (event.type === 'paste') {
@@ -1306,22 +1858,12 @@ jQuery(function ($) {
}
});
$toolbar.prop('hidden', false);
$layout.find('[data-canvas-jump]').prop('hidden', false);
$layout.find('[data-canvas-template], [data-canvas-element], [data-hero-control]').prop('disabled', false);
$presets.triggerHandler('studio:canvas-ready');
}
$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'});
if (section.hasAttribute('data-studio-dynamic')) selectElement(section);
else body.focus({preventScroll: true});
});
});
$('[data-rich-canvas]').each(function () {