forked from laysense/laysite
1432 lines
71 KiB
JavaScript
1432 lines
71 KiB
JavaScript
'use strict';
|
|
|
|
jQuery(function ($) {
|
|
const $picker = $('#media-picker');
|
|
const $pickerItems = $picker.find('[data-picker-items]');
|
|
const $pickerStatus = $picker.find('[data-picker-status]');
|
|
let pick = null;
|
|
let files = [];
|
|
let mediaType = '';
|
|
let pickerRequest;
|
|
|
|
function safeLink(value, media = false) {
|
|
return value !== '' && !/[\u0000-\u0020\u007f\\]/.test(value)
|
|
&& (/^\/(?!\/)/.test(value) || (media ? /^https:\/\//i : /^(https?:\/\/|mailto:|tel:|#\S)/i).test(value));
|
|
}
|
|
|
|
function mediaMarkup(file) {
|
|
let $node;
|
|
if (file.mime.startsWith('image/')) {
|
|
const alt = window.prompt('图片替代文本(装饰图可留空)', file.label);
|
|
if (alt === null) return '';
|
|
$node = $('<img>', {src: file.url, alt, loading: 'lazy'});
|
|
} else if (file.mime.startsWith('video/') || file.mime.startsWith('audio/')) {
|
|
const tag = file.mime.startsWith('video/') ? '<video>' : '<audio>';
|
|
$node = $(tag, {src: file.url, controls: true, preload: 'metadata'});
|
|
} else {
|
|
$node = $('<a>', {href: file.url}).text(file.label);
|
|
}
|
|
return $node.prop('outerHTML');
|
|
}
|
|
|
|
function renderPicker() {
|
|
const query = String($picker.find('[data-media-query]').val() || '').trim().toLowerCase();
|
|
const results = files.filter((file) => file.mime.startsWith(mediaType)
|
|
&& (file.label + ' ' + file.url).toLowerCase().includes(query));
|
|
$pickerStatus.text(results.length ? results.length + ' 个资源' : '没有匹配资源。');
|
|
$pickerItems.empty();
|
|
for (const file of results) {
|
|
const $item = $('<button>', {type: 'button', class: 'picker-item'}).data('file', file);
|
|
if (file.mime.startsWith('image/')) {
|
|
$item.append($('<img>', {src: file.url, alt: '', loading: 'lazy'}));
|
|
}
|
|
$item.append($('<span>').text(file.label));
|
|
$pickerItems.append($item);
|
|
}
|
|
}
|
|
|
|
function openPicker(type, callback) {
|
|
if (!$picker.length || typeof $picker.get(0).showModal !== 'function') return;
|
|
pick = callback;
|
|
mediaType = type;
|
|
$picker.find('[data-media-query]').val('');
|
|
$pickerItems.empty();
|
|
$pickerStatus.text('加载资源…');
|
|
$picker.get(0).showModal();
|
|
pickerRequest?.abort();
|
|
pickerRequest = $.getJSON('/admin/media/options').done(function (response) {
|
|
files = response.files;
|
|
renderPicker();
|
|
}).fail(function (_request, status) {
|
|
if (status !== 'abort') $pickerStatus.text('媒体库暂时无法打开。');
|
|
});
|
|
}
|
|
|
|
$picker.on('studio:pick', (_event, type, callback) => openPicker(type, callback));
|
|
$picker.on('input', '[data-media-query]', renderPicker);
|
|
$picker.on('click', '[data-close-picker]', () => $picker.get(0).close());
|
|
$picker.on('click', '.picker-item', function () {
|
|
const file = $(this).data('file');
|
|
$picker.get(0).close();
|
|
pick?.(file);
|
|
});
|
|
|
|
$('[data-asset-pick]').on('click', function () {
|
|
const $button = $(this);
|
|
const name = $button.data('asset-pick');
|
|
const $input = $button.closest('form').find('input').filter((_, field) => field.name === name);
|
|
openPicker($button.data('asset-type') || '', (file) => $input.val(file.url).trigger('input').trigger('focus'));
|
|
});
|
|
|
|
$('[data-copy-asset]').on('click', function () {
|
|
const $button = $(this);
|
|
const url = $button.data('copy-asset');
|
|
if (!navigator.clipboard) {
|
|
window.prompt('复制资源路径', url);
|
|
return;
|
|
}
|
|
navigator.clipboard.writeText(url).then(() => $button.text('已复制')).catch(() => window.prompt('复制资源路径', url));
|
|
});
|
|
|
|
$('[data-media-library]').each(function () {
|
|
const $library = $(this);
|
|
const $cards = $library.find('[data-library-card]');
|
|
function filter() {
|
|
const query = String($library.find('[data-library-query]').val()).trim().toLowerCase();
|
|
const category = $library.find('[data-library-type]').val();
|
|
let count = 0;
|
|
$cards.each(function () {
|
|
const $card = $(this);
|
|
const mime = $card.data('mime');
|
|
const matchesType = category === 'other' ? !/^(image|audio|video)\//.test(mime) : mime.startsWith(category);
|
|
const visible = matchesType && $card.data('search').toLowerCase().includes(query);
|
|
$card.prop('hidden', !visible);
|
|
if (visible) count++;
|
|
});
|
|
$library.find('[data-library-count]').text(count + ' 个资源');
|
|
}
|
|
$library.on('input change', '[data-library-query], [data-library-type]', filter);
|
|
filter();
|
|
});
|
|
|
|
function bodyEdits(original, edited) {
|
|
// Work in Unicode code points, then encode offsets in UTF-8 for PHP.
|
|
const before = Array.from(original);
|
|
const after = Array.from(edited);
|
|
const encoder = new TextEncoder();
|
|
const anchorSize = 32;
|
|
let start = 0;
|
|
let beforeEnd = before.length;
|
|
let afterEnd = after.length;
|
|
while (start < beforeEnd && start < afterEnd && before[start] === after[start]) start++;
|
|
while (beforeEnd > start && afterEnd > start && before[beforeEnd - 1] === after[afterEnd - 1]) {
|
|
beforeEnd--;
|
|
afterEnd--;
|
|
}
|
|
if (beforeEnd === start && afterEnd === start) return [];
|
|
|
|
const anchors = new Map();
|
|
for (let index = start; index + anchorSize <= beforeEnd; index += anchorSize) {
|
|
const key = before.slice(index, index + anchorSize).join('');
|
|
if (!anchors.has(key)) anchors.set(key, []);
|
|
anchors.get(key).push(index);
|
|
}
|
|
|
|
const edits = [];
|
|
let oldIndex = start;
|
|
let newIndex = start;
|
|
let byteOffset = encoder.encode(before.slice(0, start).join('')).length;
|
|
function copy() {
|
|
const first = oldIndex;
|
|
while (oldIndex < beforeEnd && newIndex < afterEnd && before[oldIndex] === after[newIndex]) {
|
|
oldIndex++;
|
|
newIndex++;
|
|
}
|
|
byteOffset += encoder.encode(before.slice(first, oldIndex).join('')).length;
|
|
}
|
|
|
|
function replace(oldEnd, newEnd) {
|
|
if (oldEnd === oldIndex && newEnd === newIndex) return;
|
|
const removed = encoder.encode(before.slice(oldIndex, oldEnd).join('')).length;
|
|
edits.push([byteOffset, removed, after.slice(newIndex, newEnd).join('')]);
|
|
byteOffset += removed;
|
|
oldIndex = oldEnd;
|
|
newIndex = newEnd;
|
|
}
|
|
|
|
for (let scan = start; scan + anchorSize <= afterEnd && edits.length < 511; scan++) {
|
|
const matches = anchors.get(after.slice(scan, scan + anchorSize).join(''));
|
|
if (!matches) continue;
|
|
let low = 0;
|
|
let high = matches.length;
|
|
while (low < high) {
|
|
const middle = Math.floor((low + high) / 2);
|
|
if (matches[middle] < oldIndex) low = middle + 1;
|
|
else high = middle;
|
|
}
|
|
if (low === matches.length) continue;
|
|
let nextOld = matches[low];
|
|
let nextNew = scan;
|
|
while (nextOld > oldIndex && nextNew > newIndex && before[nextOld - 1] === after[nextNew - 1]) {
|
|
nextOld--;
|
|
nextNew--;
|
|
}
|
|
replace(nextOld, nextNew);
|
|
copy();
|
|
scan = newIndex - 1;
|
|
}
|
|
replace(beforeEnd, afterEnd);
|
|
|
|
return edits;
|
|
}
|
|
|
|
$('[data-canvas-presets]').each(function () {
|
|
const $gallery = $(this);
|
|
const $tabs = $gallery.find('[data-library-tab]');
|
|
const $panels = $gallery.find('[data-library-panel]');
|
|
const $peek = $gallery.find('[data-template-peek]');
|
|
const $dialog = $gallery.find('[data-template-dialog]');
|
|
const $use = $dialog.find('[data-template-use]');
|
|
let $selection;
|
|
|
|
function hidePeek() {
|
|
$peek.prop('hidden', true);
|
|
}
|
|
|
|
function selectTab(kind, focus = false) {
|
|
const $current = $tabs.filter((_, tab) => tab.dataset.libraryTab === kind);
|
|
$tabs.attr({'aria-selected': 'false', tabindex: '-1'});
|
|
$current.attr({'aria-selected': 'true', tabindex: '0'});
|
|
$panels.each(function () {
|
|
$(this).prop('hidden', this.dataset.libraryPanel !== kind);
|
|
});
|
|
$gallery.closest('.studio-library').scrollTop(0);
|
|
hidePeek();
|
|
if (focus) $current.trigger('focus');
|
|
}
|
|
|
|
function filterItems($panel) {
|
|
const query = $panel.find('[data-template-search]').val().trim().toLowerCase();
|
|
let matches = 0;
|
|
$panel.find('[data-template-group]').filter((_, group) => !group.hidden).find('[data-library-item]').each(function () {
|
|
const visible = this.dataset.templateSearchText.toLowerCase().includes(query);
|
|
$(this).prop('hidden', !visible);
|
|
if (visible) matches++;
|
|
});
|
|
$panel.find('[data-template-empty]').prop('hidden', matches !== 0);
|
|
hidePeek();
|
|
}
|
|
|
|
$gallery.find('[data-library-tabs]').prop('hidden', false);
|
|
function openLayersFromHash() {
|
|
if (window.location.hash !== '#blocks') return false;
|
|
selectTab('layers');
|
|
$gallery.find('#blocks').prop('open', true);
|
|
return true;
|
|
}
|
|
if (!openLayersFromHash()) selectTab('modules');
|
|
$(window).on('hashchange', openLayersFromHash);
|
|
$tabs.on('click', function () {
|
|
selectTab(this.dataset.libraryTab);
|
|
}).on('keydown', function (event) {
|
|
const index = $tabs.index(this);
|
|
const last = $tabs.length - 1;
|
|
const next = {Home: 0, End: last, ArrowLeft: index === 0 ? last : index - 1, ArrowRight: index === last ? 0 : index + 1}[event.key];
|
|
if (typeof next !== 'number') return;
|
|
event.preventDefault();
|
|
selectTab($tabs.get(next).dataset.libraryTab, true);
|
|
});
|
|
|
|
$gallery.on('click', '[data-library-category]', function () {
|
|
const $panel = $(this).closest('[data-library-panel]');
|
|
$panel.data('categoryTrigger', this);
|
|
$panel.find('[data-library-index], .studio-anchor-create').prop('hidden', true);
|
|
$panel.find('[data-library-content]').prop('hidden', false);
|
|
$panel.find('[data-library-title]').text(this.dataset.libraryLabel);
|
|
$panel.find('[data-template-search]').val('');
|
|
const key = this.dataset.libraryCategory;
|
|
$panel.find('[data-template-group]').each(function () {
|
|
$(this).prop('hidden', this.dataset.templateGroup !== key);
|
|
});
|
|
filterItems($panel);
|
|
$panel.find('[data-library-back]').trigger('focus');
|
|
}).on('click', '[data-library-back]', function () {
|
|
const $panel = $(this).closest('[data-library-panel]');
|
|
$panel.find('[data-library-content]').prop('hidden', true);
|
|
$panel.find('[data-library-index], .studio-anchor-create').prop('hidden', false);
|
|
hidePeek();
|
|
$($panel.data('categoryTrigger')).trigger('focus');
|
|
}).on('input', '[data-template-search]', function () {
|
|
filterItems($(this).closest('[data-library-panel]'));
|
|
});
|
|
|
|
$gallery.on('mouseenter focusin', '[data-template-preview]', function (event) {
|
|
if (event.type === 'mouseenter' && !matchMedia('(hover: hover)').matches) return;
|
|
const bounds = this.getBoundingClientRect();
|
|
const width = Math.min(430, window.innerWidth - bounds.right - 24);
|
|
if (width < 240) return;
|
|
const top = Math.max(12, Math.min(bounds.top, window.innerHeight - width * 0.625 - 56));
|
|
$peek.find('img').attr('src', $(this).find('img').attr('src'));
|
|
$peek.find('p').text(this.dataset.templateTitle);
|
|
$peek.css({width, top, left: bounds.right + 12}).prop('hidden', false);
|
|
});
|
|
$gallery.on('mouseleave focusout', '[data-template-preview]', hidePeek);
|
|
$gallery.closest('.studio-library').on('scroll', hidePeek);
|
|
$(window).on('scroll resize', hidePeek);
|
|
|
|
$gallery.on('click', '[data-template-preview]', function () {
|
|
hidePeek();
|
|
const $card = $(this).closest('[data-template-card]');
|
|
$selection = $card.find('[data-canvas-template]');
|
|
$dialog.find('h2').text(this.dataset.templateTitle);
|
|
$dialog.find('img').attr('src', $(this).find('img').attr('src'));
|
|
$use.prop('disabled', $selection.prop('disabled'));
|
|
$dialog.get(0).showModal();
|
|
});
|
|
$dialog.on('click', '[data-template-close]', () => $dialog.get(0).close());
|
|
$use.on('click', () => {
|
|
if (!$selection || $selection.prop('disabled')) return;
|
|
$dialog.get(0).close();
|
|
hidePeek();
|
|
$selection.trigger('click');
|
|
});
|
|
$gallery.on('studio:canvas-ready', () => {
|
|
if ($selection) $use.prop('disabled', $selection.prop('disabled'));
|
|
});
|
|
});
|
|
|
|
$('[data-preview-studio]').each(function () {
|
|
const $studio = $(this);
|
|
const $frame = $studio.find('iframe');
|
|
const $window = $studio.find('.studio-frame-window');
|
|
const $layout = $studio.closest('.studio-layout');
|
|
const $settings = $layout.find('.studio-inspector');
|
|
const $sizing = $studio.find('[data-media-sizing]');
|
|
const $elementTools = $studio.find('[data-element-tools]');
|
|
const $alignTools = $elementTools.find('[data-element-align]');
|
|
const alignments = ['left', 'center', 'right'];
|
|
const buttonClasses = {solid: 'button-primary', outline: 'button-outline', underline: 'button-underline', plain: 'button-plain'};
|
|
const alignmentClasses = alignments.map((value) => 'studio-align-' + value);
|
|
const canvasFields = '[data-studio-field="heading"], [data-studio-field="accent"], [data-studio-field="lead"], [data-studio-part="title"], [data-studio-part="lead"], [data-studio-action], [data-studio-nav-index]';
|
|
const bodyElements = 'a, article, blockquote, details, div, dl, dt, dd, figure, h1, h2, h3, h4, h5, h6, hr, li, ol, p, pre, progress, table, ul';
|
|
const mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video';
|
|
const $handle = $studio.find('[data-media-handle]');
|
|
const $mediaSize = $sizing.find('[data-media-size]');
|
|
const mediaWidthClass = /^studio-media-\d+$/;
|
|
|
|
function fitPreview() {
|
|
const width = $window.width();
|
|
const height = $window.height();
|
|
if (!width || !height) return;
|
|
const viewport = $studio.hasClass('studio-phone') ? 390 : Math.max(1280, width);
|
|
const scale = Math.min(1, width / viewport);
|
|
$window.addClass('has-scaled-preview');
|
|
$frame.css({
|
|
width: viewport,
|
|
height: height / scale,
|
|
left: (width - viewport * scale) / 2,
|
|
transform: 'scale(' + scale + ')'
|
|
});
|
|
positionSelection();
|
|
}
|
|
const $presets = $layout.find('[data-canvas-presets]');
|
|
const $templateStatus = $presets.find('[data-template-status]');
|
|
const $pending = $presets.find('[data-template-pending]');
|
|
const heroControls = new Map();
|
|
let selectedElement;
|
|
let selectedMedia;
|
|
let mediaDrag;
|
|
const selectionObserver = 'ResizeObserver' in window ? new ResizeObserver(positionSelection) : null;
|
|
if ('ResizeObserver' in window) {
|
|
new ResizeObserver(fitPreview).observe($window.get(0));
|
|
} else {
|
|
$(window).on('resize', fitPreview);
|
|
}
|
|
fitPreview();
|
|
$studio.on('click', '[data-preview-size]', function () {
|
|
const $button = $(this);
|
|
$studio.toggleClass('studio-phone', $button.data('preview-size') === 'phone');
|
|
$studio.find('[data-preview-size]').attr('aria-pressed', 'false');
|
|
$button.attr('aria-pressed', 'true');
|
|
fitPreview();
|
|
});
|
|
const $toolbar = $studio.find('[data-canvas-toolbar]');
|
|
const $commands = $toolbar.find('[data-canvas-command]');
|
|
const $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}) => name !== 'csrf' && name !== 'canvas_sections');
|
|
const savedSettings = JSON.stringify(settingsSnapshot());
|
|
let dialogAction;
|
|
let doc;
|
|
let activeBody;
|
|
let savedRange;
|
|
let sections = [];
|
|
let saveComplete = false;
|
|
|
|
function sectionChanges(withEdits = true) {
|
|
const edits = sections.flatMap(({key, version, fields, source, template, copyOf, feed, initialFeed}) => {
|
|
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;
|
|
}
|
|
let value = field === 'body' ? node.innerHTML : node.textContent;
|
|
if (field === 'body' && node.contains(selectedElement)) {
|
|
const copy = node.cloneNode(true);
|
|
$(copy).find('[data-studio-selected]').removeAttr('data-studio-selected');
|
|
value = copy.innerHTML;
|
|
}
|
|
if (version === null || value !== initial) {
|
|
changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value;
|
|
}
|
|
}
|
|
const feedChanged = feed && (version === null || JSON.stringify(feed) !== initialFeed);
|
|
if (!Object.keys(changes).length && !alignmentChanged && !feedChanged) 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;
|
|
return [edit];
|
|
});
|
|
return [...edits, ...deletedSections];
|
|
}
|
|
|
|
$settings.on('studio:sync', () => pageInput('canvas_sections').val(JSON.stringify(sectionChanges())));
|
|
$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 || 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 && activeBody?.contains(selection.anchorNode) && activeBody.contains(selection.focusNode)) {
|
|
savedRange = selection.getRangeAt(0).cloneRange();
|
|
}
|
|
}
|
|
|
|
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();
|
|
}
|
|
|
|
$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'], bold: ['bold'], list: ['insertUnorderedList']};
|
|
edit(...commands[command]);
|
|
}
|
|
});
|
|
|
|
function configureText(node, label, placeholder = false) {
|
|
node.contentEditable = 'plaintext-only';
|
|
node.setAttribute('aria-label', label);
|
|
if (placeholder) node.dataset.studioPlaceholder = label;
|
|
}
|
|
|
|
function bindPage($doc) {
|
|
const visibilityTargets = {header: '.masthead', hero: '[data-studio-hero-content], .page-photo-credit', footer: '.site-footer'};
|
|
for (const [area, selector] of Object.entries(visibilityTargets)) {
|
|
const $input = pageInput('show_' + area);
|
|
const $target = $doc.find(selector);
|
|
$input.on('change.canvas', () => {
|
|
selectElement(null);
|
|
$target.prop('hidden', $input.val() === '0');
|
|
});
|
|
}
|
|
const labels = {name: '页面名称', heading: '首屏标题', accent: '标题第二行', lead: '首屏简介'};
|
|
$doc.find('[data-studio-field]').each(function () {
|
|
const field = this.dataset.studioField;
|
|
const $target = $(this);
|
|
const $input = pageInput(field);
|
|
configureText(this, labels[field], ['accent', 'lead'].includes(field));
|
|
$target.text($input.val()).on('input', () => $input.val($target.text()));
|
|
$input.on('input.canvas', () => $target.text($input.val()));
|
|
});
|
|
|
|
const $image = $doc.find('[data-studio-hero-image]');
|
|
const $visual = $image.parent();
|
|
function syncImage() {
|
|
const path = pageInput('image').val().trim();
|
|
const valid = safeLink(path, true);
|
|
setMediaWidth($visual.get(0), pageInput('image_scale').val());
|
|
$visual.prop('hidden', !valid).parent().toggleClass('hero-text-only', !valid);
|
|
if (valid) $image.attr('src', path);
|
|
else $image.removeAttr('src');
|
|
$image.attr('alt', pageInput('alt').val());
|
|
}
|
|
$settings.find('[name="image"], [name="alt"]').on('input.canvas', syncImage);
|
|
heroControls.set('remove-image', () => {
|
|
pageInput('alt').val('');
|
|
pageInput('image_scale').val(0);
|
|
pageInput('image').val('').trigger('input');
|
|
});
|
|
syncImage();
|
|
$image.attr({tabindex: '0', role: 'button', 'aria-label': '编辑首屏图片'});
|
|
heroControls.set('image', () => {
|
|
openProperties('首屏图片', {url: pageInput('image').val(), alt: pageInput('alt').val()}, ({url, alt}) => {
|
|
pageInput('image').val(url);
|
|
pageInput('alt').val(alt);
|
|
syncImage();
|
|
}, 'image/', true);
|
|
});
|
|
|
|
const $heroActions = $doc.find('.hero-actions');
|
|
const $actionsInput = pageInput('hero_actions');
|
|
let actions = JSON.parse($actionsInput.val()).map(([url, label, style, blank], index) => [
|
|
url, label, style || (index ? 'outline' : 'solid'), Boolean(blank),
|
|
]);
|
|
|
|
function syncActions() {
|
|
$actionsInput.val(JSON.stringify(actions));
|
|
$heroActions.empty();
|
|
for (const [index, [url, label, style, blank]] of actions.entries()) {
|
|
$('<a>', {href: url, class: 'button ' + buttonClasses[style], 'data-studio-action': index, text: label})
|
|
.attr(blank ? {target: '_blank', rel: 'noopener noreferrer'} : {}).appendTo($heroActions);
|
|
}
|
|
}
|
|
function editAction(index) {
|
|
const [url, label, style, blank] = actions[index] || ['', '', 'solid', false];
|
|
openProperties('首屏按钮', {label, url, buttonStyle: style, newTab: blank ? '1' : '0'}, (next) => {
|
|
if (!next.label || next.label.length > 70) {
|
|
$propertyError.prop('hidden', false).text('请填写不超过 70 个字符的按钮文案。');
|
|
return false;
|
|
}
|
|
selectElement(null);
|
|
actions[index] = [next.url, next.label, next.buttonStyle, next.newTab === '1'];
|
|
syncActions();
|
|
selectElement($heroActions.children().get(index));
|
|
});
|
|
}
|
|
$heroActions.on('dblclick studio:properties', '[data-studio-action]', function (event) {
|
|
event.preventDefault();
|
|
editAction(Number(this.dataset.studioAction));
|
|
});
|
|
heroControls.set('add-action', () => { if (actions.length < 8) editAction(actions.length); });
|
|
heroControls.set('edit-action', editAction);
|
|
heroControls.set('change-action', (index, copy) => {
|
|
if (copy && actions.length >= 8) return null;
|
|
actions.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [[...actions[index]]] : []));
|
|
syncActions();
|
|
return $heroActions.children().get(index + 1);
|
|
});
|
|
pageInput('palette_id').on('change.canvas', function () {
|
|
$doc.find('[data-page-palette]').remove();
|
|
if (this.value) $('<link>', {rel: 'stylesheet', href: '/palette/' + this.value + '.css', 'data-page-palette': ''}).appendTo($doc.find('head'));
|
|
});
|
|
syncActions();
|
|
|
|
const $navigation = $doc.find('[data-studio-navigation]');
|
|
const $navContent = $navigation.find('.section-nav-inner');
|
|
const $navInput = pageInput('quicklinks');
|
|
const navLines = () => $navInput.val().split(/\r\n|[\n\r\v\f\u0085\u2028\u2029]/);
|
|
function syncNavigation() {
|
|
const lines = navLines();
|
|
$navContent.empty();
|
|
for (const [index, line] of lines.entries()) {
|
|
if (!line.trim()) continue;
|
|
const separator = line.indexOf('|');
|
|
const label = (separator < 0 ? line : line.slice(0, separator)).trim();
|
|
const url = separator < 0 ? '' : line.slice(separator + 1).trim();
|
|
const link = doc.createElement('a');
|
|
link.href = safeLink(url) ? url : '#';
|
|
link.textContent = label || url;
|
|
link.dataset.studioNavIndex = index;
|
|
$(link).on('dblclick studio:properties', (event) => {
|
|
event.preventDefault();
|
|
openProperties('本页目录链接', {label, url}, (next) => {
|
|
if (!next.label || /[|\r\n]/.test(next.label)) {
|
|
$propertyError.prop('hidden', false).text('请填写目录文案,文案不能包含竖线。');
|
|
return false;
|
|
}
|
|
const updated = navLines();
|
|
updated[index] = next.label + ' | ' + next.url;
|
|
$navInput.val(updated.join('\n'));
|
|
syncNavigation();
|
|
});
|
|
});
|
|
$navContent.append(link);
|
|
}
|
|
$navigation.prop('hidden', !$navContent.children().length);
|
|
}
|
|
heroControls.set('change-nav', (index, copy) => {
|
|
const lines = navLines();
|
|
if (copy && $navContent.children().length >= 20) return null;
|
|
lines.splice(index + (copy ? 1 : 0), copy ? 0 : 1, ...(copy ? [lines[index]] : []));
|
|
$navInput.val(lines.join('\n'));
|
|
syncNavigation();
|
|
return $navContent.find('[data-studio-nav-index="' + (index + 1) + '"]').get(0);
|
|
});
|
|
$navInput.on('input.canvas', syncNavigation);
|
|
heroControls.set('remove-section-links', (key) => {
|
|
const anchor = '#' + key;
|
|
$navInput.val(navLines().filter((line) => {
|
|
const separator = line.indexOf('|');
|
|
return separator < 0 || line.slice(separator + 1).trim() !== anchor;
|
|
}).join('\n'));
|
|
syncNavigation();
|
|
actions = actions.filter(([url]) => url !== anchor);
|
|
syncActions();
|
|
});
|
|
heroControls.set('navigation', () => {
|
|
openProperties('本页目录', {quicklinks: $navInput.val()}, ({quicklinks}) => {
|
|
$navInput.val(quicklinks);
|
|
syncNavigation();
|
|
});
|
|
});
|
|
syncNavigation();
|
|
}
|
|
|
|
function editResource(node) {
|
|
const tag = node.localName;
|
|
if (tag === 'progress') {
|
|
openProperties('进度条', {value: node.getAttribute('value') || '0', max: node.getAttribute('max') || '100'}, ({value, max}) => {
|
|
if (!/^\d+$/.test(value) || !/^\d+$/.test(max) || Number(max) < 1 || Number(value) > Number(max)) {
|
|
$propertyError.prop('hidden', false).text('请输入不超过最大值的非负整数。');
|
|
return false;
|
|
}
|
|
node.max = Number(max);
|
|
node.value = Number(value);
|
|
node.textContent = Math.round(100 * node.value / node.max) + '%';
|
|
});
|
|
return;
|
|
}
|
|
if (tag === 'a') {
|
|
const product = node.parentElement.matches('.hero-directory');
|
|
const title = product ? node.querySelector(':scope > span') : null;
|
|
const note = product ? node.querySelector(':scope > small') : null;
|
|
const onlyChild = node.firstElementChild;
|
|
const text = title || (node.childElementCount === 0 ? node : (
|
|
node.childElementCount === 1 && onlyChild.matches('span, strong, b, em, i, small')
|
|
&& !onlyChild.childElementCount && node.textContent.trim() === onlyChild.textContent.trim() ? onlyChild : null
|
|
));
|
|
const values = text ? {label: text.textContent, url: node.getAttribute('href') || ''} : {url: node.getAttribute('href') || ''};
|
|
if (title) values.note = note?.textContent || '';
|
|
values.newTab = node.target === '_blank' ? '1' : '0';
|
|
if (node.classList.contains('button')) {
|
|
values.buttonStyle = Object.keys(buttonClasses).find((style) => node.classList.contains(buttonClasses[style])) || 'plain';
|
|
}
|
|
openProperties(product ? '导航卡片' : '正文链接', values, ({label, note: description, url, newTab, buttonStyle}) => {
|
|
if (text && !label) {
|
|
$propertyError.prop('hidden', false).text('请填写链接文案。');
|
|
return false;
|
|
}
|
|
node.setAttribute('href', url);
|
|
if (newTab === '1') {
|
|
$(node).attr({target: '_blank', rel: 'noopener noreferrer'});
|
|
} else {
|
|
$(node).removeAttr('target rel');
|
|
}
|
|
if (buttonStyle) $(node).removeClass(Object.values(buttonClasses)).addClass(buttonClasses[buttonStyle]);
|
|
if (text && label !== values.label) text.textContent = label;
|
|
if (description !== undefined) {
|
|
if (note) $(note).text(description);
|
|
else if (description) $('<small>').text(description).appendTo(node);
|
|
}
|
|
});
|
|
return;
|
|
}
|
|
|
|
const source = tag === 'img' ? node : (node.hasAttribute('src') ? node : node.querySelector('source') || node);
|
|
const values = {url: source.getAttribute('src') || ''};
|
|
if (tag === 'img') values.alt = node.getAttribute('alt') || '';
|
|
if (tag === 'video') values.poster = node.getAttribute('poster') || '';
|
|
openProperties({img: '正文图片', video: '视频', audio: '音频'}[tag], values, ({url, alt, poster}) => {
|
|
if (url !== values.url) {
|
|
source.setAttribute('src', url);
|
|
if (source !== node) source.removeAttribute('type');
|
|
if (tag !== 'img') node.load();
|
|
}
|
|
if (alt !== undefined && alt !== values.alt) node.setAttribute('alt', alt);
|
|
if (poster !== undefined && poster !== values.poster) {
|
|
if (poster) node.setAttribute('poster', poster);
|
|
else node.removeAttribute('poster');
|
|
}
|
|
}, (tag === 'img' ? 'image' : tag) + '/');
|
|
}
|
|
|
|
function registerSection(section, version = Number(section.dataset.studioSection), metadata = {}) {
|
|
const fields = {};
|
|
const feed = section.dataset.studioFeed ? JSON.parse(section.dataset.studioFeed) : null;
|
|
for (const node of section.querySelectorAll('[data-studio-part]')) {
|
|
const part = node.dataset.studioPart;
|
|
const body = part === 'body';
|
|
const label = {title: '区块标题', lead: '添加区块简介', body: '区块正文'}[part];
|
|
if (!feed && body) {
|
|
node.contentEditable = 'true';
|
|
node.setAttribute('aria-label', label);
|
|
node.dataset.studioPlaceholder = label;
|
|
} else if (!feed && !node.hidden) {
|
|
configureText(node, label, part === 'lead');
|
|
}
|
|
fields[part] = {node, initial: body ? node.innerHTML : node.textContent, initialAlignment: body ? '' : getAlignment(node)};
|
|
}
|
|
const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from(
|
|
atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0)
|
|
));
|
|
const entry = {node: section, key: section.id, version, fields, source, feed, initialFeed: JSON.stringify(feed), ...metadata};
|
|
sections.push(entry);
|
|
return entry;
|
|
}
|
|
|
|
function setMediaWidth(node, width) {
|
|
for (const token of Array.from(node.classList).filter((name) => mediaWidthClass.test(name))) {
|
|
node.classList.remove(token);
|
|
}
|
|
if (Number(width)) node.classList.add('studio-media-' + width);
|
|
else if (!node.classList.length) node.removeAttribute('class');
|
|
}
|
|
|
|
function sizingTarget() {
|
|
if (!selectedMedia?.isConnected) return null;
|
|
return selectedMedia.hasAttribute('data-studio-hero-image') ? selectedMedia.parentElement : selectedMedia;
|
|
}
|
|
|
|
function frameScale() {
|
|
const frame = $frame.get(0);
|
|
return frame.getBoundingClientRect().width / frame.offsetWidth;
|
|
}
|
|
|
|
function previewBounds(node) {
|
|
const frame = $frame.get(0).getBoundingClientRect();
|
|
const container = $window.get(0);
|
|
const origin = container.getBoundingClientRect();
|
|
const bounds = node.getBoundingClientRect();
|
|
const scale = frameScale();
|
|
const x = frame.left - origin.left - container.clientLeft;
|
|
const y = frame.top - origin.top - container.clientTop;
|
|
return {
|
|
left: x + bounds.left * scale, right: x + bounds.right * scale,
|
|
top: y + bounds.top * scale, bottom: y + bounds.bottom * scale,
|
|
width: bounds.width * scale, height: bounds.height * scale,
|
|
};
|
|
}
|
|
|
|
function positionSelection() {
|
|
const container = $window.get(0);
|
|
const node = sizingTarget();
|
|
if (node) {
|
|
const bounds = previewBounds(node);
|
|
const x = getAlignment(node) === 'right' ? bounds.left : bounds.right;
|
|
const y = (bounds.top + bounds.bottom) / 2;
|
|
const visible = bounds.width > 0 && y >= 0 && y <= container.clientHeight
|
|
&& x >= 0 && x <= container.clientWidth + 1;
|
|
$handle.prop('hidden', !mediaDrag && !visible);
|
|
$handle.css({left: Math.max(11, Math.min(x, container.clientWidth - 11)), top: y});
|
|
} else {
|
|
$handle.prop('hidden', true);
|
|
}
|
|
if (!selectedElement?.isConnected) {
|
|
$elementTools.prop('hidden', true);
|
|
return;
|
|
}
|
|
const bounds = previewBounds(selectedElement);
|
|
const visible = bounds.width > 0 && bounds.height > 0 && bounds.right > 0
|
|
&& bounds.left < container.clientWidth && bounds.bottom > 0 && bounds.top < container.clientHeight;
|
|
$elementTools.prop('hidden', !visible);
|
|
if (!visible) return;
|
|
const maxX = container.clientWidth - $elementTools.outerWidth() - 5;
|
|
const height = $elementTools.outerHeight();
|
|
const above = bounds.top - height - 5;
|
|
const below = bounds.bottom + 5;
|
|
const y = above >= 5 || below + height > container.clientHeight ? above : below;
|
|
$elementTools.css({
|
|
left: Math.max(5, Math.min(bounds.left, maxX)),
|
|
top: Math.max(5, Math.min(y, container.clientHeight - height - 5)),
|
|
});
|
|
}
|
|
|
|
function currentMediaWidth(node) {
|
|
return Number(Array.from(node.classList).find((name) => mediaWidthClass.test(name))?.slice('studio-media-'.length)) || 0;
|
|
}
|
|
|
|
function showMediaWidth(width) {
|
|
$mediaSize.text(width ? width + '%' : '原始尺寸');
|
|
$handle.attr({'aria-valuenow': width || 100, 'aria-valuetext': width ? width + '%' : '原始尺寸'});
|
|
}
|
|
|
|
function editableBodyElement(node) {
|
|
const body = node.closest('[data-studio-part="body"]');
|
|
if (!body) return null;
|
|
const element = node.closest(bodyElements);
|
|
return element !== body && body.contains(element) ? element : null;
|
|
}
|
|
|
|
function getAlignment(node) {
|
|
return alignments.find((value) => node.classList.contains('studio-align-' + value)) || '';
|
|
}
|
|
|
|
function alignmentTarget(node) {
|
|
if (!node) return null;
|
|
const hero = node.closest('[data-studio-align-field]');
|
|
if (hero) return hero;
|
|
return node.matches('[data-studio-part="title"], [data-studio-part="lead"]') || node.closest('[data-studio-part="body"]')
|
|
? node : null;
|
|
}
|
|
|
|
function syncAlignmentButtons(target) {
|
|
$alignTools.prop('hidden', !target).find('[data-align]').each(function () {
|
|
$(this).attr('aria-pressed', String(Boolean(target) && getAlignment(target) === this.dataset.align));
|
|
});
|
|
}
|
|
|
|
function selectElement(node) {
|
|
selectionObserver?.disconnect();
|
|
selectedElement?.removeAttribute('data-studio-selected');
|
|
selectedElement = node;
|
|
const dynamic = node?.hasAttribute('data-studio-dynamic');
|
|
$elementTools.toggleClass('is-module', Boolean(dynamic)).find('[data-element-module-settings]').prop('hidden', !dynamic);
|
|
selectedMedia = node?.matches(mediaTargets) ? node : null;
|
|
$sizing.prop('hidden', !selectedMedia);
|
|
if (node) {
|
|
node.setAttribute('data-studio-selected', '');
|
|
const target = sizingTarget();
|
|
const nav = node.hasAttribute('data-studio-nav-index');
|
|
const inBody = node.closest('[data-studio-part="body"]') !== null;
|
|
const action = node.hasAttribute('data-studio-action');
|
|
const canCopy = dynamic || inBody || (nav && $(node).siblings().length < 19) || (action && $(node).siblings().length < 7);
|
|
const hasProperties = !dynamic && (selectedMedia || node.matches('a, progress'));
|
|
const aligned = dynamic ? null : alignmentTarget(node);
|
|
syncAlignmentButtons(aligned);
|
|
$elementTools.find('[data-element-copy]').prop('hidden', !canCopy);
|
|
const deleteLabel = node.dataset.studioField === 'heading' ? '删除首屏'
|
|
: node.dataset.studioPart === 'title' ? '删除区块' : '删除';
|
|
$elementTools.find('[data-element-delete]').attr({'aria-label': deleteLabel, title: deleteLabel})
|
|
.prop('hidden', !dynamic && !inBody && !selectedMedia && !node.matches(canvasFields));
|
|
$elementTools.find('[data-element-properties]').prop('hidden', !hasProperties);
|
|
if (target) showMediaWidth(currentMediaWidth(target));
|
|
selectionObserver?.observe(target || aligned || node);
|
|
}
|
|
positionSelection();
|
|
}
|
|
|
|
function changeElement(copy) {
|
|
const node = selectedElement;
|
|
if (!node?.isConnected) return;
|
|
if (node.hasAttribute('data-studio-dynamic')) {
|
|
changeModule(sections.find((section) => section.node === node), copy);
|
|
return;
|
|
}
|
|
const {studioField, studioAction, studioNavIndex} = node.dataset;
|
|
if (!copy && studioField === 'heading') {
|
|
pageInput('show_hero').val('0').trigger('change');
|
|
$studio.find('[data-canvas-status]').text('首屏已移除,可在页面设置中恢复。');
|
|
return;
|
|
}
|
|
if (!copy && node.dataset.studioPart === 'title') {
|
|
changeModule(sections.find((section) => section.node === node.closest('[data-studio-section]')), false);
|
|
return;
|
|
}
|
|
const inBody = node.closest('[data-studio-part="body"]') !== null;
|
|
selectElement(null);
|
|
if (inBody) {
|
|
if (copy) {
|
|
const $clone = $(node.cloneNode(true));
|
|
$clone.find('[id]').addBack('[id]').removeAttr('id');
|
|
$(node).after($clone);
|
|
selectElement($clone.get(0));
|
|
} else {
|
|
$(node).remove();
|
|
savedRange = null;
|
|
}
|
|
} else if (studioAction !== undefined) {
|
|
const next = heroControls.get('change-action')(Number(studioAction), copy);
|
|
if (copy && next) selectElement(next);
|
|
} else if (studioNavIndex !== undefined) {
|
|
const next = heroControls.get('change-nav')(Number(studioNavIndex), copy);
|
|
if (copy && next) selectElement(next);
|
|
} else if (!copy) {
|
|
if (node.hasAttribute('data-studio-hero-image')) {
|
|
heroControls.get('remove-image')();
|
|
|
|
} else if (studioField) {
|
|
pageInput(studioField).val('').trigger('input');
|
|
} else {
|
|
$(node).text('');
|
|
}
|
|
}
|
|
}
|
|
|
|
$elementTools.on('click', '[data-align]', function () {
|
|
const target = alignmentTarget(selectedElement);
|
|
const alignment = this.dataset.align;
|
|
if (!target || !alignments.includes(alignment)) return;
|
|
target.classList.remove(...alignmentClasses);
|
|
target.classList.add('studio-align-' + alignment);
|
|
const field = target.dataset.studioAlignField;
|
|
if (field) {
|
|
const $value = pageInput('alignments');
|
|
const values = {...JSON.parse($value.val())};
|
|
values[field] = alignment;
|
|
$value.val(JSON.stringify(values));
|
|
}
|
|
syncAlignmentButtons(target);
|
|
positionSelection();
|
|
}).on('click', '[data-element-copy]', () => changeElement(true))
|
|
.on('click', '[data-element-delete]', () => changeElement(false))
|
|
.on('click', '[data-element-properties]', () => {
|
|
if (selectedMedia) replaceMedia();
|
|
else if (selectedElement?.hasAttribute('data-studio-action')) {
|
|
heroControls.get('edit-action')(Number(selectedElement.dataset.studioAction));
|
|
} else if (selectedElement?.matches('[data-studio-nav-index]')) {
|
|
$(selectedElement).triggerHandler('studio:properties');
|
|
} else if (selectedElement?.matches('a, progress')) {
|
|
editResource(selectedElement);
|
|
}
|
|
}).on('keydown', (event) => {
|
|
if (event.key === 'Escape') selectElement(null);
|
|
});
|
|
|
|
function noteModule(section, text) {
|
|
const $body = $(section).find('[data-studio-part="body"]');
|
|
let $note = $(section).find('[data-studio-module-note]');
|
|
if (!$note.length) $note = $('<p>', {class: 'studio-module-note', 'data-studio-module-note': ''}).insertBefore($body);
|
|
$note.text(text);
|
|
}
|
|
|
|
$elementTools.on('click', '[data-element-module-settings]', () => {
|
|
editedModule = sections.find(({node}) => node === selectedElement);
|
|
if (!editedModule?.feed) return;
|
|
const {fields, feed} = editedModule;
|
|
moduleInput('module_title').val(fields.title.node.textContent);
|
|
moduleInput('module_lead').val(fields.lead.node.textContent);
|
|
moduleInput('feed_mode').val(feed.mode);
|
|
moduleInput('feed_limit').val(feed.limit);
|
|
moduleInput('feed_categories[]').each(function () {
|
|
this.checked = feed.categories.includes(this.value);
|
|
});
|
|
$moduleDialog.find('[data-module-error]').prop('hidden', true);
|
|
$moduleDialog.get(0).showModal();
|
|
});
|
|
$moduleDialog.on('click', '[data-module-close]', () => $moduleDialog.get(0).close());
|
|
$moduleForm.on('submit', (event) => {
|
|
event.preventDefault();
|
|
const categories = moduleInput('feed_categories[]').filter(':checked').map((_, node) => node.value).get();
|
|
const title = moduleInput('module_title').val().trim();
|
|
if (!title || !categories.length) {
|
|
$moduleDialog.find('[data-module-error]').text('请填写标题并至少选择一个分类。').prop('hidden', false);
|
|
return;
|
|
}
|
|
const {node, fields} = editedModule;
|
|
editedModule.feed = {mode: moduleInput('feed_mode').val(), categories, limit: Number(moduleInput('feed_limit').val())};
|
|
fields.title.node.textContent = title;
|
|
fields.lead.node.textContent = moduleInput('module_lead').val().trim();
|
|
noteModule(node, '模块设置将在保存页面后更新。');
|
|
$moduleDialog.get(0).close();
|
|
positionSelection();
|
|
});
|
|
|
|
function newSectionId() {
|
|
return 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
}
|
|
|
|
function addPending(section) {
|
|
const $button = $('<button>', {type: 'button', text: '取消新增:' + section.fields.title.node.textContent});
|
|
section.$pending = $('<li>').append($button).appendTo($pending);
|
|
$pending.prop('hidden', false);
|
|
$button.on('click', () => removeSection(section));
|
|
}
|
|
|
|
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);
|
|
section.$pending?.remove();
|
|
$pending.prop('hidden', !$pending.children().length);
|
|
}
|
|
|
|
function scopeTemplateIds(root, prefix, oldKey = '') {
|
|
const ids = new Map();
|
|
$(root).find('[id]').addBack('[id]').each(function () {
|
|
const next = oldKey && this.id.includes(oldKey) ? this.id.replace(oldKey, prefix) : prefix + '-' + this.id;
|
|
ids.set(this.id, next);
|
|
this.id = next;
|
|
});
|
|
$(root).find('[aria-labelledby], [aria-controls], [href^="#"]').addBack('[aria-labelledby]').each(function () {
|
|
for (const attribute of ['aria-labelledby', 'aria-controls', 'href']) {
|
|
const value = this.getAttribute(attribute);
|
|
if (!value) continue;
|
|
if (attribute === 'href') {
|
|
const target = ids.get(value.slice(1));
|
|
if (value.startsWith('#') && target) this.setAttribute('href', '#' + target);
|
|
} else {
|
|
this.setAttribute(attribute, value.split(' ').map((part) => ids.get(part) || part).join(' '));
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
function changeModule(section, copy) {
|
|
if (!section) return;
|
|
if (!copy) {
|
|
if (window.confirm('删除此区块?保存页面后生效。')) {
|
|
removeSection(section);
|
|
$studio.find('[data-canvas-status]').text('区块已移除,保存页面后生效。');
|
|
}
|
|
return;
|
|
}
|
|
if (sections.filter(({version}) => version === null).length >= 50) return;
|
|
selectElement(null);
|
|
const clone = section.node.cloneNode(true);
|
|
const id = newSectionId();
|
|
scopeTemplateIds(clone, id, section.key);
|
|
clone.dataset.studioFeed = JSON.stringify(section.feed);
|
|
doc.querySelector('[data-studio-section-end]').before(clone);
|
|
const copyOf = section.copyOf || (section.version === null ? null : {key: section.key, version: section.version});
|
|
const entry = registerSection(clone, null, {template: copyOf ? null : section.template, copyOf});
|
|
addPending(entry);
|
|
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) {
|
|
$templateStatus.text('动态模块需要作为独立区块添加。');
|
|
return;
|
|
}
|
|
if (!activeBody) {
|
|
$templateStatus.text('先在画布中选择要插入的区块正文。');
|
|
return;
|
|
}
|
|
insertInBody(markup, activeBody, savedRange);
|
|
selectElement(null);
|
|
$templateStatus.text('已插入当前正文。');
|
|
return;
|
|
}
|
|
if (sections.filter(({version}) => version === null).length >= 50) {
|
|
$templateStatus.text('请先保存,再添加更多区块。');
|
|
return;
|
|
}
|
|
const end = doc.querySelector('[data-studio-section-end]');
|
|
const section = end.content.firstElementChild.cloneNode(true);
|
|
const id = 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});
|
|
addPending(entry);
|
|
section.scrollIntoView({block: 'start'});
|
|
if (feed) selectElement(section);
|
|
else entry.fields.body.node.focus({preventScroll: true});
|
|
$templateStatus.text('已添加 ' + title.textContent + ' 区块。');
|
|
});
|
|
|
|
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', '');
|
|
const $doc = $(doc);
|
|
$settings.find(':input').off('.canvas');
|
|
bindPage($doc);
|
|
selectBody(null);
|
|
selectElement(null);
|
|
$pending.empty().prop('hidden', true);
|
|
sections = [];
|
|
deletedSections = [];
|
|
$doc.find('[data-studio-section]').each((_, section) => registerSection(section));
|
|
|
|
$doc.on('focusin.canvas', '[contenteditable]', function () {
|
|
selectBody(this.dataset.studioPart === 'body' ? this : null);
|
|
});
|
|
$doc.on('selectionchange.canvas', rememberSelection).on('scroll.canvas', positionSelection);
|
|
$doc.on('click.canvas auxclick.canvas', 'a', (event) => event.preventDefault());
|
|
$doc.on('click.canvas dblclick.canvas', mediaTargets, function (event) {
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
const dynamic = this.closest('[data-studio-dynamic]');
|
|
if (dynamic) {
|
|
selectBody(null);
|
|
selectElement(dynamic);
|
|
return;
|
|
}
|
|
selectBody(this.closest('[data-studio-part="body"]'));
|
|
selectElement(this);
|
|
if (event.type === 'dblclick') replaceMedia();
|
|
});
|
|
$doc.on('click.canvas', (event) => {
|
|
const node = event.target;
|
|
const dynamic = node.closest?.('[data-studio-dynamic]');
|
|
if (dynamic) {
|
|
selectBody(null);
|
|
selectElement(dynamic);
|
|
return;
|
|
}
|
|
const field = node.closest?.(canvasFields);
|
|
selectElement(doc.getSelection()?.isCollapsed ? field || editableBodyElement(node) : null);
|
|
});
|
|
$doc.on('dblclick.canvas', '[data-studio-part="body"] a', function (event) {
|
|
event.preventDefault();
|
|
if (!this.closest('[data-studio-dynamic]') && !event.target.closest(mediaTargets)) editResource(this);
|
|
});
|
|
$doc.on('keydown.canvas', (event) => {
|
|
if (event.key === 'Escape') selectElement(null);
|
|
});
|
|
$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('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-jump]').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();
|
|
$studio.closest('.studio-layout').on('click', '[data-canvas-jump]', function () {
|
|
const section = doc?.getElementById(this.dataset.canvasJump);
|
|
const body = section?.querySelector('[data-studio-part="body"]');
|
|
if (!body) return;
|
|
$studio.get(0).scrollIntoView({block: 'start'});
|
|
section.scrollIntoView({block: 'start'});
|
|
if (section.hasAttribute('data-studio-dynamic')) selectElement(section);
|
|
else body.focus({preventScroll: true});
|
|
});
|
|
});
|
|
|
|
$('[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));
|
|
});
|
|
});
|
|
});
|