Files
laysense.cn/public/assets/studio.js
T

856 lines
40 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('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 $search = $gallery.find('[data-template-search]');
const $groups = $gallery.find('[data-template-group]');
const $filters = $gallery.find('[data-template-filter]');
const $peek = $gallery.find('[data-template-peek]');
const $dialog = $gallery.find('[data-template-dialog]');
const $use = $dialog.find('[data-template-use]');
let category = '';
let $selection;
function hidePeek() {
$peek.prop('hidden', true);
}
function filter() {
const query = String($search.val()).trim().toLowerCase();
let count = 0;
$groups.each(function () {
const $group = $(this);
const allowed = !category || this.dataset.templateGroup === category;
let groupCount = 0;
$group.find('[data-template-card]').each(function () {
const visible = allowed && this.dataset.templateSearchText.toLowerCase().includes(query);
$(this).prop('hidden', !visible);
if (visible) groupCount++;
});
$group.prop('hidden', groupCount === 0);
count += groupCount;
});
$gallery.find('[data-template-empty]').prop('hidden', count !== 0);
hidePeek();
}
$search.on('input', filter);
$filters.on('click', function () {
category = this.dataset.templateFilter;
$filters.attr('aria-pressed', 'false');
$(this).attr('aria-pressed', 'true');
filter();
});
$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');
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 + ')'
});
}
if ('ResizeObserver' in window) {
new ResizeObserver(fitPreview).observe($window.get(0));
} else {
$(window).on('resize', fitPreview);
}
fitPreview();
const $layout = $studio.closest('.studio-layout');
const $settings = $layout.find('.studio-inspector');
const $sizing = $studio.find('[data-media-sizing]');
const $width = $sizing.find('[data-media-width]');
const availableWidths = Array.from($width.get(0).options, ({value}) => value).filter((value) => value !== '0');
const sizeClasses = availableWidths.map((value) => 'studio-media-' + value);
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 selectedMedia;
$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 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) {
return sections.flatMap(({key, version, fields, source}) => {
const changes = {};
for (const [field, {node, initial}] of Object.entries(fields)) {
const value = field === 'body' ? node.innerHTML : node.textContent;
if (version === null || value !== initial) {
changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value;
}
}
return Object.keys(changes).length ? [{key, version, fields: changes}] : [];
});
}
$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', 'url', 'alt', 'poster', 'quicklinks']) {
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 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);
syncImage();
$image.attr({tabindex: '0', role: 'button', 'aria-label': '编辑首屏图片'});
heroControls.set('image', () => {
openProperties('首屏图片', {url: pageInput('image').val(), alt: pageInput('alt').val()}, ({url, alt}) => {
pageInput('image').val(url);
pageInput('alt').val(alt);
syncImage();
}, 'image/', true);
});
$doc.find('[data-studio-action]').each(function () {
const $button = $(this);
const index = this.dataset.studioAction;
const $label = pageInput('label' + index);
const $url = pageInput('url' + index);
function sync() {
const url = $url.val().trim();
$button.text($label.val()).attr('href', safeLink(url) ? url : '#').prop('hidden', !$label.val() && !url);
}
$label.add($url).on('input.canvas', sync);
const editButton = () => {
openProperties('首屏按钮', {label: $label.val(), url: $url.val()}, ({label, url}) => {
if (Boolean(label) !== Boolean(url)) {
$propertyError.prop('hidden', false).text('请同时填写按钮文案和链接,或将两项都留空。');
return false;
}
$label.val(label);
$url.val(url);
sync();
}, null, true);
};
heroControls.set(index, editButton);
$button.on('click', (event) => {
event.preventDefault();
editButton();
});
sync();
});
const $navigation = $doc.find('[data-studio-navigation]');
const $navContent = $navigation.find('.section-nav-inner');
const $navInput = pageInput('quicklinks');
const navLines = () => $navInput.val().split(/\r\n|[\n\r\v\f\u0085\u2028\u2029]/);
function syncNavigation() {
const lines = navLines();
$navContent.empty();
for (const [index, line] of lines.entries()) {
if (!line.trim()) continue;
const separator = line.indexOf('|');
const label = (separator < 0 ? line : line.slice(0, separator)).trim();
const url = separator < 0 ? '' : line.slice(separator + 1).trim();
const link = doc.createElement('a');
link.href = safeLink(url) ? url : '#';
link.textContent = label || url;
link.addEventListener('click', (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);
}
$navInput.on('input.canvas', syncNavigation);
heroControls.set('navigation', () => {
openProperties('本页目录', {quicklinks: $navInput.val()}, ({quicklinks}) => {
$navInput.val(quicklinks);
syncNavigation();
});
});
syncNavigation();
}
function editResource(node) {
const tag = node.localName;
if (tag === 'a') {
const onlyChild = node.firstElementChild;
const text = node.childElementCount === 0 ? node : (
node.childElementCount === 1 && onlyChild.matches('span, strong, b, em, i, small')
&& !onlyChild.childElementCount && node.textContent.trim() === onlyChild.textContent.trim() ? onlyChild : null
);
const values = text ? {label: text.textContent, url: node.getAttribute('href') || ''} : {url: node.getAttribute('href') || ''};
openProperties('正文链接', values, ({label, url}) => {
node.setAttribute('href', url);
if (text && label !== values.label) text.textContent = label;
});
return;
}
const source = tag === 'img' ? node : (node.hasAttribute('src') ? node : node.querySelector('source') || node);
const values = {url: source.getAttribute('src') || ''};
if (tag === 'img') values.alt = node.getAttribute('alt') || '';
if (tag === 'video') values.poster = node.getAttribute('poster') || '';
openProperties({img: '正文图片', video: '视频', audio: '音频'}[tag], values, ({url, alt, poster}) => {
if (url !== values.url) {
source.setAttribute('src', url);
if (source !== node) source.removeAttribute('type');
if (tag !== 'img') node.load();
}
if (alt !== undefined && alt !== values.alt) node.setAttribute('alt', alt);
if (poster !== undefined && poster !== values.poster) {
if (poster) node.setAttribute('poster', poster);
else node.removeAttribute('poster');
}
}, (tag === 'img' ? 'image' : tag) + '/');
}
function registerSection(section, version = Number(section.dataset.studioSection)) {
const fields = {};
for (const node of section.querySelectorAll('[data-studio-part]')) {
const part = node.dataset.studioPart;
const body = part === 'body';
const label = {title: '区块标题', lead: '添加区块简介', body: '区块正文'}[part];
if (body) {
node.contentEditable = 'true';
node.setAttribute('aria-label', label);
node.dataset.studioPlaceholder = label;
} else {
configureText(node, label, part === 'lead');
}
fields[part] = {node, initial: body ? node.innerHTML : node.textContent};
}
const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from(
atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0)
));
sections.push({key: section.id, version, fields, source});
}
function setMediaWidth(node, width) {
node.classList.remove(...sizeClasses);
if (availableWidths.includes(width)) node.classList.add('studio-media-' + width);
}
function selectMedia(node) {
selectedMedia?.removeAttribute('data-studio-selected');
selectedMedia = node;
if (!node) {
$sizing.prop('hidden', true);
return;
}
node.setAttribute('data-studio-selected', '');
const width = node.hasAttribute('data-studio-hero-image') ? pageInput('image_scale').val()
: availableWidths.find((value) => node.classList.contains('studio-media-' + value)) || '0';
$width.val(width);
$sizing.prop('hidden', false);
}
function replaceMedia() {
if (!selectedMedia?.isConnected) return;
if (selectedMedia.hasAttribute('data-studio-hero-image')) heroControls.get('image')();
else editResource(selectedMedia);
}
$width.on('change', function () {
if (!selectedMedia?.isConnected) return;
const hero = selectedMedia.hasAttribute('data-studio-hero-image');
if (hero) pageInput('image_scale').val(this.value);
setMediaWidth(hero ? selectedMedia.parentElement : selectedMedia, this.value);
});
$sizing.on('click', '[data-replace-media]', replaceMedia);
$layout.on('click', '[data-hero-control]', function () {
heroControls.get(this.dataset.heroControl)?.();
});
$presets.on('mousedown', '[data-canvas-template]', (event) => event.preventDefault());
$presets.on('click', '[data-canvas-template]', function () {
const markup = $presets.find('template[data-preset="' + this.dataset.canvasTemplate + '"]').get(0).innerHTML;
if ($presets.find('[data-template-inline]').prop('checked')) {
if (!activeBody) {
$templateStatus.text('先在画布中选择要插入的区块正文。');
return;
}
// Insert at the saved caret without replacing any selected text.
const insertion = savedRange?.cloneRange();
insertion?.collapse(false);
editBody(activeBody, insertion, 'insertHTML', markup);
$templateStatus.text('已插入当前正文。');
return;
}
if (sections.filter(({version}) => version === null).length >= 50) {
$templateStatus.text('请先保存,再添加更多区块。');
return;
}
const end = doc.querySelector('[data-studio-section-end]');
const section = end.content.firstElementChild.cloneNode(true);
const id = 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('');
section.id = id;
const title = section.querySelector('[data-studio-part="title"]');
title.id = 'heading-' + id;
title.textContent = this.dataset.templateTitle;
section.setAttribute('aria-labelledby', title.id);
section.querySelector('[data-studio-part="body"]').innerHTML = markup;
end.before(section);
registerSection(section, null);
section.scrollIntoView({block: 'start'});
section.querySelector('[data-studio-part="body"]').focus({preventScroll: true});
const $cancel = $('<button>', {type: 'button', text: '取消新增:' + title.textContent});
const $item = $('<li>').append($cancel).appendTo($pending);
$pending.prop('hidden', false);
$cancel.on('click', () => {
if (section.contains(activeBody)) selectBody(null);
if (section.contains(selectedMedia)) selectMedia(null);
section.remove();
sections = sections.filter(({key}) => key !== id);
$item.remove();
$pending.prop('hidden', !$pending.children().length);
$templateStatus.text('已取消新增区块。');
});
$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);
selectMedia(null);
$pending.empty().prop('hidden', true);
sections = [];
$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);
$doc.on('click.canvas', (event) => {
if (!event.target.closest?.('[data-studio-selected]')) selectMedia(null);
});
$doc.on('click.canvas auxclick.canvas', 'a', (event) => event.preventDefault());
const mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video';
$doc.on('click.canvas dblclick.canvas', mediaTargets, function (event) {
event.preventDefault();
event.stopPropagation();
selectBody(this.closest('[data-studio-part="body"]'));
selectMedia(this);
if (event.type === 'dblclick') replaceMedia();
});
$doc.on('click.canvas', '[data-studio-part="body"] a', function (event) {
event.preventDefault();
if ($(this).find('img, audio, video').length && event.target.closest('img, audio, video')) return;
selectBody(this.closest('[data-studio-part="body"]'));
editResource(this);
});
$doc.on('keydown.canvas', '[data-studio-hero-image]', function (event) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
selectMedia(this);
$width.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-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'});
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));
});
});
});