forked from laysense/laysite
2493 lines
128 KiB
JavaScript
2493 lines
128 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-field="eyebrow"], [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, td, th, caption, small';
|
|
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 $color = $toolbar.find('[data-canvas-color]');
|
|
const $clearColor = $toolbar.find('[data-clear-color]');
|
|
const $imageDisplay = $toolbar.find('[data-canvas-image-display]');
|
|
const $source = $studio.find('[data-canvas-source]');
|
|
const $sourcePart = $source.find('[data-source-part]');
|
|
const $sourceCode = $source.find('[data-source-code]');
|
|
const $sourceError = $source.find('[data-source-error]');
|
|
let sourceParts;
|
|
let sourceRequest;
|
|
let colorSheet;
|
|
const canvasColors = new Set();
|
|
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' || prefix === 'color' || Object.hasOwn(formatOptions, prefix))) result[prefix] = name;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
function installColor(token) {
|
|
if (!colorSheet || canvasColors.has(token) || !/^studio-style-color-[a-f0-9]{6}$/.test(token)) return;
|
|
colorSheet.insertRule('.' + token + '{color:#' + token.slice(-6) + '!important}', colorSheet.cssRules.length);
|
|
canvasColors.add(token);
|
|
}
|
|
|
|
function installMarkupColors(markup) {
|
|
for (const [token] of markup.matchAll(/\bstudio-style-color-[a-f0-9]{6}(?![\w-])/g)) installColor(token);
|
|
}
|
|
|
|
function putStyle(node, property, value) {
|
|
const current = classesOf(node)[property];
|
|
if (current) node.classList.remove(current);
|
|
if (value !== '') {
|
|
const token = 'studio-style-' + property + '-' + value;
|
|
if (property === 'color') installColor(token);
|
|
node.classList.add(token);
|
|
}
|
|
}
|
|
|
|
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);
|
|
});
|
|
}
|
|
if (node.dataset.studioPlaceholder) node.toggleAttribute('data-studio-empty', !value.trim());
|
|
}
|
|
|
|
function presentationOf(node, text = false) {
|
|
const classes = Object.values(classesOf(node)).join(' ');
|
|
let runs = text ? readRuns(node) : [];
|
|
const first = runs.findIndex(([part]) => part.trim() !== '');
|
|
if (first < 0) runs = [];
|
|
else {
|
|
runs = runs.slice(first, runs.findLastIndex(([part]) => part.trim() !== '') + 1);
|
|
runs[0][0] = runs[0][0].trimStart();
|
|
runs.at(-1)[0] = runs.at(-1)[0].trimEnd();
|
|
}
|
|
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 = {};
|
|
if (pageInput('canvas_breadcrumbs_custom').val() === '1') result.breadcrumbLinks = pageInput('canvas_breadcrumbs').val();
|
|
if (pageInput('canvas_eyebrow_custom').val() === '1') result.heroEyebrow = pageInput('eyebrow').val();
|
|
if (pageInput('canvas_hero_custom').val() === '1') result.heroHtml = cleanBody(doc.querySelector('[data-studio-hero-source]'));
|
|
$(doc).find('[data-studio-style-field]').each(function () {
|
|
const role = this.dataset.studioStyleField;
|
|
const style = presentationOf(this, this.matches(canvasFields));
|
|
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 !== null && (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) 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 computed = sample ? doc.defaultView.getComputedStyle(sample.nodeType === 1 ? sample : sample.parentElement) : null;
|
|
if (!$fontSize.is(':focus')) $fontSize.val(computed ? Math.round(parseFloat(computed.fontSize)) : '');
|
|
$color.add($clearColor).prop('disabled', !target);
|
|
const rgb = computed?.color.match(/^rgba?\((\d+), (\d+), (\d+)(?:, [\d.]+)?\)$/);
|
|
if (rgb && !$color.is(':focus')) $color.val('#' + rgb.slice(1).map((channel) => Number(channel).toString(16).padStart(2, '0')).join(''));
|
|
$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 (Object.hasOwn(formatOptions, property)) {
|
|
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 !== '' || property === 'color') {
|
|
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');
|
|
// Keep a reset inside the selected run, independent of surrounding color.
|
|
putStyle(span, property, property === 'color' && value === '' ? 'theme' : 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();
|
|
}
|
|
|
|
$color.on('change', function () {
|
|
if (/^#[0-9a-f]{6}$/i.test(this.value)) applyTextStyle('color', this.value.slice(1).toLowerCase());
|
|
});
|
|
$clearColor.on('click', () => applyTextStyle('color', ''));
|
|
$imageDisplay.on('change', function () {
|
|
if (selectedMedia?.matches('img')) putStyle(sizingTarget(), 'display', this.value);
|
|
positionSelection();
|
|
});
|
|
$toolbar.on('mousedown', '[data-canvas-format], [data-clear-color]', (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;
|
|
const update = () => node.toggleAttribute('data-studio-empty', !plainText(node));
|
|
$(node).on('input.studioPlaceholder', update);
|
|
update();
|
|
}
|
|
}
|
|
|
|
function bindPage($doc) {
|
|
const $body = $doc.find('body');
|
|
const visibilityInputs = ['show_hero', 'header_choice', 'footer_choice'];
|
|
const $heroInput = pageInput('show_hero');
|
|
const $heroSource = $doc.find('[data-studio-hero-source]');
|
|
const $managedHero = $doc.find('[data-studio-hero-content]');
|
|
$heroSource.attr({'contenteditable': 'true', 'aria-label': '首屏自定义 HTML'});
|
|
function syncHeroMode() {
|
|
const visible = $heroInput.val() !== '0';
|
|
const custom = pageInput('canvas_hero_custom').val() === '1';
|
|
$managedHero.prop('hidden', !visible || custom);
|
|
$heroSource.prop('hidden', !visible || !custom);
|
|
$doc.find('.page-photo-credit').prop('hidden', !visible);
|
|
}
|
|
$heroInput.on('change.canvas', () => {
|
|
selectElement(null);
|
|
syncHeroMode();
|
|
});
|
|
heroControls.set('mode', syncHeroMode);
|
|
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;
|
|
installMarkupColors(replacement.outerHTML);
|
|
$target.replaceWith(doc.importNode(replacement, true));
|
|
rendered = choice;
|
|
});
|
|
});
|
|
}
|
|
const labels = {eyebrow: '首屏眉题', 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.on('input', () => {
|
|
$input.val(plainText(this));
|
|
if (field === 'eyebrow') pageInput('canvas_eyebrow_custom').val('1');
|
|
});
|
|
$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('[data-studio-hero-content] .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('order-action', (order) => {
|
|
remapPageStyles('action', order);
|
|
actions = order.map((index) => actions[index]);
|
|
syncActions();
|
|
});
|
|
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 paths = {};
|
|
for (const [type, config] of Object.entries({
|
|
navigation: {container: '[data-studio-navigation]', field: 'quicklinks', heading: '本页目录', prefix: 'nav'},
|
|
breadcrumbs: {container: '[data-studio-breadcrumbs]', field: 'canvas_breadcrumbs', heading: '面包屑路径', prefix: 'crumb'},
|
|
})) {
|
|
const $container = $doc.find(config.container);
|
|
if (!$container.length) continue;
|
|
const crumb = type === 'breadcrumbs';
|
|
const $content = crumb ? $container : $container.find('.section-nav-inner');
|
|
const $input = pageInput(config.field);
|
|
const read = () => $input.val().split(/\r?\n/).flatMap((line) => {
|
|
if (!line.trim()) return [];
|
|
const [label, ...href] = line.split('|');
|
|
return [[href.join('|').trim(), label.trim()]];
|
|
});
|
|
const links = () => $content.find('a[data-studio-nav-index]');
|
|
const customize = () => { if (crumb) pageInput('canvas_breadcrumbs_custom').val('1'); };
|
|
const valid = (list) => list.length <= 20 && list.every(([url, label]) =>
|
|
safeLink(url) && url.length <= 1000 && label && Array.from(label).length <= 70 && !/[|\r\n]/.test(label));
|
|
const sync = () => {
|
|
const presentation = pagePresentation();
|
|
const items = read();
|
|
$content.empty();
|
|
items.forEach(([url, label], index) => {
|
|
if (crumb && index) $content.append($('<span>', {class: 'crumb-divider', 'aria-hidden': 'true', text: '/'}));
|
|
const role = config.prefix + '-' + index;
|
|
const $link = $('<a>', {href: safeLink(url) ? url : '#', 'data-studio-nav-index': index,
|
|
'data-studio-path-type': type, 'data-studio-style-field': role});
|
|
if (crumb && index === items.length - 1) $link.attr('aria-current', 'page');
|
|
const node = $link.get(0);
|
|
configureText(node, config.heading + '链接');
|
|
setPageStyle(node, presentation[role]);
|
|
paintText(node, label || url, presentation[role]?.runs);
|
|
$link.on('input', () => {
|
|
items[index][1] = plainText(node).replace(/[|\r\n]/g, ' ');
|
|
customize();
|
|
$input.val(items.map(([link, text]) => text + ' | ' + link).join('\n'));
|
|
});
|
|
$link.on('dblclick studio:properties', (event) => {
|
|
event.preventDefault();
|
|
openProperties(config.heading + '链接', {label: plainText(node), url}, (next) => {
|
|
const updated = read();
|
|
updated[index] = [next.url, next.label];
|
|
if (!valid(updated)) {
|
|
$propertyError.prop('hidden', false).text('请输入有效网址及不超过 70 个字符的文案,文案不能包含竖线。');
|
|
return false;
|
|
}
|
|
write(updated);
|
|
});
|
|
});
|
|
$content.append($link);
|
|
});
|
|
$container.prop('hidden', items.length === 0);
|
|
};
|
|
const write = (items) => {
|
|
syncPagePresentation();
|
|
customize();
|
|
$input.val(items.map(([url, label]) => label + ' | ' + url).join('\n'));
|
|
sync();
|
|
renderLayers();
|
|
};
|
|
paths[type] = {read, sync, write};
|
|
heroControls.set(type, () => {
|
|
const field = crumb ? 'breadcrumbs' : 'quicklinks';
|
|
openProperties(config.heading, {[field]: $input.val()}, (values) => {
|
|
const previous = $input.val();
|
|
$input.val(values[field]);
|
|
const next = read();
|
|
$input.val(previous);
|
|
if (!valid(next)) {
|
|
$propertyError.prop('hidden', false).text('每行填写「文案 | 链接」,最多 20 条。');
|
|
return false;
|
|
}
|
|
write(next);
|
|
});
|
|
});
|
|
heroControls.set('order-' + type, (order) => {
|
|
const items = read();
|
|
remapPageStyles(config.prefix, order);
|
|
customize();
|
|
$input.val(order.map((index) => items[index][1] + ' | ' + items[index][0]).join('\n'));
|
|
sync();
|
|
});
|
|
heroControls.set('change-' + type, (index, copy) => {
|
|
const items = read();
|
|
if (copy && items.length >= 20) return null;
|
|
const order = items.map((_, position) => position);
|
|
order.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [index] : []));
|
|
remapPageStyles(config.prefix, order);
|
|
customize();
|
|
$input.val(order.map((i) => items[i][1] + ' | ' + items[i][0]).join('\n'));
|
|
sync();
|
|
return links().get(index + 1);
|
|
});
|
|
}
|
|
pageInput('name').on('input.canvas', function () {
|
|
if (!paths.breadcrumbs || pageInput('canvas_breadcrumbs_custom').val() === '1') return;
|
|
const $input = pageInput('canvas_breadcrumbs');
|
|
const first = $input.val().split('\n')[0];
|
|
$input.val(first + '\n' + this.value.replace(/[|\r\n]/g, ' ') + ' | /' + $settings.attr('action').split('/').at(-1));
|
|
paths.breadcrumbs.sync();
|
|
renderLayers();
|
|
});
|
|
heroControls.set('remove-section-links', (key) => {
|
|
const anchor = '#' + key;
|
|
for (const [type, path] of Object.entries(paths)) {
|
|
const items = path.read();
|
|
const order = items.flatMap(([url], i) => url === anchor ? [] : [i]);
|
|
if (order.length === items.length) continue;
|
|
remapPageStyles(type === 'breadcrumbs' ? 'crumb' : 'nav', order);
|
|
const crumb = type === 'breadcrumbs';
|
|
if (crumb) pageInput('canvas_breadcrumbs_custom').val('1');
|
|
pageInput(crumb ? 'canvas_breadcrumbs' : 'quicklinks').val(order.map((i) => items[i][1] + ' | ' + items[i][0]).join('\n'));
|
|
path.sync();
|
|
}
|
|
if (actions.some(([url]) => url === anchor)) {
|
|
remapPageStyles('action', actions.flatMap(([url], i) => url === anchor ? [] : [i]));
|
|
actions = actions.filter(([url]) => url !== anchor);
|
|
syncActions();
|
|
}
|
|
});
|
|
syncPageFromInputs = () => {
|
|
const presentation = pagePresentation();
|
|
$heroSource.html(presentation.heroHtml ?? '');
|
|
installMarkupColors(presentation.heroHtml ?? '');
|
|
$doc.find('[data-studio-field]').each(function () {
|
|
const field = this.dataset.studioField;
|
|
paintText(this, pageInput(field).val(), presentation[field]?.runs);
|
|
});
|
|
$doc.find('[data-studio-style-field]').each(function () {
|
|
setPageStyle(this, presentation[this.dataset.studioStyleField]);
|
|
});
|
|
const values = JSON.parse(pageInput('alignments').val());
|
|
$doc.find('[data-studio-align-field]').each(function () {
|
|
this.classList.remove(...alignmentClasses);
|
|
if (values[this.dataset.studioAlignField]) this.classList.add('studio-align-' + values[this.dataset.studioAlignField]);
|
|
});
|
|
visibilityInputs.forEach((field) => pageInput(field).triggerHandler('change.canvas'));
|
|
pageInput('palette_id').triggerHandler('change.canvas');
|
|
actions = readActions();
|
|
syncActions();
|
|
Object.values(paths).forEach(({sync}) => sync());
|
|
syncImage();
|
|
};
|
|
syncPageFromInputs();
|
|
}
|
|
|
|
function editResource(node) {
|
|
const tag = node.localName;
|
|
if (node.matches('a.studio-member-slot') && $settings.find('[data-shared-auth]').length) {
|
|
syncMemberSettings();
|
|
$settings.find('[data-shared-auth]').prop('open', true).find('[name=provider_mode]').trigger('focus');
|
|
return;
|
|
}
|
|
if (tag === 'progress') {
|
|
openProperties('进度条', {value: node.getAttribute('value') || '0', max: node.getAttribute('max') || '100'}, ({value, max}) => {
|
|
if (!/^\d+$/.test(value) || !/^\d+$/.test(max) || Number(max) < 1 || Number(value) > Number(max)) {
|
|
$propertyError.prop('hidden', false).text('请输入不超过最大值的非负整数。');
|
|
return false;
|
|
}
|
|
node.max = Number(max);
|
|
node.value = Number(value);
|
|
node.textContent = Math.round(100 * node.value / node.max) + '%';
|
|
});
|
|
return;
|
|
}
|
|
if (tag === 'a') {
|
|
const product = node.parentElement.matches('.hero-directory');
|
|
const title = product ? node.querySelector(':scope > span') : null;
|
|
const note = product ? node.querySelector(':scope > small') : null;
|
|
const onlyChild = node.firstElementChild;
|
|
const text = title || (node.childElementCount === 0 ? node : (
|
|
node.childElementCount === 1 && onlyChild.matches('span, strong, b, em, i, small')
|
|
&& !onlyChild.childElementCount && node.textContent.trim() === onlyChild.textContent.trim() ? onlyChild : null
|
|
));
|
|
const values = text ? {label: text.textContent, url: node.getAttribute('href') || ''} : {url: node.getAttribute('href') || ''};
|
|
if (title) values.note = note?.textContent || '';
|
|
values.newTab = node.target === '_blank' ? '1' : '0';
|
|
if (node.classList.contains('button')) {
|
|
values.buttonStyle = Object.keys(buttonClasses).find((style) => node.classList.contains(buttonClasses[style])) || 'plain';
|
|
}
|
|
openProperties(product ? '导航卡片' : '正文链接', values, ({label, note: description, url, newTab, buttonStyle}) => {
|
|
if (text && !label) {
|
|
$propertyError.prop('hidden', false).text('请填写链接文案。');
|
|
return false;
|
|
}
|
|
node.setAttribute('href', url);
|
|
if (newTab === '1') {
|
|
$(node).attr({target: '_blank', rel: 'noopener noreferrer'});
|
|
} else {
|
|
$(node).removeAttr('target rel');
|
|
}
|
|
if (buttonStyle) $(node).removeClass(Object.values(buttonClasses)).addClass(buttonClasses[buttonStyle]);
|
|
if (text && label !== values.label) text.textContent = label;
|
|
if (description !== undefined) {
|
|
if (note) $(note).text(description);
|
|
else if (description) $('<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 (body) {
|
|
node.contentEditable = 'true';
|
|
node.setAttribute('aria-label', label);
|
|
node.dataset.studioPlaceholder = label;
|
|
} else if (!node.hidden && !body) {
|
|
configureText(node, label, part === 'lead');
|
|
}
|
|
fields[part] = {node, initial: body ? node.innerHTML : plainText(node), initialAlignment: body ? '' : getAlignment(node)};
|
|
}
|
|
const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from(
|
|
atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0)
|
|
));
|
|
const entry = {node: section, key: section.id, version, fields, source, feed, initialFeed: JSON.stringify(feed),
|
|
parent: section.parentNode, fixed: section.classList.contains('hero-directory-slot'), ...metadata};
|
|
entry.initialPresentation = JSON.stringify(sectionPresentation(entry));
|
|
sections.push(entry);
|
|
return entry;
|
|
}
|
|
|
|
function setMediaWidth(node, width) {
|
|
for (const token of Array.from(node.classList).filter((name) => mediaWidthClass.test(name))) {
|
|
node.classList.remove(token);
|
|
}
|
|
if (Number(width)) node.classList.add('studio-media-' + width);
|
|
else if (!node.classList.length) node.removeAttribute('class');
|
|
}
|
|
|
|
function sizingTarget() {
|
|
if (!selectedMedia?.isConnected) return null;
|
|
return selectedMedia.hasAttribute('data-studio-hero-image') ? selectedMedia.parentElement : selectedMedia;
|
|
}
|
|
|
|
function frameScale() {
|
|
const frame = $frame.get(0);
|
|
return frame.getBoundingClientRect().width / frame.offsetWidth;
|
|
}
|
|
|
|
function previewBounds(node) {
|
|
const frame = $frame.get(0).getBoundingClientRect();
|
|
const container = $window.get(0);
|
|
const origin = container.getBoundingClientRect();
|
|
const bounds = node.getBoundingClientRect();
|
|
const scale = frameScale();
|
|
const x = frame.left - origin.left - container.clientLeft;
|
|
const y = frame.top - origin.top - container.clientTop;
|
|
return {
|
|
left: x + bounds.left * scale, right: x + bounds.right * scale,
|
|
top: y + bounds.top * scale, bottom: y + bounds.bottom * scale,
|
|
width: bounds.width * scale, height: bounds.height * scale,
|
|
};
|
|
}
|
|
|
|
function positionSelection() {
|
|
const container = $window.get(0);
|
|
const node = sizingTarget();
|
|
if (node) {
|
|
const bounds = previewBounds(node);
|
|
const x = getAlignment(node) === 'right' ? bounds.left : bounds.right;
|
|
const y = (bounds.top + bounds.bottom) / 2;
|
|
const visible = bounds.width > 0 && y >= 0 && y <= container.clientHeight
|
|
&& x >= 0 && x <= container.clientWidth + 1;
|
|
$handle.prop('hidden', !mediaDrag && !visible);
|
|
$handle.css({left: Math.max(11, Math.min(x, container.clientWidth - 11)), top: y});
|
|
} else {
|
|
$handle.prop('hidden', true);
|
|
}
|
|
if (!selectedElement?.isConnected) {
|
|
$elementTools.prop('hidden', true);
|
|
return;
|
|
}
|
|
const bounds = previewBounds(selectedElement);
|
|
const visible = bounds.width > 0 && bounds.height > 0 && bounds.right > 0
|
|
&& bounds.left < container.clientWidth && bounds.bottom > 0 && bounds.top < container.clientHeight;
|
|
$elementTools.prop('hidden', !visible);
|
|
if (!visible) return;
|
|
const maxX = container.clientWidth - $elementTools.outerWidth() - 5;
|
|
const height = $elementTools.outerHeight();
|
|
const above = bounds.top - height - 5;
|
|
const below = bounds.bottom + 5;
|
|
const y = above >= 5 || below + height > container.clientHeight ? above : below;
|
|
$elementTools.css({
|
|
left: Math.max(5, Math.min(bounds.left, maxX)),
|
|
top: Math.max(5, Math.min(y, container.clientHeight - height - 5)),
|
|
});
|
|
}
|
|
|
|
function currentMediaWidth(node) {
|
|
return Number(Array.from(node.classList).find((name) => mediaWidthClass.test(name))?.slice('studio-media-'.length)) || 0;
|
|
}
|
|
|
|
function showMediaWidth(width) {
|
|
$mediaSize.text(width ? width + '%' : '原始尺寸');
|
|
$handle.attr({'aria-valuenow': width || 100, 'aria-valuetext': width ? width + '%' : '原始尺寸'});
|
|
}
|
|
|
|
function editableBodyElement(node) {
|
|
const body = node.closest('[data-studio-part="body"]');
|
|
if (!body) return null;
|
|
const element = node.closest(bodyElements) || node.closest('span');
|
|
if (element?.contains(body)) return node.closest('span');
|
|
return element !== body && body.contains(element) ? element : null;
|
|
}
|
|
|
|
function getAlignment(node) {
|
|
return alignments.find((value) => node.classList.contains('studio-align-' + value)) || '';
|
|
}
|
|
|
|
function alignmentTarget(node) {
|
|
if (!node) return null;
|
|
const hero = node.closest('[data-studio-align-field]');
|
|
if (hero) return hero;
|
|
return node.matches('[data-studio-part="title"], [data-studio-part="lead"]') || node.parentElement?.closest('[data-studio-part="body"]')
|
|
? node : null;
|
|
}
|
|
|
|
function syncAlignmentButtons(target) {
|
|
$alignTools.prop('hidden', !target).find('[data-align]').each(function () {
|
|
$(this).attr('aria-pressed', String(Boolean(target) && getAlignment(target) === this.dataset.align));
|
|
});
|
|
}
|
|
|
|
function selectElement(node) {
|
|
selectionObserver?.disconnect();
|
|
selectedElement?.removeAttribute('data-studio-selected');
|
|
if (node && textHost && !node.contains(textHost) && !textHost.contains(node)) {
|
|
textHost = null;
|
|
textRange = null;
|
|
}
|
|
selectedElement = node;
|
|
const dynamic = node?.hasAttribute('data-studio-dynamic');
|
|
$elementTools.toggleClass('is-module', Boolean(dynamic)).find('[data-element-module-settings]').prop('hidden', !dynamic);
|
|
$elementTools.find('[data-element-spacing]').prop('hidden', !styleTarget(node));
|
|
$elementTools.find('[data-element-parent]').prop('hidden', !parentElement(node));
|
|
$elementTools.find('[data-element-source]').prop('hidden', !node?.matches('[data-studio-section], [data-studio-hero]'));
|
|
selectedMedia = node?.matches(mediaTargets) ? node : null;
|
|
$sizing.prop('hidden', !selectedMedia);
|
|
$imageDisplay.prop('disabled', !selectedMedia?.matches('img')).val(classesOf(sizingTarget() || doc.documentElement).display?.slice('studio-style-display-'.length) || '');
|
|
$layers.find('.studio-layer-row[aria-current]').removeAttr('aria-current');
|
|
if (node) {
|
|
node.setAttribute('data-studio-selected', '');
|
|
const target = sizingTarget();
|
|
const nav = node.hasAttribute('data-studio-nav-index');
|
|
const inBody = Boolean(node.parentElement?.closest('[data-studio-part="body"]'));
|
|
const action = node.hasAttribute('data-studio-action');
|
|
const canCopy = dynamic || inBody || (nav && $(node).siblings().length < 19) || (action && $(node).siblings().length < 7);
|
|
const hasProperties = !dynamic && (selectedMedia || node.matches('a, progress'));
|
|
const aligned = dynamic ? null : alignmentTarget(node);
|
|
syncAlignmentButtons(aligned);
|
|
$elementTools.find('[data-element-copy]').prop('hidden', !canCopy);
|
|
const sectionRoot = node.hasAttribute('data-studio-section');
|
|
const hero = node.hasAttribute('data-studio-hero') && isHeroVisible();
|
|
const deleteLabel = hero || node.dataset.studioField === 'heading' ? '删除首屏'
|
|
: node.dataset.studioPart === 'title' || sectionRoot ? '删除区块' : '删除';
|
|
$elementTools.find('[data-element-delete]').attr({'aria-label': deleteLabel, title: deleteLabel})
|
|
.prop('hidden', !hero && !sectionRoot && !inBody && !selectedMedia && !node.matches(canvasFields));
|
|
$elementTools.find('[data-element-properties]').prop('hidden', !hasProperties && !node.matches('[data-studio-navigation], [data-studio-breadcrumbs]'));
|
|
$layers.find('.studio-layer-row').filter((_, row) => $(row).data('canvasNode') === node).attr('aria-current', 'true');
|
|
if (target) showMediaWidth(currentMediaWidth(target));
|
|
selectionObserver?.observe(target || aligned || node);
|
|
}
|
|
syncFormatControls();
|
|
positionSelection();
|
|
}
|
|
|
|
function changeElement(copy) {
|
|
const node = selectedElement;
|
|
if (!node?.isConnected) return;
|
|
if (node.hasAttribute('data-studio-section')) {
|
|
changeModule(sections.find((section) => section.node === node), copy);
|
|
return;
|
|
}
|
|
const {studioField, studioAction, studioNavIndex} = node.dataset;
|
|
if (!copy && (studioField === 'heading' || node.hasAttribute('data-studio-hero'))) {
|
|
removeHero();
|
|
return;
|
|
}
|
|
if (!copy && node.dataset.studioPart === 'title') {
|
|
changeModule(sections.find((section) => section.node === node.closest('[data-studio-section]')), false);
|
|
return;
|
|
}
|
|
const inBody = Boolean(node.parentElement?.closest('[data-studio-part="body"]'));
|
|
selectElement(null);
|
|
if (inBody) {
|
|
if (copy) {
|
|
const $clone = $(node.cloneNode(true));
|
|
$clone.find('[id]').addBack('[id]').removeAttr('id');
|
|
$(node).after($clone);
|
|
selectElement($clone.get(0));
|
|
} else {
|
|
$(node).remove();
|
|
savedRange = null;
|
|
}
|
|
} else if (studioAction !== undefined) {
|
|
const next = heroControls.get('change-action')(Number(studioAction), copy);
|
|
if (copy && next) selectElement(next);
|
|
} else if (studioNavIndex !== undefined) {
|
|
const next = heroControls.get('change-' + node.dataset.studioPathType)(Number(studioNavIndex), copy);
|
|
if (copy && next) selectElement(next);
|
|
} else if (!copy) {
|
|
if (node.hasAttribute('data-studio-hero-image')) {
|
|
heroControls.get('remove-image')();
|
|
|
|
} else if (studioField) {
|
|
pageInput(studioField).val('').trigger('input');
|
|
} else {
|
|
$(node).text('');
|
|
}
|
|
}
|
|
}
|
|
|
|
$elementTools.on('click', '[data-align]', function () {
|
|
const target = alignmentTarget(selectedElement);
|
|
const alignment = this.dataset.align;
|
|
if (!target || !alignments.includes(alignment)) return;
|
|
target.classList.remove(...alignmentClasses);
|
|
target.classList.add('studio-align-' + alignment);
|
|
const field = target.dataset.studioAlignField;
|
|
if (field) {
|
|
const $value = pageInput('alignments');
|
|
const values = {...JSON.parse($value.val())};
|
|
values[field] = alignment;
|
|
$value.val(JSON.stringify(values));
|
|
}
|
|
syncAlignmentButtons(target);
|
|
positionSelection();
|
|
}).on('click', '[data-element-copy]', () => changeElement(true))
|
|
.on('click', '[data-element-delete]', () => changeElement(false))
|
|
.on('click', '[data-element-properties]', () => {
|
|
if (selectedMedia) replaceMedia();
|
|
else if (selectedElement?.matches('[data-studio-navigation], [data-studio-breadcrumbs]')) {
|
|
heroControls.get(selectedElement.hasAttribute('data-studio-breadcrumbs') ? 'breadcrumbs' : 'navigation')();
|
|
} else if (selectedElement?.hasAttribute('data-studio-action')) {
|
|
heroControls.get('edit-action')(Number(selectedElement.dataset.studioAction));
|
|
} else if (selectedElement?.matches('[data-studio-nav-index]')) {
|
|
$(selectedElement).triggerHandler('studio:properties');
|
|
} else if (selectedElement?.matches('a, progress')) {
|
|
editResource(selectedElement);
|
|
}
|
|
}).on('click', '[data-element-source]', () => openSource(selectedElement))
|
|
.on('keydown', (event) => {
|
|
if (event.key === 'Escape') selectElement(null);
|
|
});
|
|
|
|
function noteModule(section, text) {
|
|
const $body = $(section).find('[data-studio-part="body"]');
|
|
let $note = $(section).find('[data-studio-module-note]');
|
|
if (!$note.length) $note = $('<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(plainText(fields.title.node));
|
|
moduleInput('module_lead').val(plainText(fields.lead.node));
|
|
moduleInput('feed_mode').val(feed.mode);
|
|
moduleInput('feed_limit').val(feed.limit);
|
|
moduleInput('feed_categories[]').each(function () {
|
|
this.checked = feed.categories.includes(this.value);
|
|
});
|
|
$moduleDialog.find('[data-module-error]').prop('hidden', true);
|
|
$moduleDialog.get(0).showModal();
|
|
});
|
|
$moduleDialog.on('click', '[data-module-close]', () => $moduleDialog.get(0).close());
|
|
$moduleForm.on('submit', (event) => {
|
|
event.preventDefault();
|
|
const categories = moduleInput('feed_categories[]').filter(':checked').map((_, node) => node.value).get();
|
|
const title = moduleInput('module_title').val().trim();
|
|
if (!title || !categories.length) {
|
|
$moduleDialog.find('[data-module-error]').text('请填写标题并至少选择一个分类。').prop('hidden', false);
|
|
return;
|
|
}
|
|
const {node, fields} = editedModule;
|
|
editedModule.feed = {mode: moduleInput('feed_mode').val(), categories, limit: Number(moduleInput('feed_limit').val())};
|
|
if (plainText(fields.title.node) !== title) paintText(fields.title.node, title);
|
|
const lead = moduleInput('module_lead').val().trim();
|
|
if (plainText(fields.lead.node) !== lead) paintText(fields.lead.node, lead);
|
|
noteModule(node, '模块设置将在保存页面后更新。');
|
|
refreshLayerTitle(editedModule);
|
|
$moduleDialog.get(0).close();
|
|
positionSelection();
|
|
});
|
|
|
|
function newSectionId() {
|
|
return 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
}
|
|
|
|
function refreshLayerTitle(section) {
|
|
const title = plainText(section.fields.title.node) || '未命名区块';
|
|
$layers.find('.studio-layer-row').filter((_, row) => $(row).data('canvasNode') === section.node)
|
|
.find('.studio-layer-label').text(title);
|
|
}
|
|
|
|
function isHeroVisible() {
|
|
return pageInput('show_hero').val() === '1';
|
|
}
|
|
|
|
function removeHero() {
|
|
if (!isHeroVisible()) return;
|
|
selectBody(null);
|
|
textHost = null;
|
|
textRange = null;
|
|
doc.getSelection().removeAllRanges();
|
|
pageInput('show_hero').val('0').trigger('change');
|
|
$studio.find('[data-canvas-status]').text('首屏已移除,可撤销或在页面设置中恢复。');
|
|
}
|
|
|
|
function locateLayer(node, body = null) {
|
|
doc.getSelection().removeAllRanges();
|
|
textRange = null;
|
|
textHost = null;
|
|
selectBody(body);
|
|
$studio.get(0).scrollIntoView({block: 'start'});
|
|
node.scrollIntoView({block: 'start'});
|
|
selectElement(node);
|
|
}
|
|
|
|
function openSource(node) {
|
|
if (!node?.isConnected) return;
|
|
const entry = sections.find((section) => section.node === node);
|
|
const hero = node.hasAttribute('data-studio-hero');
|
|
if (!entry && !hero) return;
|
|
const parts = new Map();
|
|
if (hero) {
|
|
const target = node.querySelector('[data-studio-hero-source]');
|
|
const managed = node.querySelector('[data-studio-hero-content]');
|
|
const custom = pageInput('canvas_hero_custom').val() === '1';
|
|
const clone = managed.cloneNode(true);
|
|
clone.removeAttribute('hidden');
|
|
$(clone).find('[hidden]').remove();
|
|
$(clone).find('img:not([src]), [data-studio-field="accent"]:empty, [data-studio-field="lead"]:empty').remove();
|
|
// The saved markup contains only public content, with editor attributes removed by the server.
|
|
parts.set('hero', {label: '首屏完整内容', node: target, original: custom ? cleanBody(target) : clone.outerHTML});
|
|
$source.find('[data-source-reset]').prop('hidden', !custom);
|
|
} else {
|
|
for (const [key, label] of Object.entries({body: '区块正文', title: '区块标题', lead: '区块简介'})) {
|
|
const node = entry.fields[key].node;
|
|
parts.set(key, {label, node, original: key === 'body' ? cleanBody(node) : node.innerHTML});
|
|
}
|
|
$source.find('[data-source-reset]').prop('hidden', true);
|
|
}
|
|
for (const part of parts.values()) part.draft = part.original;
|
|
sourceParts = parts;
|
|
$sourcePart.empty();
|
|
for (const [key, {label}] of parts) $('<option>', {value: key, text: label}).appendTo($sourcePart);
|
|
$sourcePart.prop('disabled', hero).triggerHandler('change');
|
|
$source.find('[data-source-hint]').text(hero
|
|
? '应用后可继续在画布上编辑自定义首屏。原首屏可随时恢复。'
|
|
: '可编辑标题、简介和正文。区块外壳与动态文章列表由系统渲染。');
|
|
$sourceError.prop('hidden', true);
|
|
$source.get(0).showModal();
|
|
$sourceCode.trigger('focus');
|
|
}
|
|
|
|
$sourcePart.on('change', () => {
|
|
$sourceCode.val(sourceParts.get($sourcePart.val()).draft);
|
|
$sourceError.prop('hidden', true);
|
|
});
|
|
$sourceCode.on('input', () => { sourceParts.get($sourcePart.val()).draft = $sourceCode.val(); });
|
|
$source.on('click', '[data-source-close]', () => $source.get(0).close()).on('close', () => {
|
|
sourceRequest?.forEach((request) => request.abort());
|
|
sourceRequest = null;
|
|
sourceParts = null;
|
|
}).on('click', '[data-source-reset]', () => {
|
|
pageInput('canvas_hero_custom').val('0');
|
|
heroControls.get('mode')();
|
|
$source.get(0).close();
|
|
renderLayers();
|
|
captureHistory();
|
|
});
|
|
$source.find('form').on('submit', async (event) => {
|
|
event.preventDefault();
|
|
if (sourceRequest) return;
|
|
const parts = sourceParts;
|
|
const changed = [...parts].filter(([, part]) => part.draft !== part.original);
|
|
if (!changed.length) {
|
|
$source.get(0).close();
|
|
return;
|
|
}
|
|
const $submit = $source.find('[type=submit]').prop('disabled', true);
|
|
$sourceError.prop('hidden', true);
|
|
sourceRequest = changed.map(([, part]) => $.ajax({
|
|
url: '/admin/preview', method: 'POST', dataType: 'text',
|
|
data: {csrf: pageInput('csrf').val(), format: 'html', body: part.draft},
|
|
}));
|
|
try {
|
|
const markup = await Promise.all(sourceRequest);
|
|
if (!$source.get(0).open || sourceParts !== parts || changed.some(([, part]) => !part.node.isConnected)) return;
|
|
const fragments = markup.map((html, index) => {
|
|
const template = doc.createElement('template');
|
|
template.innerHTML = html;
|
|
const key = changed[index][0];
|
|
if (key === 'title' || key === 'lead') {
|
|
for (const element of template.content.querySelectorAll('*')) {
|
|
const format = {b: ['weight', 'bold'], strong: ['weight', 'bold'], i: ['slant', 'italic'],
|
|
em: ['slant', 'italic'], s: ['strike', 'on']}[element.localName];
|
|
if (format) putStyle(element, ...format);
|
|
else if (!element.matches('span, br')) throw new Error('标题和简介支持 span、br、strong、em 和 s 等行内格式。');
|
|
}
|
|
if (key === 'title' && !plainText(template.content)) throw new Error('请保留区块标题。');
|
|
}
|
|
return template.content;
|
|
});
|
|
selectElement(null);
|
|
changed.forEach(([key, {node}], index) => {
|
|
installMarkupColors(markup[index]);
|
|
node.replaceChildren(fragments[index]);
|
|
if (node.dataset.studioPlaceholder) node.toggleAttribute('data-studio-empty', !plainText(node));
|
|
if (key === 'hero') {
|
|
pageInput('canvas_hero_custom').val('1');
|
|
heroControls.get('mode')();
|
|
}
|
|
});
|
|
$source.get(0).close();
|
|
renderLayers();
|
|
captureHistory();
|
|
} catch (error) {
|
|
if ($source.get(0).open && sourceParts === parts) {
|
|
const message = error instanceof Error ? error.message : '无法处理 HTML,请检查源码长度或登录状态。';
|
|
$sourceError.text(message).prop('hidden', false);
|
|
}
|
|
} finally {
|
|
if (sourceParts === parts) sourceRequest = null;
|
|
$submit.prop('disabled', false);
|
|
}
|
|
});
|
|
|
|
const expandedLayers = new WeakSet();
|
|
const closedLayers = new WeakSet();
|
|
let draggedLayer;
|
|
let dropHint;
|
|
let layerTimer;
|
|
const layerActions = {
|
|
jump: ['target', '定位'], up: ['up', '上移'], down: ['down', '下移'],
|
|
delete: ['delete', '删除'], source: ['code', '编辑 HTML'],
|
|
};
|
|
|
|
function layerButton(type, directionDisabled = false) {
|
|
const [icon, label] = layerActions[type];
|
|
const content = $layout.find('template[data-layer-icon="' + icon + '"]').get(0).content.cloneNode(true);
|
|
return $('<button>', {type: 'button', class: 'button button-outline', 'aria-label': label, title: label,
|
|
'data-layer-operation': type, disabled: directionDisabled}).append(content);
|
|
}
|
|
|
|
function layerChildren(node) {
|
|
const authored = node.closest('[data-studio-part="body"]');
|
|
return [...node.children].filter((child) => (authored || !child.hidden)
|
|
&& !child.matches('meta, template, [data-studio-module-note]') && (authored || !child.matches('[aria-hidden="true"]')));
|
|
}
|
|
|
|
function layerName(node) {
|
|
const structure = {'wrap': '内容宽度容器', 'section-heading': '标题与简介', 'hero-copy': '首屏文案',
|
|
'hero-inner': '首屏布局', 'hero-actions': '首屏按钮', 'section-nav-inner': '目录链接'};
|
|
if (node.dataset.studioPart === 'body') return '区块正文';
|
|
const group = Object.keys(structure).find((name) => node.classList.contains(name));
|
|
if (group) return structure[group];
|
|
const tag = node.localName;
|
|
const authoredLabel = node.matches('img') ? node.alt : node.firstChild?.nodeType === 3 ? node.firstChild.textContent.trim() : '';
|
|
const types = {img: '图片', a: '链接', nav: '导航', div: '容器', section: '分区', p: '段落', br: '换行'};
|
|
return (authoredLabel || node.getAttribute('aria-label') || types[tag] || tag).slice(0, 38);
|
|
}
|
|
|
|
function layerContext(node) {
|
|
if (!node?.isConnected) return null;
|
|
const entry = sections.find((section) => section.node === node);
|
|
if (entry) return entry.fixed ? null : 'section';
|
|
if (node.hasAttribute('data-studio-action')) return 'action';
|
|
if (node.hasAttribute('data-studio-nav-index')) return node.dataset.studioPathType;
|
|
return node.parentElement?.closest('[data-studio-part="body"]') ? 'body' : null;
|
|
}
|
|
|
|
function pathLayers(node) {
|
|
return [...node.parentElement.children].filter((element) => element.matches('[data-studio-action], [data-studio-nav-index]'));
|
|
}
|
|
|
|
function moveLayer(source, target, where) {
|
|
if (!canDropLayer(source, target, where)) return null;
|
|
const kind = layerContext(source);
|
|
let moved = source;
|
|
if (kind === 'section') {
|
|
const entry = sections.find(({node}) => node === source);
|
|
sections = sections.filter((item) => item !== entry);
|
|
const index = sections.findIndex(({node}) => node === target);
|
|
sections.splice(index + Number(where === 'after'), 0, entry);
|
|
}
|
|
if (kind === 'body' || kind === 'section') {
|
|
if (where === 'inside') {
|
|
target.append(source);
|
|
expandedLayers.add(target);
|
|
} else target[where](source);
|
|
} else {
|
|
const links = pathLayers(source);
|
|
const order = links.map((_, index) => index);
|
|
const previous = links.indexOf(source);
|
|
order.splice(previous, 1);
|
|
const next = order.indexOf(links.indexOf(target)) + Number(where === 'after');
|
|
order.splice(next, 0, previous);
|
|
const parent = source.parentElement;
|
|
selectElement(null);
|
|
heroControls.get('order-' + kind)(order);
|
|
moved = parent.querySelector(kind === 'action'
|
|
? '[data-studio-action="' + next + '"]' : '[data-studio-nav-index="' + next + '"]');
|
|
}
|
|
captureHistory();
|
|
renderLayers();
|
|
positionSelection();
|
|
return moved;
|
|
}
|
|
|
|
const phrasing = new Set('a b br button code em i img label progress s small span strong'.split(' '));
|
|
const textContainers = new Set('a b button code em h1 h2 h3 h4 h5 h6 i label p pre s small span strong summary'.split(' '));
|
|
const allowedParents = {
|
|
li: ['ul', 'ol'], dt: ['dl'], dd: ['dl'], summary: ['details'], figcaption: ['figure'],
|
|
source: ['audio', 'video'], caption: ['table'], thead: ['table'], tbody: ['table'], tfoot: ['table'], tr: ['thead', 'tbody', 'tfoot'],
|
|
td: ['tr'], th: ['tr'],
|
|
};
|
|
const specialParents = new Set(Object.values(allowedParents).flat().filter((tag) => !['details', 'figure'].includes(tag)));
|
|
|
|
function canDropLayer(source, target, where) {
|
|
const kind = layerContext(source);
|
|
if (!kind || !target?.isConnected || source === target || source.contains(target)) return false;
|
|
if (kind !== 'body') return where !== 'inside' && kind === layerContext(target)
|
|
&& (kind === 'section' || source.parentElement === target.parentElement);
|
|
const parent = where === 'inside' ? target : target.parentElement;
|
|
if (!parent?.closest('[data-studio-part="body"]')) return false;
|
|
const tag = source.localName;
|
|
const container = parent.localName;
|
|
if (parent.matches('br, hr, img, progress, source') || parent.closest('a, button') && (source.matches('a, button') || source.querySelector('a, button'))) return false;
|
|
if (textContainers.has(container)) return phrasing.has(tag);
|
|
if (allowedParents[tag]) return allowedParents[tag].includes(container);
|
|
return !specialParents.has(container);
|
|
}
|
|
|
|
function adjacentLayer(node, offset) {
|
|
const kind = layerContext(node);
|
|
if (kind === 'section') {
|
|
const ordered = sections.filter(({fixed}) => !fixed);
|
|
return ordered[ordered.findIndex((entry) => entry.node === node) + offset]?.node;
|
|
}
|
|
if (kind === 'body') return offset < 0 ? node.previousElementSibling : node.nextElementSibling;
|
|
const links = pathLayers(node);
|
|
return links[links.indexOf(node) + offset];
|
|
}
|
|
|
|
function layerRow($list, node, label = '', entry = null, root = false) {
|
|
const $item = $('<li>').appendTo($list);
|
|
const $row = $('<div>', {class: 'studio-layer-row', draggable: Boolean(layerContext(node))})
|
|
.data('canvasNode', node).appendTo($item);
|
|
if (node === selectedElement) $row.attr('aria-current', 'true');
|
|
const $caption = $('<div>', {class: 'studio-layer-caption'}).appendTo($row);
|
|
if (node.hidden) $('<small>', {text: '隐藏'}).appendTo($caption);
|
|
$('<span>', {class: 'studio-layer-label', text: label || layerName(node)}).appendTo($caption);
|
|
if (!root) $('<small>').text(node.localName).appendTo($caption);
|
|
if (entry && entry.feed !== null) $('<span>', {class: 'studio-dynamic-badge', text: '动态'}).appendTo($caption);
|
|
const $actions = $('<div>', {class: 'studio-layer-actions'}).appendTo($row);
|
|
$actions.append(layerButton('jump'));
|
|
if (layerContext(node)) {
|
|
$actions.append(layerButton('up', !canDropLayer(node, adjacentLayer(node, -1), 'before')),
|
|
layerButton('down', !canDropLayer(node, adjacentLayer(node, 1), 'after')));
|
|
}
|
|
if (root && (entry || node.hasAttribute('data-studio-hero'))) $actions.append(layerButton('source'));
|
|
if (entry || layerContext(node) || node.hasAttribute('data-studio-hero')) $actions.append(layerButton('delete'));
|
|
if (entry?.version != null) {
|
|
const icon = $layout.find('template[data-layer-icon="settings"]').get(0).content.cloneNode(true);
|
|
$('<a>', {class: 'button button-outline', href: $settings.attr('action') + '/' + entry.key,
|
|
title: '区块设置', 'aria-label': '区块设置'}).append(icon).appendTo($actions);
|
|
}
|
|
const children = layerChildren(node).filter((child) => !child.hasAttribute('data-studio-section'));
|
|
if (!children.length) return;
|
|
const $details = $('<details>', {class: 'studio-layer-details',
|
|
open: expandedLayers.has(node) || root && !closedLayers.has(node)}).appendTo($item);
|
|
const $summary = $('<summary>').text('子图层 · ' + children.length).appendTo($details);
|
|
function showChildren() {
|
|
if ($details.children('ul').length) return;
|
|
const $children = $('<ul>', {class: 'studio-layer-tree'}).appendTo($details);
|
|
for (const child of children) layerRow($children, child);
|
|
}
|
|
function syncDisclosure() {
|
|
if ($details.prop('open')) {
|
|
expandedLayers.add(node);
|
|
closedLayers.delete(node);
|
|
showChildren();
|
|
} else {
|
|
expandedLayers.delete(node);
|
|
closedLayers.add(node);
|
|
}
|
|
}
|
|
$summary.on('click', (event) => {
|
|
event.preventDefault();
|
|
$details.prop('open', !$details.prop('open'));
|
|
syncDisclosure();
|
|
});
|
|
$details.on('toggle', () => { if ($details.get(0).isConnected) syncDisclosure(); });
|
|
if ($details.prop('open')) showChildren();
|
|
}
|
|
|
|
function renderLayers() {
|
|
if (!doc) return;
|
|
$layers.empty();
|
|
$pending.empty();
|
|
const hero = isHeroVisible() && doc.querySelector('[data-studio-hero]');
|
|
const navigation = doc.querySelector('[data-studio-navigation]:not([hidden])');
|
|
if (hero) layerRow($layers, hero, '首屏', null, true);
|
|
if (navigation) layerRow($layers, navigation, '本页目录', null, true);
|
|
for (const entry of sections) {
|
|
layerRow($layers, entry.node, plainText(entry.fields.title.node) || '未命名区块', entry, true);
|
|
if (entry.version === null) {
|
|
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', Boolean(hero || navigation || sections.length));
|
|
$(doc).find('[data-studio-empty-layout]').prop('hidden', Boolean(hero || sections.length));
|
|
$pending.prop('hidden', !$pending.children().length);
|
|
}
|
|
|
|
function scheduleLayers() {
|
|
window.clearTimeout(layerTimer);
|
|
layerTimer = window.setTimeout(() => { if (!draggedLayer) renderLayers(); }, 200);
|
|
}
|
|
|
|
$layers.on('click', '[data-layer-operation]', function () {
|
|
const node = $(this).closest('.studio-layer-row').data('canvasNode');
|
|
if (!node?.isConnected) return;
|
|
const operation = this.dataset.layerOperation;
|
|
if (operation === 'source') openSource(node);
|
|
else if (operation === 'jump') {
|
|
const dynamic = !node.closest('[data-studio-part]') && node.closest('[data-studio-dynamic]');
|
|
locateLayer(dynamic || node, dynamic ? null : node.closest('[data-studio-part="body"]') || node.querySelector('[data-studio-part="body"]'));
|
|
} else if (operation === 'delete') {
|
|
selectElement(node);
|
|
changeElement(false);
|
|
renderLayers();
|
|
} else {
|
|
const offset = operation === 'up' ? -1 : 1;
|
|
const moved = moveLayer(node, adjacentLayer(node, offset), offset < 0 ? 'before' : 'after');
|
|
if (moved) {
|
|
$layers.find('.studio-layer-row').filter((_, row) => $(row).data('canvasNode') === moved)
|
|
.find('[data-layer-operation="' + operation + '"]:enabled, [data-layer-operation="jump"]').last().trigger('focus');
|
|
}
|
|
}
|
|
}).on('dragstart', '.studio-layer-row[draggable=true]', function (event) {
|
|
draggedLayer = $(this).data('canvasNode');
|
|
event.originalEvent.dataTransfer.effectAllowed = 'move';
|
|
event.originalEvent.dataTransfer.setData('text/plain', 'LaySite layer');
|
|
}).on('dragover', '.studio-layer-row', function (event) {
|
|
if (!draggedLayer) return;
|
|
if (dropHint !== this) dropHint?.removeAttribute('data-drop');
|
|
dropHint = this;
|
|
const target = $(this).data('canvasNode');
|
|
const box = this.getBoundingClientRect();
|
|
const position = (event.clientY - box.top) / box.height;
|
|
const edge = position < .5 ? 'before' : 'after';
|
|
const where = position > .28 && position < .72 && canDropLayer(draggedLayer, target, 'inside') ? 'inside' : edge;
|
|
if (!canDropLayer(draggedLayer, target, where)) {
|
|
this.removeAttribute('data-drop');
|
|
return;
|
|
}
|
|
event.preventDefault();
|
|
event.originalEvent.dataTransfer.dropEffect = 'move';
|
|
this.dataset.drop = where;
|
|
}).on('drop', '.studio-layer-row[data-drop]', function (event) {
|
|
if (!draggedLayer) return;
|
|
event.preventDefault();
|
|
const source = draggedLayer;
|
|
draggedLayer = null;
|
|
moveLayer(source, $(this).data('canvasNode'), this.dataset.drop);
|
|
this.removeAttribute('data-drop');
|
|
dropHint = null;
|
|
}).on('dragend', () => {
|
|
draggedLayer = null;
|
|
dropHint?.removeAttribute('data-drop');
|
|
dropHint = null;
|
|
});
|
|
|
|
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);
|
|
if (section.feed !== null) 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 (element.dataset.studioPlaceholder) element.toggleAttribute('data-studio-empty', !plainText(element));
|
|
}
|
|
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);
|
|
$studio.find('dialog').on('close.canvasHistory', () => {
|
|
if (document.activeElement === document.body) $studio.get(0).focus({preventScroll: true});
|
|
});
|
|
$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', '');
|
|
colorSheet = doc.querySelector('[data-canvas-colors]')?.sheet;
|
|
canvasColors.clear();
|
|
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((records) => {
|
|
captureHistory(mediaDrag || null);
|
|
if (records.some((record) => record.type === 'childList'
|
|
&& [...record.addedNodes, ...record.removedNodes].some((node) => node.nodeType === 1))) scheduleLayers();
|
|
});
|
|
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 && !this.closest('[data-studio-part="body"]')) {
|
|
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;
|
|
if (node.nodeType !== 1) return;
|
|
const dynamic = node.closest('[data-studio-dynamic]');
|
|
if (dynamic && !node.closest('[data-studio-part]')) {
|
|
selectBody(null);
|
|
selectElement(dynamic);
|
|
return;
|
|
}
|
|
const field = node.closest(canvasFields);
|
|
const body = node.closest('[data-studio-part="body"]');
|
|
const leaf = field || editableBodyElement(node);
|
|
const wrapper = node.closest('[data-studio-section], [data-studio-hero], [data-studio-navigation]');
|
|
selectBody(body);
|
|
selectElement(doc.getSelection()?.isCollapsed ? leaf || (body === node ? wrapper || body : body || wrapper) : null);
|
|
});
|
|
$doc.on('dblclick.canvas', '[data-studio-part="body"] a', function (event) {
|
|
event.preventDefault();
|
|
if (!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));
|
|
});
|
|
});
|
|
});
|