', {href: url, class: 'button ' + buttonClasses[style], 'data-studio-action': index, text: label})
.attr(blank ? {target: '_blank', rel: 'noopener noreferrer'} : {}).appendTo($heroActions);
}
}
function editAction(index) {
const [url, label, style, blank] = actions[index] || ['', '', 'solid', false];
openProperties('首屏按钮', {label, url, buttonStyle: style, newTab: blank ? '1' : '0'}, (next) => {
if (!next.label || next.label.length > 70) {
$propertyError.prop('hidden', false).text('请填写不超过 70 个字符的按钮文案。');
return false;
}
selectElement(null);
actions[index] = [next.url, next.label, next.buttonStyle, next.newTab === '1'];
syncActions();
selectElement($heroActions.children().get(index));
});
}
$heroActions.on('dblclick studio:properties', '[data-studio-action]', function (event) {
event.preventDefault();
editAction(Number(this.dataset.studioAction));
});
heroControls.set('add-action', () => { if (actions.length < 8) editAction(actions.length); });
heroControls.set('edit-action', editAction);
heroControls.set('change-action', (index, copy) => {
if (copy && actions.length >= 8) return null;
actions.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [[...actions[index]]] : []));
syncActions();
return $heroActions.children().get(index + 1);
});
pageInput('palette_id').on('change.canvas', function () {
$doc.find('[data-page-palette]').remove();
if (this.value) $('', {rel: 'stylesheet', href: '/palette/' + this.value + '.css', 'data-page-palette': ''}).appendTo($doc.find('head'));
});
syncActions();
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.dataset.studioNavIndex = index;
$(link).on('dblclick studio:properties', (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);
}
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('remove-section-links', (key) => {
const anchor = '#' + key;
$navInput.val(navLines().filter((line) => {
const separator = line.indexOf('|');
return separator < 0 || line.slice(separator + 1).trim() !== anchor;
}).join('\n'));
syncNavigation();
actions = actions.filter(([url]) => url !== anchor);
syncActions();
});
heroControls.set('navigation', () => {
openProperties('本页目录', {quicklinks: $navInput.val()}, ({quicklinks}) => {
$navInput.val(quicklinks);
syncNavigation();
});
});
syncNavigation();
}
function editResource(node) {
const tag = node.localName;
if (tag === 'progress') {
openProperties('进度条', {value: node.getAttribute('value') || '0', max: node.getAttribute('max') || '100'}, ({value, max}) => {
if (!/^\d+$/.test(value) || !/^\d+$/.test(max) || Number(max) < 1 || Number(value) > Number(max)) {
$propertyError.prop('hidden', false).text('请输入不超过最大值的非负整数。');
return false;
}
node.max = Number(max);
node.value = Number(value);
node.textContent = Math.round(100 * node.value / node.max) + '%';
});
return;
}
if (tag === 'a') {
const product = node.parentElement.matches('.hero-directory');
const title = product ? node.querySelector(':scope > span') : null;
const note = product ? node.querySelector(':scope > small') : null;
const onlyChild = node.firstElementChild;
const text = title || (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') || ''};
if (title) values.note = note?.textContent || '';
values.newTab = node.target === '_blank' ? '1' : '0';
if (node.classList.contains('button')) {
values.buttonStyle = Object.keys(buttonClasses).find((style) => node.classList.contains(buttonClasses[style])) || 'plain';
}
openProperties(product ? '导航卡片' : '正文链接', values, ({label, note: description, url, newTab, buttonStyle}) => {
if (text && !label) {
$propertyError.prop('hidden', false).text('请填写链接文案。');
return false;
}
node.setAttribute('href', url);
if (newTab === '1') {
$(node).attr({target: '_blank', rel: 'noopener noreferrer'});
} else {
$(node).removeAttr('target rel');
}
if (buttonStyle) $(node).removeClass(Object.values(buttonClasses)).addClass(buttonClasses[buttonStyle]);
if (text && label !== values.label) text.textContent = label;
if (description !== undefined) {
if (note) $(note).text(description);
else if (description) $('').text(description).appendTo(node);
}
});
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 registerSection(section, version = Number(section.dataset.studioSection), metadata = {}) {
const fields = {};
const feed = section.dataset.studioFeed ? JSON.parse(section.dataset.studioFeed) : null;
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 (!feed && body) {
node.contentEditable = 'true';
node.setAttribute('aria-label', label);
node.dataset.studioPlaceholder = label;
} else if (!feed && !node.hidden) {
configureText(node, label, part === 'lead');
}
fields[part] = {node, initial: body ? node.innerHTML : node.textContent, 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};
sections.push(entry);
return entry;
}
function setMediaWidth(node, 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 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 x = getAlignment(node) === 'right' ? bounds.left : bounds.right;
const y = (bounds.top + bounds.bottom) / 2;
const visible = bounds.width > 0 && y >= 0 && y <= container.clientHeight
&& x >= 0 && x <= container.clientWidth + 1;
$handle.prop('hidden', !mediaDrag && !visible);
$handle.css({left: Math.max(11, Math.min(x, container.clientWidth - 11)), top: y});
} else {
$handle.prop('hidden', true);
}
if (!selectedElement?.isConnected) {
$elementTools.prop('hidden', true);
return;
}
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 getAlignment(node) {
return alignments.find((value) => node.classList.contains('studio-align-' + value)) || '';
}
function alignmentTarget(node) {
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"]')
? node : null;
}
function syncAlignmentButtons(target) {
$alignTools.prop('hidden', !target).find('[data-align]').each(function () {
$(this).attr('aria-pressed', String(Boolean(target) && getAlignment(target) === this.dataset.align));
});
}
function selectElement(node) {
selectionObserver?.disconnect();
selectedElement?.removeAttribute('data-studio-selected');
selectedElement = node;
const dynamic = node?.hasAttribute('data-studio-dynamic');
$elementTools.toggleClass('is-module', Boolean(dynamic)).find('[data-element-module-settings]').prop('hidden', !dynamic);
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 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 deleteLabel = node.dataset.studioField === 'heading' ? '删除首屏'
: node.dataset.studioPart === 'title' ? '删除区块' : '删除';
$elementTools.find('[data-element-delete]').attr({'aria-label': deleteLabel, title: deleteLabel})
.prop('hidden', !dynamic && !inBody && !selectedMedia && !node.matches(canvasFields));
$elementTools.find('[data-element-properties]').prop('hidden', !hasProperties);
if (target) showMediaWidth(currentMediaWidth(target));
selectionObserver?.observe(target || aligned || node);
}
positionSelection();
}
function changeElement(copy) {
const node = selectedElement;
if (!node?.isConnected) return;
if (node.hasAttribute('data-studio-dynamic')) {
changeModule(sections.find((section) => section.node === node), copy);
return;
}
const {studioField, studioAction, studioNavIndex} = node.dataset;
if (!copy && studioField === 'heading') {
pageInput('show_hero').val('0').trigger('change');
$studio.find('[data-canvas-status]').text('首屏已移除,可在页面设置中恢复。');
return;
}
if (!copy && node.dataset.studioPart === 'title') {
changeModule(sections.find((section) => section.node === node.closest('[data-studio-section]')), false);
return;
}
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 (studioAction !== undefined) {
const next = heroControls.get('change-action')(Number(studioAction), copy);
if (copy && next) selectElement(next);
} 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 (studioField) {
pageInput(studioField).val('').trigger('input');
} else {
$(node).text('');
}
}
}
$elementTools.on('click', '[data-align]', function () {
const target = alignmentTarget(selectedElement);
const alignment = this.dataset.align;
if (!target || !alignments.includes(alignment)) return;
target.classList.remove(...alignmentClasses);
target.classList.add('studio-align-' + alignment);
const field = target.dataset.studioAlignField;
if (field) {
const $value = pageInput('alignments');
const values = {...JSON.parse($value.val())};
values[field] = alignment;
$value.val(JSON.stringify(values));
}
syncAlignmentButtons(target);
positionSelection();
}).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?.hasAttribute('data-studio-action')) {
heroControls.get('edit-action')(Number(selectedElement.dataset.studioAction));
} else if (selectedElement?.matches('[data-studio-nav-index]')) {
$(selectedElement).triggerHandler('studio:properties');
} else if (selectedElement?.matches('a, progress')) {
editResource(selectedElement);
}
}).on('keydown', (event) => {
if (event.key === 'Escape') selectElement(null);
});
function noteModule(section, text) {
const $body = $(section).find('[data-studio-part="body"]');
let $note = $(section).find('[data-studio-module-note]');
if (!$note.length) $note = $('', {class: 'studio-module-note', 'data-studio-module-note': ''}).insertBefore($body);
$note.text(text);
}
$elementTools.on('click', '[data-element-module-settings]', () => {
editedModule = sections.find(({node}) => node === selectedElement);
if (!editedModule?.feed) return;
const {fields, feed} = editedModule;
moduleInput('module_title').val(fields.title.node.textContent);
moduleInput('module_lead').val(fields.lead.node.textContent);
moduleInput('feed_mode').val(feed.mode);
moduleInput('feed_limit').val(feed.limit);
moduleInput('feed_categories[]').each(function () {
this.checked = feed.categories.includes(this.value);
});
$moduleDialog.find('[data-module-error]').prop('hidden', true);
$moduleDialog.get(0).showModal();
});
$moduleDialog.on('click', '[data-module-close]', () => $moduleDialog.get(0).close());
$moduleForm.on('submit', (event) => {
event.preventDefault();
const categories = moduleInput('feed_categories[]').filter(':checked').map((_, node) => node.value).get();
const title = moduleInput('module_title').val().trim();
if (!title || !categories.length) {
$moduleDialog.find('[data-module-error]').text('请填写标题并至少选择一个分类。').prop('hidden', false);
return;
}
const {node, fields} = editedModule;
editedModule.feed = {mode: moduleInput('feed_mode').val(), categories, limit: Number(moduleInput('feed_limit').val())};
fields.title.node.textContent = title;
fields.lead.node.textContent = moduleInput('module_lead').val().trim();
noteModule(node, '模块设置将在保存页面后更新。');
$moduleDialog.get(0).close();
positionSelection();
});
function newSectionId() {
return 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('');
}
function addPending(section) {
const $button = $('