forked from laysense/laysite
Fix canvas formatting persistence and editor interactions
This commit is contained in:
+110
-41
@@ -8,16 +8,25 @@ jQuery(function ($) {
|
||||
let files = [];
|
||||
let mediaType = '';
|
||||
let pickerRequest;
|
||||
const $pickerRefresh = $picker.find('[data-refresh-picker]');
|
||||
const mediaUpdates = 'BroadcastChannel' in window ? new BroadcastChannel('laysite-media') : null;
|
||||
|
||||
function imageAlt(file) {
|
||||
return window.laySiteAction({
|
||||
title: '插入图片', label: '替代文本(装饰图可留空)', value: file.label, accept: '插入',
|
||||
});
|
||||
}
|
||||
$picker.on('studio:image-alt', (_event, file) => imageAlt(file));
|
||||
|
||||
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) {
|
||||
async function mediaMarkup(file) {
|
||||
let $node;
|
||||
if (file.mime.startsWith('image/')) {
|
||||
const alt = window.prompt('图片替代文本(装饰图可留空)', file.label);
|
||||
const alt = await imageAlt(file);
|
||||
if (alt === null) return '';
|
||||
$node = $('<img>', {src: file.url, alt, loading: 'lazy'});
|
||||
} else if (file.mime.startsWith('video/') || file.mime.startsWith('audio/')) {
|
||||
@@ -49,19 +58,32 @@ jQuery(function ($) {
|
||||
if (!$picker.length || typeof $picker.get(0).showModal !== 'function') return;
|
||||
pick = callback;
|
||||
mediaType = type;
|
||||
files = [];
|
||||
$picker.find('[data-media-query]').val('');
|
||||
$pickerItems.empty();
|
||||
$pickerStatus.text('加载资源…');
|
||||
$picker.get(0).showModal();
|
||||
refreshPicker();
|
||||
}
|
||||
|
||||
function refreshPicker() {
|
||||
if (!$picker.get(0)?.open) return;
|
||||
pickerRequest?.abort();
|
||||
pickerRequest = $.getJSON('/admin/media/options').done(function (response) {
|
||||
$pickerStatus.text('正在刷新资源…');
|
||||
$pickerRefresh.prop('disabled', true);
|
||||
pickerRequest = $.ajax({url: '/admin/media/options', dataType: 'json', cache: false}).done((response) => {
|
||||
files = response.files;
|
||||
renderPicker();
|
||||
}).fail(function (_request, status) {
|
||||
if (status !== 'abort') $pickerStatus.text('媒体库暂时无法打开。');
|
||||
});
|
||||
}).fail((_request, status) => {
|
||||
if (status !== 'abort') $pickerStatus.text('媒体库暂时无法刷新,请重试。');
|
||||
}).always(() => $pickerRefresh.prop('disabled', false));
|
||||
}
|
||||
|
||||
$picker.on('click', '[data-refresh-picker]', refreshPicker);
|
||||
$(window).on('focus', refreshPicker);
|
||||
$(document).on('visibilitychange', () => { if (!document.hidden) refreshPicker(); });
|
||||
mediaUpdates?.addEventListener('message', (event) => { if (event.data === 'changed') refreshPicker(); });
|
||||
$('form[action^="/admin/media"]').on('studio:saved', () => mediaUpdates?.postMessage('changed'));
|
||||
|
||||
$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());
|
||||
@@ -78,14 +100,15 @@ jQuery(function ($) {
|
||||
openPicker($button.data('asset-type') || '', (file) => $input.val(file.url).trigger('input').trigger('focus'));
|
||||
});
|
||||
|
||||
$('[data-copy-asset]').on('click', function () {
|
||||
$('[data-copy-asset]').on('click', async function () {
|
||||
const $button = $(this);
|
||||
const url = $button.data('copy-asset');
|
||||
if (!navigator.clipboard) {
|
||||
window.prompt('复制资源路径', url);
|
||||
return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
$button.text('已复制');
|
||||
} catch {
|
||||
window.laySiteAction({title: '复制资源路径', label: '资源路径', value: url, readOnly: true, accept: '完成'});
|
||||
}
|
||||
navigator.clipboard.writeText(url).then(() => $button.text('已复制')).catch(() => window.prompt('复制资源路径', url));
|
||||
});
|
||||
|
||||
$('[data-media-library]').each(function () {
|
||||
@@ -311,6 +334,8 @@ jQuery(function ($) {
|
||||
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 minMediaWidth = Number($handle.attr('aria-valuemin'));
|
||||
const pathGroups = '[data-studio-navigation], [data-studio-breadcrumbs]';
|
||||
const $mediaSize = $sizing.find('[data-media-size]');
|
||||
const mediaWidthClass = /^studio-media-\d+$/;
|
||||
|
||||
@@ -395,6 +420,7 @@ jQuery(function ($) {
|
||||
let saveComplete = false;
|
||||
let syncPageFromInputs;
|
||||
let spacingTarget;
|
||||
let sourceEditor;
|
||||
|
||||
function classesOf(node, textOnly = false) {
|
||||
const result = {};
|
||||
@@ -450,15 +476,18 @@ jQuery(function ($) {
|
||||
}
|
||||
|
||||
function paintText(node, value, runs) {
|
||||
const display = runs?.map(([text]) => text).join('').trim() === value ? runs : [[value, '']];
|
||||
const lineBreaks = (text) => text.replace(/\r\n?/g, '\n');
|
||||
const plain = lineBreaks(value);
|
||||
const display = runs?.map(([text]) => lineBreaks(text)).join('').trim() === plain ? runs : [[plain, '']];
|
||||
node.replaceChildren();
|
||||
for (const [text, tokens] of display) {
|
||||
const parent = tokens ? doc.createElement('span') : node;
|
||||
if (tokens) {
|
||||
parent.className = tokens;
|
||||
installMarkupColors(tokens);
|
||||
node.append(parent);
|
||||
}
|
||||
text.split('\n').forEach((line, index) => {
|
||||
lineBreaks(text).split('\n').forEach((line, index) => {
|
||||
if (index) parent.append(doc.createElement('br'));
|
||||
if (line) parent.append(line);
|
||||
});
|
||||
@@ -525,7 +554,10 @@ jQuery(function ($) {
|
||||
|
||||
function setPageStyle(node, style) {
|
||||
node.classList.remove(...Object.values(classesOf(node)));
|
||||
if (style?.classes) node.classList.add(...style.classes.split(' '));
|
||||
if (style?.classes) {
|
||||
installMarkupColors(style.classes);
|
||||
node.classList.add(...style.classes.split(' '));
|
||||
}
|
||||
}
|
||||
|
||||
function canvasOrder() {
|
||||
@@ -596,7 +628,7 @@ jQuery(function ($) {
|
||||
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']) {
|
||||
for (const key of ['label', 'note', 'url', 'alt', 'poster', 'quicklinks', 'breadcrumbs', '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] : '');
|
||||
@@ -795,8 +827,14 @@ jQuery(function ($) {
|
||||
$spacingForm.find('input').each(function () {
|
||||
this.value = styles[this.name]?.slice(('studio-style-' + this.name + '-').length) || '';
|
||||
});
|
||||
$spacingForm.find('[data-spacing-preset]').val('');
|
||||
$spacing.get(0).showModal();
|
||||
});
|
||||
$spacingForm.on('change', '[data-spacing-preset]', function () {
|
||||
if (this.value !== '') $(this).closest('fieldset').find('input').val(this.value === 'template' ? '' : this.value);
|
||||
}).on('input', 'input', function () {
|
||||
$(this).closest('fieldset').find('[data-spacing-preset]').val('');
|
||||
});
|
||||
$elementTools.on('click', '[data-element-parent]', () => {
|
||||
const parent = parentElement(selectedElement);
|
||||
if (!parent) return;
|
||||
@@ -822,8 +860,8 @@ jQuery(function ($) {
|
||||
const range = savedRange?.cloneRange();
|
||||
const edit = (action, value) => editBody(body, range, action, value);
|
||||
if (command === 'media') {
|
||||
openPicker('', (file) => {
|
||||
const markup = mediaMarkup(file);
|
||||
openPicker('', async (file) => {
|
||||
const markup = await mediaMarkup(file);
|
||||
if (markup) edit('insertHTML', markup);
|
||||
});
|
||||
} else if (command === 'link') {
|
||||
@@ -1064,6 +1102,7 @@ jQuery(function ($) {
|
||||
renderLayers();
|
||||
};
|
||||
paths[type] = {read, sync, write};
|
||||
heroControls.set('remove-' + type, () => write([]));
|
||||
heroControls.set(type, () => {
|
||||
const field = crumb ? 'breadcrumbs' : 'quicklinks';
|
||||
openProperties(config.heading, {[field]: $input.val()}, (values) => {
|
||||
@@ -1287,11 +1326,14 @@ jQuery(function ($) {
|
||||
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;
|
||||
const top = Math.max(0, bounds.top);
|
||||
const bottom = Math.min(container.clientHeight, bounds.bottom);
|
||||
const visible = bounds.width > 0 && bounds.right > 0 && bounds.left < container.clientWidth && bottom > top;
|
||||
$handle.prop('hidden', !mediaDrag && !visible);
|
||||
$handle.css({left: Math.max(11, Math.min(x, container.clientWidth - 11)), top: y});
|
||||
$handle.css({
|
||||
left: Math.max(11, Math.min(x, container.clientWidth - 11)),
|
||||
top: Math.max(23, Math.min((top + bottom) / 2, container.clientHeight - 23)),
|
||||
});
|
||||
} else {
|
||||
$handle.prop('hidden', true);
|
||||
}
|
||||
@@ -1380,10 +1422,11 @@ jQuery(function ($) {
|
||||
$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' ? '删除首屏'
|
||||
const pathGroup = node.matches(pathGroups);
|
||||
const deleteLabel = pathGroup ? (node.hasAttribute('data-studio-navigation') ? '删除本页目录' : '删除面包屑') : 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));
|
||||
.prop('hidden', !hero && !pathGroup && !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));
|
||||
@@ -1411,7 +1454,10 @@ jQuery(function ($) {
|
||||
}
|
||||
const inBody = Boolean(node.parentElement?.closest('[data-studio-part="body"]'));
|
||||
selectElement(null);
|
||||
if (inBody) {
|
||||
if (!copy && node.matches(pathGroups)) {
|
||||
heroControls.get(node.hasAttribute('data-studio-breadcrumbs') ? 'remove-breadcrumbs' : 'remove-navigation')();
|
||||
captureHistory();
|
||||
} else if (inBody) {
|
||||
if (copy) {
|
||||
const $clone = $(node.cloneNode(true));
|
||||
$clone.find('[id]').addBack('[id]').removeAttr('id');
|
||||
@@ -1571,8 +1617,23 @@ jQuery(function ($) {
|
||||
}
|
||||
$source.find('[data-source-reset]').prop('hidden', true);
|
||||
}
|
||||
for (const part of parts.values()) part.draft = part.original;
|
||||
for (const [key, part] of parts) {
|
||||
if (key === 'body' || key === 'hero') {
|
||||
part.original = window.html_beautify?.(part.original, {indent_size: 2}) ?? part.original;
|
||||
}
|
||||
part.draft = part.original;
|
||||
}
|
||||
sourceParts = parts;
|
||||
if (!sourceEditor && window.CodeMirror) {
|
||||
sourceEditor = window.CodeMirror.fromTextArea($sourceCode.get(0), {
|
||||
mode: {name: 'xml', htmlMode: true}, lineNumbers: true, lineWrapping: true,
|
||||
indentUnit: 2, tabSize: 2, viewportMargin: 10,
|
||||
});
|
||||
sourceEditor.getInputField().setAttribute('aria-label', 'HTML 源码');
|
||||
sourceEditor.on('change', (editor) => {
|
||||
if (sourceParts) sourceParts.get($sourcePart.val()).draft = editor.getValue();
|
||||
});
|
||||
}
|
||||
$sourcePart.empty();
|
||||
for (const [key, {label}] of parts) $('<option>', {value: key, text: label}).appendTo($sourcePart);
|
||||
$sourcePart.prop('disabled', hero).triggerHandler('change');
|
||||
@@ -1581,11 +1642,18 @@ jQuery(function ($) {
|
||||
: '可编辑标题、简介和正文。区块外壳与动态文章列表由系统渲染。');
|
||||
$sourceError.prop('hidden', true);
|
||||
$source.get(0).showModal();
|
||||
$sourceCode.trigger('focus');
|
||||
if (sourceEditor) {
|
||||
sourceEditor.refresh();
|
||||
sourceEditor.focus();
|
||||
} else $sourceCode.trigger('focus');
|
||||
}
|
||||
|
||||
$sourcePart.on('change', () => {
|
||||
$sourceCode.val(sourceParts.get($sourcePart.val()).draft);
|
||||
const draft = sourceParts.get($sourcePart.val()).draft;
|
||||
if (sourceEditor) {
|
||||
sourceEditor.setValue(draft);
|
||||
sourceEditor.clearHistory();
|
||||
} else $sourceCode.val(draft);
|
||||
$sourceError.prop('hidden', true);
|
||||
});
|
||||
$sourceCode.on('input', () => { sourceParts.get($sourcePart.val()).draft = $sourceCode.val(); });
|
||||
@@ -1791,7 +1859,7 @@ jQuery(function ($) {
|
||||
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 || layerContext(node) || node.matches(pathGroups) || 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,
|
||||
@@ -1937,10 +2005,11 @@ jQuery(function ($) {
|
||||
});
|
||||
}
|
||||
|
||||
function changeModule(section, copy) {
|
||||
async function changeModule(section, copy) {
|
||||
if (!section) return;
|
||||
if (!copy) {
|
||||
if (window.confirm('删除此区块?保存页面后生效。')) {
|
||||
const confirmed = await window.laySiteAction({title: '删除区块', message: '保存页面后生效,可在画布上撤销。', accept: '删除'});
|
||||
if (confirmed && section.node.isConnected) {
|
||||
removeSection(section);
|
||||
$studio.find('[data-canvas-status]').text('区块已移除,保存页面后生效。');
|
||||
}
|
||||
@@ -1975,12 +2044,12 @@ jQuery(function ($) {
|
||||
const classes = node.getAttribute('class');
|
||||
setMediaWidth(node, 100);
|
||||
const full = node.getBoundingClientRect();
|
||||
setMediaWidth(node, 10);
|
||||
setMediaWidth(node, minMediaWidth);
|
||||
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 edgeTravel = (fromLeft ? narrow.left - full.left : full.right - narrow.right) / (1 - minMediaWidth / 100);
|
||||
const available = edgeTravel > full.width * .15 ? edgeTravel : full.width;
|
||||
return {available, fromLeft, initialWidth: width || Math.round(100 * natural / (full.width || natural || 1))};
|
||||
}
|
||||
@@ -1988,7 +2057,7 @@ jQuery(function ($) {
|
||||
function resizeMedia(width) {
|
||||
const node = sizingTarget();
|
||||
if (!node) return;
|
||||
const next = width === null ? 0 : Math.round(Math.max(10, Math.min(100, width)));
|
||||
const next = width === null ? 0 : Math.round(Math.max(minMediaWidth, 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);
|
||||
@@ -2019,7 +2088,7 @@ jQuery(function ($) {
|
||||
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);
|
||||
const next = {Home: minMediaWidth, End: 100}[event.key] ?? initialWidth + (increase ? step : -step);
|
||||
resizeMedia(next);
|
||||
});
|
||||
$sizing.on('click', '[data-replace-media]', replaceMedia)
|
||||
@@ -2063,7 +2132,7 @@ jQuery(function ($) {
|
||||
$status.text('已插入' + $(this).text() + '。');
|
||||
};
|
||||
if (this.dataset.elementMime) {
|
||||
openPicker(this.dataset.elementMime, (file) => add(mediaMarkup(file)));
|
||||
openPicker(this.dataset.elementMime, async (file) => add(await mediaMarkup(file)));
|
||||
} else {
|
||||
add($presets.find('template[data-element="' + this.dataset.canvasElement + '"]').get(0).innerHTML);
|
||||
}
|
||||
@@ -2307,7 +2376,7 @@ jQuery(function ($) {
|
||||
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]');
|
||||
const wrapper = node.closest('[data-studio-section], [data-studio-hero], ' + pathGroups);
|
||||
selectBody(body);
|
||||
selectElement(doc.getSelection()?.isCollapsed ? leaf || (body === node ? wrapper || body : body || wrapper) : null);
|
||||
});
|
||||
@@ -2431,10 +2500,10 @@ jQuery(function ($) {
|
||||
});
|
||||
|
||||
$editor.on('mousedown', '[data-insert], [data-rich-media]', (event) => event.preventDefault());
|
||||
$editor.on('click', '[data-insert]', function () {
|
||||
$editor.on('click', '[data-insert]', async function () {
|
||||
const command = $(this).data('insert');
|
||||
if (command === 'link') {
|
||||
const href = window.prompt('输入链接地址', 'https://')?.trim();
|
||||
const href = (await window.laySiteAction({title: '插入链接', label: '链接地址', value: 'https://', accept: '插入'}))?.trim();
|
||||
if (!href) return;
|
||||
if (!safeLink(href)) {
|
||||
$status.prop('hidden', false).text('请输入站内地址或有效的链接。');
|
||||
@@ -2455,8 +2524,8 @@ jQuery(function ($) {
|
||||
});
|
||||
|
||||
$editor.on('click', '[data-rich-media]', function () {
|
||||
openPicker('', (file) => {
|
||||
const markup = mediaMarkup(file);
|
||||
openPicker('', async (file) => {
|
||||
const markup = await mediaMarkup(file);
|
||||
if (markup) edit('insertHTML', markup);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user