', {href: url}).text(label || url).prop('outerHTML'));
}
});
});
} else {
const commands = {heading: ['formatBlock', 'h3'], bold: ['bold'], list: ['insertUnorderedList']};
edit(...commands[command]);
}
});
function configureText(node, label, placeholder = false) {
node.contentEditable = 'plaintext-only';
node.setAttribute('aria-label', label);
if (placeholder) node.dataset.studioPlaceholder = label;
}
function bindPage($doc) {
const labels = {name: '页面名称', heading: '首屏标题', accent: '标题第二行', lead: '首屏简介'};
$doc.find('[data-studio-field]').each(function () {
const field = this.dataset.studioField;
const $target = $(this);
const $input = pageInput(field);
configureText(this, labels[field], ['accent', 'lead'].includes(field));
$target.text($input.val()).on('input', () => $input.val($target.text()));
$input.on('input.canvas', () => $target.text($input.val()));
});
const $image = $doc.find('[data-studio-hero-image]');
const $visual = $image.parent();
function syncImage() {
const path = pageInput('image').val().trim();
const valid = safeLink(path, true);
setMediaWidth($visual.get(0), pageInput('image_scale').val());
$visual.prop('hidden', !valid).parent().toggleClass('hero-text-only', !valid);
if (valid) $image.attr('src', path);
else $image.removeAttr('src');
$image.attr('alt', pageInput('alt').val());
}
$settings.find('[name="image"], [name="alt"]').on('input.canvas', syncImage);
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', () => {
openProperties('首屏图片', {url: pageInput('image').val(), alt: pageInput('alt').val()}, ({url, alt}) => {
pageInput('image').val(url);
pageInput('alt').val(alt);
syncImage();
}, 'image/', true);
});
$doc.find('[data-studio-action]').each(function () {
const $button = $(this);
const index = this.dataset.studioAction;
const $label = pageInput('label' + index);
const $url = pageInput('url' + index);
function sync() {
const url = $url.val().trim();
$button.text($label.val()).attr('href', safeLink(url) ? url : '#').prop('hidden', !$label.val() && !url);
}
$label.add($url).on('input.canvas', sync);
const editButton = () => {
openProperties('首屏按钮', {label: $label.val(), url: $url.val()}, ({label, url}) => {
if (Boolean(label) !== Boolean(url)) {
$propertyError.prop('hidden', false).text('请同时填写按钮文案和链接,或将两项都留空。');
return false;
}
$label.val(label);
$url.val(url);
sync();
}, null, true);
};
heroControls.set(index, editButton);
$button.on('dblclick studio:properties', (event) => {
event.preventDefault();
editButton();
});
sync();
});
const $navigation = $doc.find('[data-studio-navigation]');
const $navContent = $navigation.find('.section-nav-inner');
const $navInput = pageInput('quicklinks');
const navLines = () => $navInput.val().split(/\r\n|[\n\r\v\f\u0085\u2028\u2029]/);
function syncNavigation() {
const lines = navLines();
$navContent.empty();
for (const [index, line] of lines.entries()) {
if (!line.trim()) continue;
const separator = line.indexOf('|');
const label = (separator < 0 ? line : line.slice(0, separator)).trim();
const url = separator < 0 ? '' : line.slice(separator + 1).trim();
const link = doc.createElement('a');
link.href = safeLink(url) ? url : '#';
link.textContent = label || url;
link.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('navigation', () => {
openProperties('本页目录', {quicklinks: $navInput.val()}, ({quicklinks}) => {
$navInput.val(quicklinks);
syncNavigation();
});
});
syncNavigation();
}
function editResource(node) {
const tag = node.localName;
if (tag === 'a') {
const onlyChild = node.firstElementChild;
const text = node.childElementCount === 0 ? node : (
node.childElementCount === 1 && onlyChild.matches('span, strong, b, em, i, small')
&& !onlyChild.childElementCount && node.textContent.trim() === onlyChild.textContent.trim() ? onlyChild : null
);
const values = text ? {label: text.textContent, url: node.getAttribute('href') || ''} : {url: node.getAttribute('href') || ''};
openProperties('正文链接', values, ({label, url}) => {
node.setAttribute('href', url);
if (text && label !== values.label) text.textContent = label;
});
return;
}
const source = tag === 'img' ? node : (node.hasAttribute('src') ? node : node.querySelector('source') || node);
const values = {url: source.getAttribute('src') || ''};
if (tag === 'img') values.alt = node.getAttribute('alt') || '';
if (tag === 'video') values.poster = node.getAttribute('poster') || '';
openProperties({img: '正文图片', video: '视频', audio: '音频'}[tag], values, ({url, alt, poster}) => {
if (url !== values.url) {
source.setAttribute('src', url);
if (source !== node) source.removeAttribute('type');
if (tag !== 'img') node.load();
}
if (alt !== undefined && alt !== values.alt) node.setAttribute('alt', alt);
if (poster !== undefined && poster !== values.poster) {
if (poster) node.setAttribute('poster', poster);
else node.removeAttribute('poster');
}
}, (tag === 'img' ? 'image' : tag) + '/');
}
function registerSection(section, version = Number(section.dataset.studioSection)) {
const fields = {};
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 {
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)
));
sections.push({key: section.id, version, fields, source, template: section.dataset.studioTemplate});
}
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;
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');
const aligned = alignmentTarget(node);
syncAlignmentButtons(aligned);
$elementTools.find('[data-element-copy]').prop('hidden', !canCopy);
$elementTools.find('[data-element-delete]').prop('hidden', !inBody && !selectedMedia && !node.matches(heroOrOptional));
$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;
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-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-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);
}
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 fromLeft = getAlignment(node) === 'right';
const edgeTravel = (fromLeft ? narrow.left - full.left : full.right - narrow.right) / .9;
const available = edgeTravel > full.width * .15 ? edgeTravel : full.width;
return {available, fromLeft, 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;
const distance = (pointer.clientX - mediaDrag.x) * (mediaDrag.fromLeft ? -1 : 1);
resizeMedia(mediaDrag.initialWidth + 100 * distance / (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)
.on('click', '[data-reset-media]', () => resizeMedia(null));
$layout.on('click', '[data-hero-control]', function () {
heroControls.get(this.dataset.heroControl)?.();
});
function insertInBody(markup, body, range) {
if (!body.isConnected) return;
const insertion = doc.createRange();
// Insert between blocks so the browser doesn't split a paragraph or duplicate its ID.
let node = range?.endContainer;
if (!node || !body.contains(node)) {
insertion.selectNodeContents(body);
insertion.collapse(false);
} else if (node === body) {
insertion.setStart(body, range.endOffset);
} else {
while (node.parentNode !== body) node = node.parentNode;
insertion.setStartAfter(node);
}
editBody(body, insertion, 'insertHTML', markup);
}
$presets.on('mousedown', '[data-canvas-template], [data-canvas-element]', (event) => event.preventDefault());
$presets.on('click', '[data-canvas-element]', function () {
const $status = $presets.find('[data-element-status]');
const body = activeBody;
const range = savedRange?.cloneRange();
if (!body) {
$status.text('请先在画布中选中要插入的正文。');
return;
}
const add = (markup) => {
if (!markup) return;
insertInBody(markup, body, range);
selectElement(null);
$status.text('已插入' + $(this).text() + '。');
};
if (this.dataset.elementMime) {
openPicker(this.dataset.elementMime, (file) => add(mediaMarkup(file)));
} else {
add($presets.find('template[data-element="' + this.dataset.canvasElement + '"]').get(0).innerHTML);
}
});
$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;
}
insertInBody(markup, activeBody, savedRange);
selectElement(null);
$templateStatus.text('已插入当前正文。');
return;
}
if (sections.filter(({version}) => version === null).length >= 50) {
$templateStatus.text('请先保存,再添加更多区块。');
return;
}
const end = doc.querySelector('[data-studio-section-end]');
const section = end.content.firstElementChild.cloneNode(true);
const id = 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('');
section.id = id;
const title = section.querySelector('[data-studio-part="title"]');
title.id = 'heading-' + id;
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;
$('', {class: 'empty-state', text: '保存页面后可在图层的区块设置中选择分类和展示方式。'})
.insertBefore($(section).find('[data-studio-part="body"]'));
}
end.before(section);
registerSection(section, null);
section.scrollIntoView({block: 'start'});
section.querySelector('[data-studio-part="body"]').focus({preventScroll: true});
const $cancel = $('