Files
laysite/public/assets/studio.js
T

2053 lines
103 KiB
JavaScript

'use strict';
jQuery(function ($) {
const $picker = $('#media-picker');
const $pickerItems = $picker.find('[data-picker-items]');
const $pickerStatus = $picker.find('[data-picker-status]');
let pick = null;
let files = [];
let mediaType = '';
let pickerRequest;
function safeLink(value, media = false) {
return value !== '' && !/[\u0000-\u0020\u007f\\]/.test(value)
&& (/^\/(?!\/)/.test(value) || (media ? /^https:\/\//i : /^(https?:\/\/|mailto:|tel:|#\S)/i).test(value));
}
function mediaMarkup(file) {
let $node;
if (file.mime.startsWith('image/')) {
const alt = window.prompt('图片替代文本(装饰图可留空)', file.label);
if (alt === null) return '';
$node = $('<img>', {src: file.url, alt, loading: 'lazy'});
} else if (file.mime.startsWith('video/') || file.mime.startsWith('audio/')) {
const tag = file.mime.startsWith('video/') ? '<video>' : '<audio>';
$node = $(tag, {src: file.url, controls: true, preload: 'metadata'});
} else {
$node = $('<a>', {href: file.url}).text(file.label);
}
return $node.prop('outerHTML');
}
function renderPicker() {
const query = String($picker.find('[data-media-query]').val() || '').trim().toLowerCase();
const results = files.filter((file) => file.mime.startsWith(mediaType)
&& (file.label + ' ' + file.url).toLowerCase().includes(query));
$pickerStatus.text(results.length ? results.length + ' 个资源' : '没有匹配资源。');
$pickerItems.empty();
for (const file of results) {
const $item = $('<button>', {type: 'button', class: 'picker-item'}).data('file', file);
if (file.mime.startsWith('image/')) {
$item.append($('<img>', {src: file.url, alt: '', loading: 'lazy'}));
}
$item.append($('<span>').text(file.label));
$pickerItems.append($item);
}
}
function openPicker(type, callback) {
if (!$picker.length || typeof $picker.get(0).showModal !== 'function') return;
pick = callback;
mediaType = type;
$picker.find('[data-media-query]').val('');
$pickerItems.empty();
$pickerStatus.text('加载资源…');
$picker.get(0).showModal();
pickerRequest?.abort();
pickerRequest = $.getJSON('/admin/media/options').done(function (response) {
files = response.files;
renderPicker();
}).fail(function (_request, status) {
if (status !== 'abort') $pickerStatus.text('媒体库暂时无法打开。');
});
}
$picker.on('studio:pick', (_event, type, callback) => openPicker(type, callback));
$picker.on('input', '[data-media-query]', renderPicker);
$picker.on('click', '[data-close-picker]', () => $picker.get(0).close());
$picker.on('click', '.picker-item', function () {
const file = $(this).data('file');
$picker.get(0).close();
pick?.(file);
});
$('[data-asset-pick]').on('click', function () {
const $button = $(this);
const name = $button.data('asset-pick');
const $input = $button.closest('form').find('input').filter((_, field) => field.name === name);
openPicker($button.data('asset-type') || '', (file) => $input.val(file.url).trigger('input').trigger('focus'));
});
$('[data-copy-asset]').on('click', function () {
const $button = $(this);
const url = $button.data('copy-asset');
if (!navigator.clipboard) {
window.prompt('复制资源路径', url);
return;
}
navigator.clipboard.writeText(url).then(() => $button.text('已复制')).catch(() => window.prompt('复制资源路径', url));
});
$('[data-media-library]').each(function () {
const $library = $(this);
const $cards = $library.find('[data-library-card]');
function filter() {
const query = String($library.find('[data-library-query]').val()).trim().toLowerCase();
const category = $library.find('[data-library-type]').val();
let count = 0;
$cards.each(function () {
const $card = $(this);
const mime = $card.data('mime');
const matchesType = category === 'other' ? !/^(image|audio|video)\//.test(mime) : mime.startsWith(category);
const visible = matchesType && $card.data('search').toLowerCase().includes(query);
$card.prop('hidden', !visible);
if (visible) count++;
});
$library.find('[data-library-count]').text(count + ' 个资源');
}
$library.on('input change', '[data-library-query], [data-library-type]', filter);
filter();
});
function bodyEdits(original, edited) {
// Work in Unicode code points, then encode offsets in UTF-8 for PHP.
const before = Array.from(original);
const after = Array.from(edited);
const encoder = new TextEncoder();
const anchorSize = 32;
let start = 0;
let beforeEnd = before.length;
let afterEnd = after.length;
while (start < beforeEnd && start < afterEnd && before[start] === after[start]) start++;
while (beforeEnd > start && afterEnd > start && before[beforeEnd - 1] === after[afterEnd - 1]) {
beforeEnd--;
afterEnd--;
}
if (beforeEnd === start && afterEnd === start) return [];
const anchors = new Map();
for (let index = start; index + anchorSize <= beforeEnd; index += anchorSize) {
const key = before.slice(index, index + anchorSize).join('');
if (!anchors.has(key)) anchors.set(key, []);
anchors.get(key).push(index);
}
const edits = [];
let oldIndex = start;
let newIndex = start;
let byteOffset = encoder.encode(before.slice(0, start).join('')).length;
function copy() {
const first = oldIndex;
while (oldIndex < beforeEnd && newIndex < afterEnd && before[oldIndex] === after[newIndex]) {
oldIndex++;
newIndex++;
}
byteOffset += encoder.encode(before.slice(first, oldIndex).join('')).length;
}
function replace(oldEnd, newEnd) {
if (oldEnd === oldIndex && newEnd === newIndex) return;
const removed = encoder.encode(before.slice(oldIndex, oldEnd).join('')).length;
edits.push([byteOffset, removed, after.slice(newIndex, newEnd).join('')]);
byteOffset += removed;
oldIndex = oldEnd;
newIndex = newEnd;
}
for (let scan = start; scan + anchorSize <= afterEnd && edits.length < 511; scan++) {
const matches = anchors.get(after.slice(scan, scan + anchorSize).join(''));
if (!matches) continue;
let low = 0;
let high = matches.length;
while (low < high) {
const middle = Math.floor((low + high) / 2);
if (matches[middle] < oldIndex) low = middle + 1;
else high = middle;
}
if (low === matches.length) continue;
let nextOld = matches[low];
let nextNew = scan;
while (nextOld > oldIndex && nextNew > newIndex && before[nextOld - 1] === after[nextNew - 1]) {
nextOld--;
nextNew--;
}
replace(nextOld, nextNew);
copy();
scan = newIndex - 1;
}
replace(beforeEnd, afterEnd);
return edits;
}
$('[data-canvas-presets]').each(function () {
const $gallery = $(this);
const $tabs = $gallery.find('[data-library-tab]');
const $panels = $gallery.find('[data-library-panel]');
const $peek = $gallery.find('[data-template-peek]');
const $dialog = $gallery.find('[data-template-dialog]');
const $use = $dialog.find('[data-template-use]');
let $selection;
function hidePeek() {
$peek.prop('hidden', true);
}
function selectTab(kind, focus = false) {
const $current = $tabs.filter((_, tab) => tab.dataset.libraryTab === kind);
$tabs.attr({'aria-selected': 'false', tabindex: '-1'});
$current.attr({'aria-selected': 'true', tabindex: '0'});
$panels.each(function () {
$(this).prop('hidden', this.dataset.libraryPanel !== kind);
});
$gallery.closest('.studio-library').scrollTop(0);
hidePeek();
if (focus) $current.trigger('focus');
}
function filterItems($panel) {
const query = $panel.find('[data-template-search]').val().trim().toLowerCase();
let matches = 0;
$panel.find('[data-template-group]').filter((_, group) => !group.hidden).find('[data-library-item]').each(function () {
const visible = this.dataset.templateSearchText.toLowerCase().includes(query);
$(this).prop('hidden', !visible);
if (visible) matches++;
});
$panel.find('[data-template-empty]').prop('hidden', matches !== 0);
hidePeek();
}
$gallery.find('[data-library-tabs]').prop('hidden', false);
function openLayersFromHash() {
if (window.location.hash !== '#blocks') return false;
selectTab('layers');
$gallery.find('#blocks').prop('open', true);
return true;
}
if (!openLayersFromHash()) selectTab('modules');
$(window).on('hashchange', openLayersFromHash);
$tabs.on('click', function () {
selectTab(this.dataset.libraryTab);
}).on('keydown', function (event) {
const index = $tabs.index(this);
const last = $tabs.length - 1;
const next = {Home: 0, End: last, ArrowLeft: index === 0 ? last : index - 1, ArrowRight: index === last ? 0 : index + 1}[event.key];
if (typeof next !== 'number') return;
event.preventDefault();
selectTab($tabs.get(next).dataset.libraryTab, true);
});
$gallery.on('click', '[data-library-category]', function () {
const $panel = $(this).closest('[data-library-panel]');
$panel.data('categoryTrigger', this);
$panel.find('[data-library-index], .studio-anchor-create').prop('hidden', true);
$panel.find('[data-library-content]').prop('hidden', false);
$panel.find('[data-library-title]').text(this.dataset.libraryLabel);
$panel.find('[data-template-search]').val('');
const key = this.dataset.libraryCategory;
$panel.find('[data-template-group]').each(function () {
$(this).prop('hidden', this.dataset.templateGroup !== key);
});
filterItems($panel);
$panel.find('[data-library-back]').trigger('focus');
}).on('click', '[data-library-back]', function () {
const $panel = $(this).closest('[data-library-panel]');
$panel.find('[data-library-content]').prop('hidden', true);
$panel.find('[data-library-index], .studio-anchor-create').prop('hidden', false);
hidePeek();
$($panel.data('categoryTrigger')).trigger('focus');
}).on('input', '[data-template-search]', function () {
filterItems($(this).closest('[data-library-panel]'));
});
$gallery.on('mouseenter focusin', '[data-template-preview]', function (event) {
if (event.type === 'mouseenter' && !matchMedia('(hover: hover)').matches) return;
const bounds = this.getBoundingClientRect();
const width = Math.min(430, window.innerWidth - bounds.right - 24);
if (width < 240) return;
const top = Math.max(12, Math.min(bounds.top, window.innerHeight - width * 0.625 - 56));
$peek.find('img').attr('src', $(this).find('img').attr('src'));
$peek.find('p').text(this.dataset.templateTitle);
$peek.css({width, top, left: bounds.right + 12}).prop('hidden', false);
});
$gallery.on('mouseleave focusout', '[data-template-preview]', hidePeek);
$gallery.closest('.studio-library').on('scroll', hidePeek);
$(window).on('scroll resize', hidePeek);
$gallery.on('click', '[data-template-preview]', function () {
hidePeek();
const $card = $(this).closest('[data-template-card]');
$selection = $card.find('[data-canvas-template]');
$dialog.find('h2').text(this.dataset.templateTitle);
$dialog.find('img').attr('src', $(this).find('img').attr('src'));
$use.prop('disabled', $selection.prop('disabled'));
$dialog.get(0).showModal();
});
$dialog.on('click', '[data-template-close]', () => $dialog.get(0).close());
$use.on('click', () => {
if (!$selection || $selection.prop('disabled')) return;
$dialog.get(0).close();
hidePeek();
$selection.trigger('click');
});
$gallery.on('studio:canvas-ready', () => {
if ($selection) $use.prop('disabled', $selection.prop('disabled'));
});
});
$('[data-preview-studio]').each(function () {
const $studio = $(this);
const $frame = $studio.find('iframe');
const $window = $studio.find('.studio-frame-window');
const $layout = $studio.closest('.studio-layout');
const $settings = $layout.find('.studio-inspector');
const $sizing = $studio.find('[data-media-sizing]');
const $elementTools = $studio.find('[data-element-tools]');
const $alignTools = $elementTools.find('[data-element-align]');
const alignments = ['left', 'center', 'right'];
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, button, details, div, dl, dt, dd, figure, figcaption, footer, h1, h2, h3, h4, h5, h6, header, hr, li, nav, 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]');
const mediaWidthClass = /^studio-media-\d+$/;
function fitPreview() {
const width = $window.width();
const height = $window.height();
if (!width || !height) return;
const viewport = $studio.hasClass('studio-phone') ? 390 : Math.max(1280, width);
const scale = Math.min(1, width / viewport);
$window.addClass('has-scaled-preview');
$frame.css({
width: viewport,
height: height / scale,
left: (width - viewport * scale) / 2,
transform: 'scale(' + scale + ')'
});
positionSelection();
}
const $presets = $layout.find('[data-canvas-presets]');
const $templateStatus = $presets.find('[data-template-status]');
const $pending = $presets.find('[data-template-pending]');
const heroControls = new Map();
let selectedElement;
let selectedMedia;
let mediaDrag;
const selectionObserver = 'ResizeObserver' in window ? new ResizeObserver(positionSelection) : null;
if ('ResizeObserver' in window) {
new ResizeObserver(fitPreview).observe($window.get(0));
} else {
$(window).on('resize', fitPreview);
}
fitPreview();
$studio.on('click', '[data-preview-size]', function () {
const $button = $(this);
$studio.toggleClass('studio-phone', $button.data('preview-size') === 'phone');
$studio.find('[data-preview-size]').attr('aria-pressed', 'false');
$button.attr('aria-pressed', 'true');
fitPreview();
});
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]');
const $moduleDialog = $studio.find('[data-module-dialog]');
const $moduleForm = $moduleDialog.find('form');
const moduleInput = (name) => $moduleForm.find('[name="' + name + '"]');
let editedModule;
let deletedSections = [];
const propertyInput = (name) => $propertyForm.find('[name="' + name + '"]');
const pageInput = (name) => $settings.find('[name="' + name + '"]');
const settingsSnapshot = () => $settings.serializeArray()
.filter(({name}) => !['csrf', 'canvas_sections', 'canvas_order', 'provider_secret'].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 syncMemberSettings() {
const $auth = $settings.find('[data-shared-auth]');
if (!$auth.length) return;
const member = Boolean(doc?.querySelector('#main-content [data-studio-part="body"] a.studio-member-slot'));
$auth.prop('hidden', !member).find('[data-provider-settings]').prop('disabled', !member);
$auth.find('[name=provider_mode]').triggerHandler('change.layoutProvider');
}
function sectionChanges(withEdits = true) {
const edits = sections.flatMap((entry) => {
const {key, version, fields, source, template, copyOf, feed, initialFeed, initialPresentation} = entry;
const changes = {};
const aligned = {};
let alignmentChanged = false;
for (const [field, {node, initial, initialAlignment}] of Object.entries(fields)) {
if (field !== 'body') {
const value = getAlignment(node);
if (value) aligned[field] = value;
if (value !== initialAlignment) alignmentChanged = true;
}
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);
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', () => {
if (!doc || initialOrder === undefined) return;
syncMemberSettings();
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 || pageInput('provider_secret').filter(':enabled').val()
|| initialOrder !== undefined && canvasOrder() !== initialOrder
|| JSON.stringify(settingsSnapshot()) !== savedSettings)) {
event.preventDefault();
event.originalEvent.returnValue = '';
}
});
function openProperties(heading, values, apply, mime = null, allowEmptyUrl = false) {
$properties.find('[data-property-heading]').text(heading);
$propertyError.prop('hidden', true);
for (const key of ['label', 'note', 'url', 'alt', 'poster', 'quicklinks', 'value', 'max', 'buttonStyle', 'newTab']) {
const visible = Object.hasOwn(values, key);
$propertyForm.find('[data-property-row="' + key + '"]').prop('hidden', !visible);
propertyInput(key).val(visible ? values[key] : '');
}
$properties.find('[data-property-pick="url"]').prop('hidden', mime === null);
$properties.find('[data-property-pick="poster"]').prop('hidden', !Object.hasOwn(values, 'poster'));
dialogAction = {values, apply, mime, allowEmptyUrl};
$properties.get(0).showModal();
}
$properties.on('click', '[data-property-close]', () => $properties.get(0).close());
$properties.on('click', '[data-property-pick]', function () {
const field = this.dataset.propertyPick;
openPicker(field === 'poster' ? 'image/' : dialogAction.mime,
(file) => propertyInput(field).val(file.url).trigger('focus'));
});
$propertyForm.on('submit', (event) => {
event.preventDefault();
const {values, apply, mime, allowEmptyUrl} = dialogAction;
const result = Object.fromEntries(Object.keys(values).map((field) => [field, propertyInput(field).val().trim()]));
if ((Object.hasOwn(result, 'url') && ((!result.url && !allowEmptyUrl) || (result.url && !safeLink(result.url, mime !== null))))
|| (result.poster && !safeLink(result.poster, true))) {
$propertyError.prop('hidden', false).text('请输入有效的站内地址或链接。媒体也可使用 HTTPS 地址。');
return;
}
if (apply(result) !== false) $properties.get(0).close();
});
function rememberSelection() {
const selection = doc.getSelection();
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();
}
}
function selectBody(body) {
if (body !== activeBody) {
activeBody = body;
savedRange = null;
}
$commands.prop('disabled', !activeBody);
}
function editBody(body, range, command, value) {
if (!body?.isConnected) return;
body.focus();
const selection = doc.getSelection();
if (!range || !body.contains(range.commonAncestorContainer)) {
range = doc.createRange();
range.selectNodeContents(body);
range.collapse(false);
}
selection.removeAllRanges();
selection.addRange(range);
doc.execCommand(command, false, value);
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;
const body = activeBody;
const range = savedRange?.cloneRange();
const edit = (action, value) => editBody(body, range, action, value);
if (command === 'media') {
openPicker('', (file) => {
const markup = mediaMarkup(file);
if (markup) edit('insertHTML', markup);
});
} else if (command === 'link') {
openProperties('插入链接', {label: range?.toString() || '', url: ''}, ({label, url}) => {
queueMicrotask(() => {
if (range && !range.collapsed && label === range.toString()) {
edit('createLink', url);
} else {
edit('insertHTML', $('<a>', {href: url}).text(label || url).prop('outerHTML'));
}
});
});
} else {
const commands = {heading: ['formatBlock', 'h3'], paragraph: ['insertParagraph'], list: ['insertUnorderedList']};
edit(...commands[command]);
}
});
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;
}
function bindPage($doc) {
const $body = $doc.find('body');
const visibilityInputs = ['show_hero', 'header_choice', 'footer_choice'];
const $heroInput = pageInput('show_hero');
$heroInput.on('change.canvas', () => {
selectElement(null);
$doc.find('[data-studio-hero-content], .page-photo-credit').prop('hidden', $heroInput.val() === '0');
});
for (const [area, fallback] of Object.entries({header: '.masthead', footer: '.site-footer'})) {
const $input = pageInput(area + '_choice');
const selector = '[data-site-area="' + area + '"], ' + fallback;
let rendered = $input.val();
let pending;
$input.on('change.canvas', () => {
selectElement(null);
pending?.abort();
const choice = $input.val();
const $target = $body.children(selector);
$target.prop('hidden', choice === 'hidden');
if (choice === 'hidden' || choice === rendered) return;
pending = $.get($frame.attr('src'), {area, choice}, undefined, 'text').done((html) => {
if ($input.val() !== choice) return;
const preview = new DOMParser().parseFromString(html, 'text/html');
const replacement = $(preview.body).children(selector).get(0);
if (!replacement) return;
$target.replaceWith(doc.importNode(replacement, true));
rendered = choice;
});
});
}
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), 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]');
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);
});
const $heroActions = $doc.find('.hero-actions');
const $actionsInput = pageInput('hero_actions');
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()) {
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) {
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;
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);
});
pageInput('palette_id').on('change.canvas', function () {
$doc.find('[data-page-palette]').remove();
if (this.value) $('<link>', {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();
const presentation = pagePresentation();
$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.dataset.studioStyleField = 'nav-' + $navContent.children().length;
setPageStyle(link, presentation[link.dataset.studioStyleField]);
$(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;
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();
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;
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();
});
heroControls.set('navigation', () => {
openProperties('本页目录', {quicklinks: $navInput.val()}, ({quicklinks}) => {
$navInput.val(quicklinks);
syncNavigation();
});
});
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]);
});
visibilityInputs.forEach((field) => pageInput(field).triggerHandler('change.canvas'));
pageInput('palette_id').triggerHandler('change.canvas');
actions = readActions();
syncActions();
syncNavigation();
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) $('<small>').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 : 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);
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));
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 = 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);
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-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 = $('<p>', {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, '模块设置将在保存页面后更新。');
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.children().filter((_, node) => node.dataset.layerKey === section.key).find('[data-layer-title]').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 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();
const heroVisible = isHeroVisible();
if (heroVisible) {
const $hero = $('<li>', {'data-layer-key': 'home'}).appendTo($layers);
$hero.append($('<strong>').text('首屏'));
$('<div>', {class: 'actions studio-block-actions'}).append(
button('定位', 'jump'), button('删除', 'delete')
).appendTo($hero);
}
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', heroVisible || sections.length > 0);
$(doc).find('[data-studio-empty-layout]').prop('hidden', heroVisible || sections.length > 0);
$pending.prop('hidden', !$pending.children().length);
}
$layers.on('click', '[data-layer-operation]', function () {
const key = this.closest('[data-layer-key]').dataset.layerKey;
const operation = this.dataset.layerOperation;
if (key === 'home') {
if (operation === 'delete') removeHero();
else if (operation === 'jump') locateLayer(doc.querySelector('[data-studio-hero]'));
return;
}
const entry = sections.find((section) => section.key === key);
if (!entry) return;
if (operation === 'delete') {
changeModule(entry, false);
} else if (operation === 'jump') {
locateLayer(entry.node, entry.feed ? null : entry.fields.body.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);
if (section.version !== null) deletedSections.push({key: section.key, version: section.version, delete: true});
section.node.remove();
sections = sections.filter((entry) => entry !== section);
heroControls.get('remove-section-links')(section.key);
renderLayers();
}
function scopeTemplateIds(root, prefix, oldKey = '') {
const ids = new Map();
$(root).find('[id]').addBack('[id]').each(function () {
const next = oldKey && this.id.includes(oldKey) ? this.id.replace(oldKey, prefix) : prefix + '-' + this.id;
ids.set(this.id, next);
this.id = next;
});
$(root).find('[aria-labelledby], [aria-controls], [href^="#"]').addBack('[aria-labelledby]').each(function () {
for (const attribute of ['aria-labelledby', 'aria-controls', 'href']) {
const value = this.getAttribute(attribute);
if (!value) continue;
if (attribute === 'href') {
const target = ids.get(value.slice(1));
if (value.startsWith('#') && target) this.setAttribute('href', '#' + target);
} else {
this.setAttribute(attribute, value.split(' ').map((part) => ids.get(part) || part).join(' '));
}
}
});
}
function changeModule(section, copy) {
if (!section) return;
if (!copy) {
if (window.confirm('删除此区块?保存页面后生效。')) {
removeSection(section);
$studio.find('[data-canvas-status]').text('区块已移除,保存页面后生效。');
}
return;
}
if (sections.filter(({version}) => version === null).length >= 50) return;
selectElement(null);
const clone = section.node.cloneNode(true);
const id = newSectionId();
scopeTemplateIds(clone, id, section.key);
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});
registerSection(clone, null, {template: copyOf ? null : section.template, copyOf});
renderLayers();
noteModule(clone, '模块副本将在保存页面后生效。');
clone.scrollIntoView({block: 'start'});
selectElement(clone);
$studio.find('[data-canvas-status]').text('已复制模块,保存页面后生效。');
}
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);
}
const template = doc.createElement('template');
template.innerHTML = markup;
if (template.content.querySelector('[id]')) scopeTemplateIds(template.content, newSectionId());
editBody(body, insertion, 'insertHTML', template.innerHTML);
}
$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;
const feed = this.dataset.templateFeed;
if ($presets.find('[data-template-inline]').prop('checked')) {
if (feed || this.dataset.templateStyle === 'layout') {
$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 skeleton = this.dataset.templateStyle === 'layout' ? doc.querySelector('[data-studio-section-layout]') : end;
const section = skeleton.content.firstElementChild.cloneNode(true);
const id = newSectionId();
section.id = id;
section.classList.replace('section-plain', 'section-' + this.dataset.templateStyle);
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="lead"]').textContent = this.dataset.templateLead || '';
const body = section.querySelector('[data-studio-part="body"]');
body.innerHTML = markup;
scopeTemplateIds(body, id);
if (feed) {
section.dataset.studioDynamic = '';
section.dataset.studioFeed = feed;
section.tabIndex = 0;
noteModule(section, '保存页面后将加载动态内容。');
}
end.before(section);
const entry = registerSection(section, null, {template});
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;
syncMemberSettings();
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();
syncMemberSettings();
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, input, textarea, select')) 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);
});
$settings.on('change', '[name="show_hero"]', () => {
if (initialOrder !== undefined) renderLayers();
});
function attachCanvas() {
doc = $frame.get(0).contentDocument;
if (!doc?.querySelector('[data-studio-field]') || doc.documentElement.hasAttribute('data-studio-editing')) return;
doc.documentElement.setAttribute('data-studio-editing', '');
doc.execCommand('defaultParagraphSeparator', false, 'p');
const $doc = $(doc);
$settings.find(':input').off('.canvas');
bindPage($doc);
selectBody(null);
selectElement(null);
sections = [];
deletedSections = [];
$doc.find('[data-studio-section]').each((_, section) => registerSection(section));
renderLayers();
initialOrder = canvasOrder();
syncMemberSettings();
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 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();
event.stopPropagation();
const dynamic = this.closest('[data-studio-dynamic]');
if (dynamic) {
selectBody(null);
selectElement(dynamic);
return;
}
selectBody(this.closest('[data-studio-part="body"]'));
selectElement(this);
if (event.type === 'dblclick') replaceMedia();
});
$doc.on('click.canvas', (event) => {
const node = event.target;
const dynamic = node.closest?.('[data-studio-dynamic]');
if (dynamic) {
selectBody(null);
selectElement(dynamic);
return;
}
const field = node.closest?.(canvasFields);
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();
if (!this.closest('[data-studio-dynamic]') && !event.target.closest(mediaTargets)) editResource(this);
});
$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) {
event.preventDefault();
selectBody(null);
selectElement(this);
$elementTools.find('[data-element-module-settings]').trigger('focus');
}
});
$doc.on('keydown.canvas', '[data-studio-hero-image]', function (event) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
selectElement(this);
$handle.trigger('focus');
}
});
$doc.on('beforeinput.canvas', '[contenteditable="plaintext-only"]', (event) => {
if (event.originalEvent?.inputType === 'insertParagraph' || event.originalEvent?.inputType === 'insertLineBreak') {
event.preventDefault();
}
});
$doc.on('keydown.canvas', '[contenteditable="true"]', function (event) {
if (event.key !== 'Enter' || event.originalEvent?.isComposing || event.altKey) return;
const paragraph = event.ctrlKey || event.metaKey;
event.preventDefault();
if (!paragraph || this.dataset.studioPart === 'body') {
doc.execCommand(paragraph ? 'insertParagraph' : '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') {
doc.execCommand('insertText', false, event.originalEvent.clipboardData.getData('text/plain'));
}
});
$toolbar.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();
});
$('[data-rich-canvas]').each(function () {
const $canvas = $(this);
const $editor = $canvas.closest('[data-editor]');
const $area = $editor.find('textarea');
const $form = $editor.closest('form');
const $status = $editor.find('[data-rich-status]');
const $visualButtons = $editor.find('[data-insert], [data-rich-media]');
let savedRange;
let source = false;
$area.prop('hidden', true);
$canvas.prop('hidden', false);
$form.on('studio:sync', () => {
if (!source) $area.val($canvas.html());
});
function restoreRange() {
const selection = window.getSelection();
const root = $canvas.get(0);
$canvas.trigger('focus');
if (!savedRange || !root.contains(savedRange.commonAncestorContainer)) {
savedRange = document.createRange();
savedRange.selectNodeContents(root);
savedRange.collapse(false);
}
selection.removeAllRanges();
selection.addRange(savedRange);
}
function edit(command, value) {
restoreRange();
document.execCommand(command, false, value);
}
$canvas.on('click', 'a', (event) => event.preventDefault());
$canvas.on('keyup mouseup focusout input', function () {
const selection = window.getSelection();
if (selection.rangeCount && this.contains(selection.anchorNode) && this.contains(selection.focusNode)) {
savedRange = selection.getRangeAt(0).cloneRange();
}
});
$canvas.on('paste', function (event) {
event.preventDefault();
document.execCommand('insertText', false, event.originalEvent.clipboardData.getData('text/plain'));
});
$editor.on('mousedown', '[data-insert], [data-rich-media]', (event) => event.preventDefault());
$editor.on('click', '[data-insert]', function () {
const command = $(this).data('insert');
if (command === 'link') {
const href = window.prompt('输入链接地址', 'https://')?.trim();
if (!href) return;
if (!safeLink(href)) {
$status.prop('hidden', false).text('请输入站内地址或有效的链接。');
return;
}
restoreRange();
const selection = window.getSelection();
if (selection.isCollapsed) {
edit('insertHTML', $('<a>', {href}).text(href).prop('outerHTML'));
} else {
edit('createLink', href);
}
return;
}
if (command === 'heading') edit('formatBlock', 'h3');
if (command === 'bold') edit('bold');
if (command === 'list') edit('insertUnorderedList');
});
$editor.on('click', '[data-rich-media]', function () {
openPicker('', (file) => {
const markup = mediaMarkup(file);
if (markup) edit('insertHTML', markup);
});
});
$editor.on('click', '[data-source-toggle]', function () {
const $button = $(this);
if (!source) {
$area.val($canvas.html()).prop('hidden', false).trigger('focus');
$canvas.prop('hidden', true);
$visualButtons.prop('disabled', true);
$button.text('返回可视化').attr('aria-pressed', 'true');
source = true;
return;
}
$button.prop('disabled', true);
$.ajax({
url: '/admin/preview',
method: 'POST',
dataType: 'text',
data: {csrf: $form.find('[name="csrf"]').val(), format: 'html', body: $area.val()}
}).done(function (html) {
$canvas.html(html).prop('hidden', false);
$area.prop('hidden', true);
$visualButtons.prop('disabled', false);
$button.text('HTML 源码').attr('aria-pressed', 'false');
$status.prop('hidden', true);
savedRange = null;
source = false;
}).fail(() => $status.prop('hidden', false).text('源码暂时无法转换,当前编辑内容已保留。'))
.always(() => $button.prop('disabled', false));
});
});
});