', {href: safeLink(url) ? url : '#', 'data-studio-nav-index': index,
'data-studio-path-type': type, 'data-studio-style-field': role});
if (crumb && index === items.length - 1) $link.attr('aria-current', 'page');
const node = $link.get(0);
configureText(node, config.heading + '链接');
setPageStyle(node, presentation[role]);
paintText(node, label || url, presentation[role]?.runs);
$link.on('input', () => {
items[index][1] = plainText(node).replace(/[|\r\n]/g, ' ');
customize();
$input.val(items.map(([link, text]) => text + ' | ' + link).join('\n'));
});
$link.on('dblclick studio:properties', (event) => {
event.preventDefault();
openProperties(config.heading + '链接', {label: plainText(node), url}, (next) => {
const updated = read();
updated[index] = [next.url, next.label];
if (!valid(updated)) {
$propertyError.prop('hidden', false).text('请输入有效网址及不超过 70 个字符的文案,文案不能包含竖线。');
return false;
}
write(updated);
});
});
$content.append($link);
});
$container.prop('hidden', items.length === 0);
};
const write = (items) => {
syncPagePresentation();
customize();
$input.val(items.map(([url, label]) => label + ' | ' + url).join('\n'));
sync();
renderLayers();
};
paths[type] = {read, sync, write};
heroControls.set(type, () => {
const field = crumb ? 'breadcrumbs' : 'quicklinks';
openProperties(config.heading, {[field]: $input.val()}, (values) => {
const previous = $input.val();
$input.val(values[field]);
const next = read();
$input.val(previous);
if (!valid(next)) {
$propertyError.prop('hidden', false).text('每行填写「文案 | 链接」,最多 20 条。');
return false;
}
write(next);
});
});
heroControls.set('order-' + type, (order) => {
const items = read();
remapPageStyles(config.prefix, order);
customize();
$input.val(order.map((index) => items[index][1] + ' | ' + items[index][0]).join('\n'));
sync();
});
heroControls.set('change-' + type, (index, copy) => {
const items = read();
if (copy && items.length >= 20) return null;
const order = items.map((_, position) => position);
order.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [index] : []));
remapPageStyles(config.prefix, order);
customize();
$input.val(order.map((i) => items[i][1] + ' | ' + items[i][0]).join('\n'));
sync();
return links().get(index + 1);
});
}
pageInput('name').on('input.canvas', function () {
if (!paths.breadcrumbs || pageInput('canvas_breadcrumbs_custom').val() === '1') return;
const $input = pageInput('canvas_breadcrumbs');
const first = $input.val().split('\n')[0];
$input.val(first + '\n' + this.value.replace(/[|\r\n]/g, ' ') + ' | /' + $settings.attr('action').split('/').at(-1));
paths.breadcrumbs.sync();
renderLayers();
});
heroControls.set('remove-section-links', (key) => {
const anchor = '#' + key;
for (const [type, path] of Object.entries(paths)) {
const items = path.read();
const order = items.flatMap(([url], i) => url === anchor ? [] : [i]);
if (order.length === items.length) continue;
remapPageStyles(type === 'breadcrumbs' ? 'crumb' : 'nav', order);
const crumb = type === 'breadcrumbs';
if (crumb) pageInput('canvas_breadcrumbs_custom').val('1');
pageInput(crumb ? 'canvas_breadcrumbs' : 'quicklinks').val(order.map((i) => items[i][1] + ' | ' + items[i][0]).join('\n'));
path.sync();
}
if (actions.some(([url]) => url === anchor)) {
remapPageStyles('action', actions.flatMap(([url], i) => url === anchor ? [] : [i]));
actions = actions.filter(([url]) => url !== anchor);
syncActions();
}
});
syncPageFromInputs = () => {
const presentation = pagePresentation();
$heroSource.html(presentation.heroHtml ?? '');
installMarkupColors(presentation.heroHtml ?? '');
$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]);
});
visibilityInputs.forEach((field) => pageInput(field).triggerHandler('change.canvas'));
pageInput('palette_id').triggerHandler('change.canvas');
actions = readActions();
syncActions();
Object.values(paths).forEach(({sync}) => sync());
syncImage();
};
syncPageFromInputs();
}
function editResource(node) {
const tag = node.localName;
if (node.matches('a.studio-member-slot') && $settings.find('[data-shared-auth]').length) {
syncMemberSettings();
$settings.find('[data-shared-auth]').prop('open', true).find('[name=provider_mode]').trigger('focus');
return;
}
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 (body) {
node.contentEditable = 'true';
node.setAttribute('aria-label', label);
node.dataset.studioPlaceholder = label;
} else if (!node.hidden && !body) {
configureText(node, label, part === 'lead');
}
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),
parent: section.parentNode, fixed: section.classList.contains('hero-directory-slot'), ...metadata};
entry.initialPresentation = JSON.stringify(sectionPresentation(entry));
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) || node.closest('span');
if (element?.contains(body)) return node.closest('span');
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.parentElement?.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');
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));
$elementTools.find('[data-element-source]').prop('hidden', !node?.matches('[data-studio-section], [data-studio-hero]'));
selectedMedia = node?.matches(mediaTargets) ? node : null;
$sizing.prop('hidden', !selectedMedia);
$imageDisplay.prop('disabled', !selectedMedia?.matches('img')).val(classesOf(sizingTarget() || doc.documentElement).display?.slice('studio-style-display-'.length) || '');
$layers.find('.studio-layer-row[aria-current]').removeAttr('aria-current');
if (node) {
node.setAttribute('data-studio-selected', '');
const target = sizingTarget();
const nav = node.hasAttribute('data-studio-nav-index');
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 hero = node.hasAttribute('data-studio-hero') && isHeroVisible();
const deleteLabel = hero || node.dataset.studioField === 'heading' ? '删除首屏'
: node.dataset.studioPart === 'title' || sectionRoot ? '删除区块' : '删除';
$elementTools.find('[data-element-delete]').attr({'aria-label': deleteLabel, title: deleteLabel})
.prop('hidden', !hero && !sectionRoot && !inBody && !selectedMedia && !node.matches(canvasFields));
$elementTools.find('[data-element-properties]').prop('hidden', !hasProperties && !node.matches('[data-studio-navigation], [data-studio-breadcrumbs]'));
$layers.find('.studio-layer-row').filter((_, row) => $(row).data('canvasNode') === node).attr('aria-current', 'true');
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-section')) {
changeModule(sections.find((section) => section.node === node), copy);
return;
}
const {studioField, studioAction, studioNavIndex} = node.dataset;
if (!copy && (studioField === 'heading' || node.hasAttribute('data-studio-hero'))) {
removeHero();
return;
}
if (!copy && node.dataset.studioPart === 'title') {
changeModule(sections.find((section) => section.node === node.closest('[data-studio-section]')), false);
return;
}
const inBody = Boolean(node.parentElement?.closest('[data-studio-part="body"]'));
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-' + node.dataset.studioPathType)(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?.matches('[data-studio-navigation], [data-studio-breadcrumbs]')) {
heroControls.get(selectedElement.hasAttribute('data-studio-breadcrumbs') ? 'breadcrumbs' : 'navigation')();
} 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('click', '[data-element-source]', () => openSource(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(plainText(fields.title.node));
moduleInput('module_lead').val(plainText(fields.lead.node));
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())};
if (plainText(fields.title.node) !== title) paintText(fields.title.node, title);
const lead = moduleInput('module_lead').val().trim();
if (plainText(fields.lead.node) !== lead) paintText(fields.lead.node, lead);
noteModule(node, '模块设置将在保存页面后更新。');
refreshLayerTitle(editedModule);
$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 refreshLayerTitle(section) {
const title = plainText(section.fields.title.node) || '未命名区块';
$layers.find('.studio-layer-row').filter((_, row) => $(row).data('canvasNode') === section.node)
.find('.studio-layer-label').text(title);
}
function isHeroVisible() {
return pageInput('show_hero').val() === '1';
}
function removeHero() {
if (!isHeroVisible()) return;
selectBody(null);
textHost = null;
textRange = null;
doc.getSelection().removeAllRanges();
pageInput('show_hero').val('0').trigger('change');
$studio.find('[data-canvas-status]').text('首屏已移除,可撤销或在页面设置中恢复。');
}
function locateLayer(node, body = null) {
doc.getSelection().removeAllRanges();
textRange = null;
textHost = null;
selectBody(body);
$studio.get(0).scrollIntoView({block: 'start'});
node.scrollIntoView({block: 'start'});
selectElement(node);
}
function openSource(node) {
if (!node?.isConnected) return;
const entry = sections.find((section) => section.node === node);
const hero = node.hasAttribute('data-studio-hero');
if (!entry && !hero) return;
const parts = new Map();
if (hero) {
const target = node.querySelector('[data-studio-hero-source]');
const managed = node.querySelector('[data-studio-hero-content]');
const custom = pageInput('canvas_hero_custom').val() === '1';
const clone = managed.cloneNode(true);
clone.removeAttribute('hidden');
$(clone).find('[hidden]').remove();
$(clone).find('img:not([src]), [data-studio-field="accent"]:empty, [data-studio-field="lead"]:empty').remove();
// The saved markup contains only public content, with editor attributes removed by the server.
parts.set('hero', {label: '首屏完整内容', node: target, original: custom ? cleanBody(target) : clone.outerHTML});
$source.find('[data-source-reset]').prop('hidden', !custom);
} else {
for (const [key, label] of Object.entries({body: '区块正文', title: '区块标题', lead: '区块简介'})) {
const node = entry.fields[key].node;
parts.set(key, {label, node, original: key === 'body' ? cleanBody(node) : node.innerHTML});
}
$source.find('[data-source-reset]').prop('hidden', true);
}
for (const part of parts.values()) part.draft = part.original;
sourceParts = parts;
$sourcePart.empty();
for (const [key, {label}] of parts) $('