582 lines
28 KiB
JavaScript
582 lines
28 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();
|
|
});
|
|
|
|
$('[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 : 1280;
|
|
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 $settings = $studio.closest('.studio-layout').find('.studio-inspector');
|
|
$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() {
|
|
return sections.flatMap(({key, version, fields}) => {
|
|
const changes = {};
|
|
for (const [field, {node, initial}] of Object.entries(fields)) {
|
|
const value = field === 'body' ? node.innerHTML : node.textContent;
|
|
if (value !== initial) changes[field] = 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) => {
|
|
$studio.prop('inert', busy);
|
|
$settings.prop('inert', busy);
|
|
});
|
|
$(window).on('beforeunload', (event) => {
|
|
if (!saveComplete && (sectionChanges().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']) {
|
|
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 ((!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);
|
|
$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': '编辑首屏图片'}).on('click', () => {
|
|
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();
|
|
const target = url === '/#product' && $doc.find('.hero-home').length ? '/services' : url;
|
|
$button.text($label.val()).attr('href', safeLink(target) ? target : '#').prop('hidden', !$label.val() && !url);
|
|
}
|
|
$label.add($url).on('input.canvas', sync);
|
|
$button.on('click', (event) => {
|
|
event.preventDefault();
|
|
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);
|
|
});
|
|
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);
|
|
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 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);
|
|
sections = $doc.find('[data-studio-section]').map(function () {
|
|
const fields = {};
|
|
$(this).find('[data-studio-part]').each(function () {
|
|
const part = this.dataset.studioPart;
|
|
const body = part === 'body';
|
|
const label = {title: '区块标题', lead: '添加区块简介', body: '区块正文'}[part];
|
|
if (body) {
|
|
this.contentEditable = 'true';
|
|
this.setAttribute('aria-label', label);
|
|
this.dataset.studioPlaceholder = label;
|
|
} else {
|
|
configureText(this, label, part === 'lead');
|
|
}
|
|
fields[part] = {node: this, initial: body ? this.innerHTML : this.textContent};
|
|
});
|
|
return {key: this.id, version: Number(this.dataset.studioSection), fields};
|
|
}).get();
|
|
|
|
$doc.on('focusin.canvas', '[contenteditable]', function () {
|
|
selectBody(this.dataset.studioPart === 'body' ? this : null);
|
|
});
|
|
$doc.on('selectionchange.canvas', rememberSelection);
|
|
$doc.on('click.canvas auxclick.canvas', 'a', (event) => event.preventDefault());
|
|
$doc.on('click.canvas', '[data-studio-part="body"] a, [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video', function (event) {
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
const node = this;
|
|
selectBody(node.closest('[data-studio-part="body"]'));
|
|
editResource(node);
|
|
});
|
|
$doc.on('keydown.canvas', '[data-studio-hero-image]', function (event) {
|
|
if (event.key === 'Enter' || event.key === ' ') {
|
|
event.preventDefault();
|
|
$(this).trigger('click');
|
|
}
|
|
});
|
|
$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);
|
|
$studio.closest('.studio-layout').find('[data-canvas-jump]').prop('hidden', false);
|
|
}
|
|
|
|
$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));
|
|
});
|
|
});
|
|
});
|