feat(submit): add user media library
This commit is contained in:
1 parent
44e165d34e
commit
f3fcfe45da
23 files changed
+1321
-945
No files matched your search
@@ -289,6 +289,200 @@ body.aksrt-editor-media-open {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__search {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__search .form-control {
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__search .but {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__status {
|
||||
min-height: 20px;
|
||||
margin: 4px 0 10px;
|
||||
color: var(--muted-color, #777);
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__status.is-loading {
|
||||
color: var(--muted-color, #777);
|
||||
}
|
||||
|
||||
.aksrt-editor-media__status.is-error {
|
||||
color: var(--danger-color, #e05252);
|
||||
}
|
||||
|
||||
.aksrt-editor-media__status.is-empty {
|
||||
padding: 28px 10px;
|
||||
color: var(--muted-2-color, #999);
|
||||
}
|
||||
|
||||
.aksrt-editor-media__list {
|
||||
display: grid;
|
||||
max-height: min(390px, 48vh);
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
overflow-y: auto;
|
||||
padding: 2px;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__item {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--main-border-color, rgba(50, 50, 50, 0.1));
|
||||
border-radius: var(--main-radius, 8px);
|
||||
background: var(--muted-bg-color, rgba(50, 50, 50, 0.03));
|
||||
color: var(--main-color, #333);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.2s, box-shadow 0.2s, opacity 0.2s;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__item:hover,
|
||||
.aksrt-editor-media__item:focus-visible {
|
||||
border-color: var(--focus-color, #f04494);
|
||||
outline: 0;
|
||||
box-shadow: 0 0 0 2px var(--focus-shadow-color, rgba(240, 68, 148, 0.15));
|
||||
}
|
||||
|
||||
.aksrt-editor-media__item.is-selected {
|
||||
border-color: var(--focus-color, #f04494);
|
||||
box-shadow: inset 0 0 0 2px var(--focus-color, #f04494);
|
||||
}
|
||||
|
||||
.aksrt-editor-media__item:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__check {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
top: 6px;
|
||||
left: 6px;
|
||||
display: flex;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 50%;
|
||||
background: rgba(0, 0, 0, 0.58);
|
||||
color: #fff;
|
||||
opacity: 0;
|
||||
font-size: 11px;
|
||||
line-height: 1;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__item.is-selected .aksrt-editor-media__check {
|
||||
background: var(--focus-color, #f04494);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__thumb {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
height: 104px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
background: var(--muted-border-color, rgba(50, 50, 50, 0.06));
|
||||
}
|
||||
|
||||
.aksrt-editor-media__thumb img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__file-icon {
|
||||
color: var(--focus-color, #f04494);
|
||||
font-size: 30px;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__meta {
|
||||
display: block;
|
||||
min-height: 34px;
|
||||
padding: 7px 8px;
|
||||
overflow: hidden;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__mine-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__mine-actions .but {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__load-more {
|
||||
display: block;
|
||||
min-width: 110px;
|
||||
margin: 12px 0 0;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__load-more[hidden],
|
||||
.aksrt-editor-media__confirm[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__confirm {
|
||||
margin: 12px 0 0 auto;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__selection {
|
||||
min-height: 20px;
|
||||
margin-top: 10px;
|
||||
color: var(--muted-color, #777);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__progress {
|
||||
position: relative;
|
||||
min-height: 34px;
|
||||
margin-top: 10px;
|
||||
padding: 9px 10px;
|
||||
overflow: hidden;
|
||||
border-radius: 4px;
|
||||
background: var(--muted-border-color, rgba(50, 50, 50, 0.08));
|
||||
color: var(--muted-color, #777);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__progress::before {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
height: 3px;
|
||||
width: var(--aksrt-upload-progress, 0%);
|
||||
background: var(--focus-color, #f04494);
|
||||
content: '';
|
||||
transition: width 0.2s;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__submit:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.featured-edit {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
@@ -548,6 +742,38 @@ body.aksrt-editor-media-open {
|
||||
border-radius: 12px 12px 0 0;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__list {
|
||||
max-height: 42vh;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__thumb {
|
||||
height: 92px;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__tabs {
|
||||
gap: 14px;
|
||||
overflow-x: auto;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__panel {
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__mine-actions {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__mine-actions .aksrt-editor-media__load-more {
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.aksrt-editor-media__search .but {
|
||||
padding-right: 10px;
|
||||
padding-left: 10px;
|
||||
}
|
||||
.aksrt-editor-media__drop {
|
||||
min-height: 150px;
|
||||
}
|
||||
|
||||
+378
-391
@@ -6,10 +6,6 @@
|
||||
(function (window, document) {
|
||||
'use strict';
|
||||
|
||||
if (!window.tinymce || !window.tinymce.PluginManager) {
|
||||
return;
|
||||
}
|
||||
|
||||
var cfg = window.aksrtSubmitData || {};
|
||||
var editorCfg = cfg.editor || {};
|
||||
var i18n = cfg.i18n || {};
|
||||
@@ -47,14 +43,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
function imageMarkup(url, attachmentId, alt) {
|
||||
function imageMarkup(url, attachmentId, alt, fullUrl) {
|
||||
var safeUrl = validHttpUrl(url);
|
||||
var safeFullUrl = validHttpUrl(fullUrl || url);
|
||||
if (!safeUrl) {
|
||||
return '';
|
||||
}
|
||||
var idAttr = attachmentId ? ' data-edit-file-id="' + Number(attachmentId) + '"' : '';
|
||||
var altAttr = alt ? ' alt="' + escapeAttr(alt) + '"' : ' alt=""';
|
||||
return '<p><img src="' + escapeAttr(safeUrl) + '"' + idAttr + altAttr + '></p>';
|
||||
var fullAttr = safeFullUrl ? ' data-full-url="' + escapeAttr(safeFullUrl) + '"' : '';
|
||||
return '<p><img src="' + escapeAttr(safeUrl) + '"' + idAttr + altAttr + fullAttr + '></p>';
|
||||
}
|
||||
|
||||
function videoMarkup(url, attachmentId, name) {
|
||||
@@ -74,7 +72,7 @@
|
||||
return '';
|
||||
}
|
||||
var filename = String(name || safeUrl.split('/').pop() || i18n.attachment || '附件');
|
||||
var idAttr = attachmentId ? ' data-download-file="' + Number(attachmentId) + '"' : '';
|
||||
var idAttr = attachmentId ? ' data-aksrt-file-id="' + Number(attachmentId) + '"' : '';
|
||||
return '<div class="mb20 muted-box file-download-box" contenteditable="false">' +
|
||||
'<div class="flex ac jsb"><div class="flex ac"><div class="mr10">' +
|
||||
'<div class="file-download-icon"><i class="fa fas fa-file-alt" aria-hidden="true"></i></div></div>' +
|
||||
@@ -99,334 +97,278 @@
|
||||
'</div></div>';
|
||||
}
|
||||
|
||||
function closeMediaModal() {
|
||||
if (!activeModal) {
|
||||
return;
|
||||
function mediaUrl(type) {
|
||||
var configured = cfg.media && cfg.media[type] && cfg.media[type].url;
|
||||
if (configured) {
|
||||
return String(configured).indexOf('{type}') !== -1
|
||||
? String(configured).replace('{type}', encodeURIComponent(type))
|
||||
: String(configured);
|
||||
}
|
||||
document.removeEventListener('keydown', activeModal.onKeydown);
|
||||
activeModal.root.remove();
|
||||
activeModal = null;
|
||||
document.body.classList.remove('aksrt-editor-media-open');
|
||||
var base = cfg.mediaUrl || '';
|
||||
if (String(base).indexOf('{type}') !== -1) return String(base).replace('{type}', encodeURIComponent(type));
|
||||
if (base) return String(base).replace(/\/$/, '') + '/' + encodeURIComponent(type);
|
||||
return cfg.restUrl ? cfg.restUrl.replace(/\/$/, '') + '/front-submit/media/' + encodeURIComponent(type) : ''; }
|
||||
|
||||
function currentPostId() {
|
||||
var field = document.querySelector('#aksrt-submit-form input[name="posts_id"]');
|
||||
return Number((field && field.value) || cfg.postId || 0) || 0;
|
||||
}
|
||||
|
||||
function acceptsFile(file, type) {
|
||||
if (!file) {
|
||||
return false;
|
||||
}
|
||||
if (type === 'image') {
|
||||
return /^image\//.test(file.type || '');
|
||||
}
|
||||
if (type === 'video') {
|
||||
return /^video\//.test(file.type || '');
|
||||
}
|
||||
if (!file) return false;
|
||||
if (type === 'image') return /^image\//.test(file.type || '');
|
||||
if (type === 'video') return /^video\//.test(file.type || '');
|
||||
return true;
|
||||
}
|
||||
|
||||
function uploadMedia(file, type) {
|
||||
var uploadKey = type === 'file' ? 'resource' : type;
|
||||
var upload = (cfg.uploads || {})[uploadKey] || null;
|
||||
if (!upload || !upload.url) {
|
||||
return Promise.reject(new Error(i18n.uploadUnavailable || '当前账号不能上传此类文件'));
|
||||
}
|
||||
if (!acceptsFile(file, type)) {
|
||||
return Promise.reject(new Error(i18n.invalidFile || '请选择有效文件'));
|
||||
}
|
||||
if (upload.maxSize && file.size > upload.maxSize) {
|
||||
return Promise.reject(new Error(i18n.fileTooLarge || '文件大小超过限制'));
|
||||
}
|
||||
|
||||
if (!upload || !upload.url) return Promise.reject(new Error(i18n.uploadUnavailable || '当前账号不能上传此类文件'));
|
||||
if (!acceptsFile(file, type)) return Promise.reject(new Error(i18n.invalidFile || '请选择有效文件'));
|
||||
if (upload.maxSize && file.size > upload.maxSize) return Promise.reject(new Error(i18n.fileTooLarge || '文件大小超过限制'));
|
||||
var body = new FormData();
|
||||
body.append('file', file);
|
||||
return fetch(upload.url, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'X-WP-Nonce': cfg.restNonce || '' },
|
||||
body: body,
|
||||
}).then(function (response) {
|
||||
return response.json().catch(function () {
|
||||
return {};
|
||||
}).then(function (payload) {
|
||||
if (!response.ok || !payload || !payload.success || !payload.url) {
|
||||
throw new Error((payload && payload.message) || i18n.error || '文件上传失败');
|
||||
}
|
||||
return payload;
|
||||
var uploadUrl = String(upload.url);
|
||||
if (currentPostId()) {
|
||||
uploadUrl += (uploadUrl.indexOf('?') === -1 ? '?' : '&') + 'post_id=' + encodeURIComponent(String(currentPostId()));
|
||||
}
|
||||
return fetch(uploadUrl, { method: 'POST', credentials: 'same-origin', headers: { 'X-WP-Nonce': cfg.restNonce || '' }, body: body })
|
||||
.then(function (response) {
|
||||
return response.json().catch(function () { return {}; }).then(function (payload) {
|
||||
if (!response.ok || !payload || !payload.success || !payload.url) {
|
||||
throw new Error((payload && (payload.message || (payload.data && payload.data.message))) || i18n.error || '文件上传失败');
|
||||
}
|
||||
return payload;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function mediaDefinition(type) {
|
||||
if (type === 'video') {
|
||||
return {
|
||||
title: i18n.insertVideo || '插入视频',
|
||||
uploadTab: i18n.uploadVideo || '上传视频',
|
||||
externalTab: i18n.externalVideo || '外链视频',
|
||||
embedTab: i18n.embedVideo || '嵌入视频',
|
||||
accept: 'video/*',
|
||||
multiple: false,
|
||||
canUpload: !!editorCfg.canUploadVideo && !!((cfg.uploads || {}).video),
|
||||
canEmbed: !!editorCfg.canEmbedVideo,
|
||||
select: i18n.selectVideo || '选择或拖入视频',
|
||||
hint: i18n.videoUploadHint || '上传完成后自动插入正文',
|
||||
externalHint: i18n.externalVideoHint || '请填写视频文件地址:',
|
||||
};
|
||||
}
|
||||
if (type === 'file') {
|
||||
return {
|
||||
title: i18n.insertFile || '上传附件',
|
||||
uploadTab: i18n.uploadFile || '上传附件',
|
||||
externalTab: i18n.externalFile || '输入地址',
|
||||
accept: '*/*',
|
||||
multiple: false,
|
||||
canUpload: !!editorCfg.canUploadFile && !!((cfg.uploads || {}).resource),
|
||||
canEmbed: false,
|
||||
select: i18n.selectFile || '选择或拖入附件',
|
||||
hint: i18n.fileUploadHint || '上传完成后自动插入正文',
|
||||
externalHint: i18n.externalFileHint || '请填写附件地址:',
|
||||
};
|
||||
}
|
||||
if (type === 'video') return {
|
||||
title: i18n.insertVideo || '插入视频', mineTab: i18n.mineVideo || '我的视频', uploadTab: i18n.uploadVideo || '上传视频',
|
||||
externalTab: i18n.externalVideo || '外链视频', embedTab: i18n.embedVideo || '嵌入视频', accept: 'video/*', multiple: false, maxItems: 1,
|
||||
canUpload: !!editorCfg.canUploadVideo && !!((cfg.uploads || {}).video), canEmbed: !!editorCfg.canEmbedVideo,
|
||||
select: i18n.selectVideo || '选择或拖入视频', hint: i18n.videoUploadHint || '上传完成后自动插入正文', externalHint: i18n.externalVideoHint || '请填写视频文件地址:',
|
||||
};
|
||||
if (type === 'file') return {
|
||||
title: i18n.insertFile || '上传附件', mineTab: i18n.mineFile || '我的文件', uploadTab: i18n.uploadFile || '上传附件', externalTab: i18n.externalFile || '输入地址',
|
||||
accept: '*/*', multiple: false, maxItems: 1, canUpload: !!editorCfg.canUploadFile && !!((cfg.uploads || {}).resource), canEmbed: false,
|
||||
select: i18n.selectFile || '选择或拖入附件', hint: i18n.fileUploadHint || '上传完成后自动插入正文', externalHint: i18n.externalFileHint || '请填写附件地址:',
|
||||
};
|
||||
return {
|
||||
title: i18n.insertImage || '插入图片',
|
||||
uploadTab: i18n.uploadImage || '上传图片',
|
||||
externalTab: i18n.externalImage || '外链图片',
|
||||
accept: 'image/gif,image/jpeg,image/png,image/webp',
|
||||
multiple: true,
|
||||
canUpload: !!editorCfg.canUploadImage && !!((cfg.uploads || {}).image),
|
||||
canEmbed: false,
|
||||
select: i18n.selectImages || '选择或拖入图片',
|
||||
hint: i18n.imageUploadHint || '可批量选择,上传完成后自动插入正文',
|
||||
externalHint: i18n.externalImageHint || '每行填写一个图片地址:',
|
||||
title: i18n.insertImage || '插入图片', mineTab: i18n.mineImage || '我的图片', uploadTab: i18n.uploadImage || '上传图片', externalTab: i18n.externalImage || '外链图片',
|
||||
accept: 'image/gif,image/jpeg,image/png,image/webp', multiple: true, maxItems: 100, canUpload: !!editorCfg.canUploadImage && !!((cfg.uploads || {}).image), canEmbed: false,
|
||||
select: i18n.selectImages || '选择或拖入图片', hint: i18n.imageUploadHint || '可批量选择,上传完成后自动插入正文', externalHint: i18n.externalImageHint || '每行填写一个图片地址:',
|
||||
};
|
||||
}
|
||||
|
||||
function mediaMarkup(type, item) {
|
||||
if (type === 'video') {
|
||||
return videoMarkup(item.url, item.attachment_id, item.filename || item.name || '');
|
||||
}
|
||||
if (type === 'file') {
|
||||
return fileMarkup(item.url, item.attachment_id, item.filename || item.name || '');
|
||||
}
|
||||
return imageMarkup(item.url, item.attachment_id, item.name || '');
|
||||
var id = item.attachment_id || item.id;
|
||||
if (type === 'video') return videoMarkup(item.url, id, item.filename || item.name || '');
|
||||
if (type === 'file') return fileMarkup(item.url, id, item.filename || item.name || '');
|
||||
return imageMarkup(item.large_url || item.url, id, item.name || item.title || '', item.url);
|
||||
}
|
||||
|
||||
function createMediaModal(editor, type) {
|
||||
closeMediaModal();
|
||||
function formatBytes(value) {
|
||||
var size = Number(value) || 0, units = ['B', 'KB', 'MB', 'GB'], index = 0;
|
||||
if (!size) return '';
|
||||
while (size >= 1024 && index < units.length - 1) { size /= 1024; index += 1; }
|
||||
return (index ? size.toFixed(size >= 10 ? 0 : 1) : String(Math.round(size))) + ' ' + units[index];
|
||||
}
|
||||
|
||||
var definition = mediaDefinition(type);
|
||||
var canUpload = definition.canUpload;
|
||||
var firstTab = canUpload ? 'upload' : 'external';
|
||||
function extension(item) {
|
||||
var name = String(item.filename || item.name || item.url || ''), match = name.match(/\.([a-z0-9]{1,8})(?:[?#].*)?$/i);
|
||||
return match ? match[1].toUpperCase() : String(item.subtype || item.type || '').toUpperCase();
|
||||
}
|
||||
|
||||
function closeMediaModal(force) {
|
||||
if (!activeModal) return;
|
||||
if (activeModal.uploading && !force) { notify(i18n.uploadingClose || '上传中,请稍候再关闭', 'warning'); return; }
|
||||
document.removeEventListener('keydown', activeModal.onKeydown);
|
||||
if (activeModal.searchTimer) window.clearTimeout(activeModal.searchTimer);
|
||||
activeModal.root.remove();
|
||||
if (activeModal.previousFocus && typeof activeModal.previousFocus.focus === 'function') activeModal.previousFocus.focus();
|
||||
activeModal = null;
|
||||
document.body.classList.remove('aksrt-editor-media-open');
|
||||
}
|
||||
|
||||
function openMediaModal(options) {
|
||||
options = options || {};
|
||||
if (activeModal) {
|
||||
closeMediaModal();
|
||||
if (activeModal) return;
|
||||
}
|
||||
var type = ['image', 'video', 'file'].indexOf(options.type) === -1 ? 'image' : options.type;
|
||||
var definition = mediaDefinition(type), multiple = options.multiple === undefined ? definition.multiple : !!options.multiple;
|
||||
var maxItems = Math.max(1, Number(options.maxItems || (multiple ? definition.maxItems : 1)) || 1);
|
||||
if (!multiple) maxItems = 1;
|
||||
var allowExternal = options.allowExternal !== false;
|
||||
var allowEmbed = definition.canEmbed && options.allowEmbed !== false;
|
||||
var canUpload = definition.canUpload && options.canUpload !== false;
|
||||
var root = document.createElement('div');
|
||||
root.className = 'aksrt-editor-media';
|
||||
root.setAttribute('data-editor-media-type', type);
|
||||
root.setAttribute('role', 'dialog');
|
||||
root.setAttribute('aria-modal', 'true');
|
||||
root.setAttribute('aria-labelledby', 'aksrt-editor-media-title');
|
||||
root.setAttribute('role', 'dialog'); root.setAttribute('aria-modal', 'true'); root.setAttribute('aria-labelledby', 'aksrt-editor-media-title');
|
||||
root.innerHTML =
|
||||
'<button type="button" class="aksrt-editor-media__backdrop" data-editor-media-close tabindex="-1" aria-label="' +
|
||||
escapeAttr(i18n.close || '关闭') + '"></button>' +
|
||||
'<div class="aksrt-editor-media__dialog" tabindex="-1">' +
|
||||
'<button type="button" class="aksrt-editor-media__close" data-editor-media-close aria-label="' +
|
||||
escapeAttr(i18n.close || '关闭') + '">×</button>' +
|
||||
'<h3 id="aksrt-editor-media-title" class="aksrt-editor-media__title">' +
|
||||
escapeAttr(definition.title) + '</h3>' +
|
||||
'<div class="aksrt-editor-media__tabs" role="tablist">' +
|
||||
(canUpload
|
||||
? '<button type="button" class="is-active" role="tab" aria-selected="true" data-editor-media-tab="upload">' +
|
||||
escapeAttr(definition.uploadTab) + '</button>'
|
||||
: '') +
|
||||
'<button type="button" class="' + (firstTab === 'external' ? 'is-active' : '') + '" role="tab" aria-selected="' +
|
||||
(canUpload ? 'false' : 'true') + '" data-editor-media-tab="external">' +
|
||||
escapeAttr(definition.externalTab) + '</button>' +
|
||||
(definition.canEmbed
|
||||
? '<button type="button" role="tab" aria-selected="false" data-editor-media-tab="embed">' +
|
||||
escapeAttr(definition.embedTab) + '</button>'
|
||||
: '') +
|
||||
'</div>' +
|
||||
'<div class="aksrt-editor-media__panels">' +
|
||||
(canUpload
|
||||
? '<section class="aksrt-editor-media__panel is-active" data-editor-media-panel="upload">' +
|
||||
'<label class="aksrt-editor-media__drop">' +
|
||||
'<input type="file" accept="' + escapeAttr(definition.accept) + '"' +
|
||||
(definition.multiple ? ' multiple' : '') + ' data-editor-media-files>' +
|
||||
'<i class="fa fas fa-cloud-upload-alt" aria-hidden="true"></i>' +
|
||||
'<strong>' + escapeAttr(definition.select) + '</strong>' +
|
||||
'<span>' + escapeAttr(definition.hint) + '</span>' +
|
||||
'</label>' +
|
||||
'<div class="aksrt-editor-media__selection" data-editor-media-selection></div>' +
|
||||
'<button type="button" class="but c-blue aksrt-editor-media__submit" data-editor-media-upload disabled>' +
|
||||
escapeAttr(i18n.confirmUpload || '确认上传') + '</button>' +
|
||||
'</section>'
|
||||
: '') +
|
||||
'<section class="aksrt-editor-media__panel ' + (firstTab === 'external' ? 'is-active' : '') + '" data-editor-media-panel="external">' +
|
||||
'<p>' + escapeAttr(definition.externalHint) + '</p>' +
|
||||
'<textarea class="form-control" rows="5" placeholder="https://..." data-editor-media-urls></textarea>' +
|
||||
'<button type="button" class="but c-blue aksrt-editor-media__submit" data-editor-media-external>' +
|
||||
escapeAttr(i18n.confirmInsert || '确认插入') + '</button>' +
|
||||
'</section>' +
|
||||
(definition.canEmbed
|
||||
? '<section class="aksrt-editor-media__panel" data-editor-media-panel="embed">' +
|
||||
'<p>' + escapeAttr(i18n.embedVideoHint || '请输入嵌入地址或者直接粘贴 iframe 嵌入代码:') + '</p>' +
|
||||
'<textarea class="form-control" rows="5" placeholder="<iframe src="https://..."></iframe>" data-editor-media-embed></textarea>' +
|
||||
'<button type="button" class="but c-blue aksrt-editor-media__submit" data-editor-media-embed-submit>' +
|
||||
escapeAttr(i18n.confirmEmbed || '确认嵌入') + '</button>' +
|
||||
'</section>'
|
||||
: '') +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
'<button type="button" class="aksrt-editor-media__backdrop" data-editor-media-close tabindex="-1" aria-label="' + escapeAttr(i18n.close || '关闭') + '"></button>' +
|
||||
'<div class="aksrt-editor-media__dialog" tabindex="-1"><button type="button" class="aksrt-editor-media__close" data-editor-media-close aria-label="' + escapeAttr(i18n.close || '关闭') + '">×</button>' +
|
||||
'<h3 id="aksrt-editor-media-title" class="aksrt-editor-media__title">' + escapeAttr(options.title || definition.title) + '</h3>' +
|
||||
'<div class="aksrt-editor-media__tabs" role="tablist"><button type="button" class="is-active" role="tab" aria-selected="true" data-editor-media-tab="mine">' + escapeAttr(definition.mineTab) + '</button>' +
|
||||
(canUpload ? '<button type="button" role="tab" aria-selected="false" data-editor-media-tab="upload">' + escapeAttr(definition.uploadTab) + '</button>' : '') +
|
||||
(allowExternal ? '<button type="button" role="tab" aria-selected="false" data-editor-media-tab="external">' + escapeAttr(definition.externalTab) + '</button>' : '') +
|
||||
(allowEmbed && type === 'video' ? '<button type="button" role="tab" aria-selected="false" data-editor-media-tab="embed">' + escapeAttr(definition.embedTab) + '</button>' : '') + '</div>' +
|
||||
'<div class="aksrt-editor-media__panels"><section class="aksrt-editor-media__panel is-active" data-editor-media-panel="mine">' +
|
||||
'<div class="aksrt-editor-media__search"><label class="screen-reader-text" for="aksrt-editor-media-search">' + escapeAttr(i18n.search || '搜索') + '</label><input id="aksrt-editor-media-search" type="search" class="form-control" placeholder="' + escapeAttr(i18n.searchMedia || '搜索媒体(至少 2 个字符)') + '" data-editor-media-search><button type="button" class="but hollow" data-editor-media-clear>' + escapeAttr(i18n.clear || '清除') + '</button></div>' +
|
||||
'<div class="aksrt-editor-media__status" data-editor-media-status aria-live="polite"></div><div class="aksrt-editor-media__list" data-editor-media-list></div><div class="aksrt-editor-media__mine-actions"><button type="button" class="but hollow aksrt-editor-media__load-more" data-editor-media-more hidden>' + escapeAttr(i18n.loadMore || '加载更多') + '</button><button type="button" class="but c-blue aksrt-editor-media__confirm" data-editor-media-confirm hidden>' + escapeAttr(i18n.confirmInsert || '确认插入') + '</button></div></section>' +
|
||||
(canUpload ? '<section class="aksrt-editor-media__panel" data-editor-media-panel="upload"><label class="aksrt-editor-media__drop"><input type="file" accept="' + escapeAttr(definition.accept) + '"' + (multiple ? ' multiple' : '') + ' data-editor-media-files><i class="fa fas fa-cloud-upload-alt" aria-hidden="true"></i><strong>' + escapeAttr(definition.select) + '</strong><span>' + escapeAttr(definition.hint) + '</span></label><div class="aksrt-editor-media__selection" data-editor-media-selection></div><div class="aksrt-editor-media__progress" data-editor-media-progress hidden></div><button type="button" class="but c-blue aksrt-editor-media__submit" data-editor-media-upload disabled>' + escapeAttr(i18n.confirmUpload || '确认上传') + '</button></section>' : '') +
|
||||
(allowExternal ? '<section class="aksrt-editor-media__panel" data-editor-media-panel="external"><p>' + escapeAttr(definition.externalHint) + '</p><textarea class="form-control" rows="5" placeholder="https://..." data-editor-media-urls></textarea><button type="button" class="but c-blue aksrt-editor-media__submit" data-editor-media-external>' + escapeAttr(i18n.confirmInsert || '确认插入') + '</button></section>' : '') +
|
||||
(allowEmbed && type === 'video' ? '<section class="aksrt-editor-media__panel" data-editor-media-panel="embed"><p>' + escapeAttr(i18n.embedVideoHint || '请输入嵌入地址或者直接粘贴 iframe 嵌入代码:') + '</p><textarea class="form-control" rows="5" placeholder="<iframe src="https://..."></iframe>" data-editor-media-embed></textarea><button type="button" class="but c-blue aksrt-editor-media__submit" data-editor-media-embed-submit>' + escapeAttr(i18n.confirmEmbed || '确认嵌入') + '</button></section>' : '') + '</div></div>';
|
||||
document.body.appendChild(root); document.body.classList.add('aksrt-editor-media-open');
|
||||
|
||||
document.body.appendChild(root);
|
||||
document.body.classList.add('aksrt-editor-media-open');
|
||||
|
||||
var fileInput = root.querySelector('[data-editor-media-files]');
|
||||
var uploadButton = root.querySelector('[data-editor-media-upload]');
|
||||
var selection = root.querySelector('[data-editor-media-selection]');
|
||||
var drop = root.querySelector('.aksrt-editor-media__drop');
|
||||
var files = [];
|
||||
|
||||
function showSelection() {
|
||||
if (!selection || !uploadButton) {
|
||||
return;
|
||||
var state = { root: root, uploading: false, loading: false, requestId: 0, searchTimer: null, previousFocus: document.activeElement, page: 0, totalPages: 0, search: '', items: [], pinned: [], selected: [], exclude: [] };
|
||||
var list = root.querySelector('[data-editor-media-list]'), status = root.querySelector('[data-editor-media-status]'), more = root.querySelector('[data-editor-media-more]');
|
||||
var confirm = root.querySelector('[data-editor-media-confirm]');
|
||||
var search = root.querySelector('[data-editor-media-search]'), fileInput = root.querySelector('[data-editor-media-files]'), uploadButton = root.querySelector('[data-editor-media-upload]');
|
||||
var selection = root.querySelector('[data-editor-media-selection]'), progress = root.querySelector('[data-editor-media-progress]'), drop = root.querySelector('.aksrt-editor-media__drop'), files = [];
|
||||
function statusText(text, cls) { if (!status) return; status.className = 'aksrt-editor-media__status' + (cls ? ' is-' + cls : ''); status.textContent = text || ''; }
|
||||
function itemId(item) { return Number(item.attachment_id || item.id || 0); }
|
||||
function selectedIndex(id) { return state.selected.findIndex(function (item) { return itemId(item) === id; }); }
|
||||
function renderSelection() { if (selection) selection.textContent = files.length ? (multiple ? (i18n.selectedFiles || '已选择 %d 个文件').replace('%d', String(files.length)) : files[0].name) : ''; if (uploadButton) uploadButton.disabled = !files.length || state.uploading; }
|
||||
function renderItem(item) {
|
||||
var id = itemId(item), index = selectedIndex(id), chosen = index !== -1, disabled = !chosen && state.selected.length >= maxItems;
|
||||
var label = escapeAttr(item.filename || item.name || item.title || item.url || '');
|
||||
var itemType = String(item.type || type);
|
||||
var hasImagePreview = itemType === 'image' && (item.thumbnail_url || item.medium_url || item.url);
|
||||
var thumb = hasImagePreview
|
||||
? '<img src="' + escapeAttr(item.thumbnail_url || item.medium_url || item.url || '') + '" alt="' + label + '">'
|
||||
: '<span class="aksrt-editor-media__file-icon"><i class="fa fas fa-' + (itemType === 'video' ? 'video' : 'file-alt') + '" aria-hidden="true"></i></span>';
|
||||
var meta = type === 'image' ? label : label + (extension(item) ? ' · ' + escapeAttr(extension(item)) : '') + (formatBytes(item.filesizeInBytes) ? ' · ' + escapeAttr(formatBytes(item.filesizeInBytes)) : '');
|
||||
return '<button type="button" class="aksrt-editor-media__item' + (chosen ? ' is-selected' : '') + '" data-editor-media-item="' + id + '"' + (disabled ? ' disabled' : '') + ' aria-pressed="' + (chosen ? 'true' : 'false') + '"><span class="aksrt-editor-media__check">' + (chosen ? String(index + 1) : '<i class="fa fas fa-check" aria-hidden="true"></i>') + '</span><span class="aksrt-editor-media__thumb">' + thumb + '</span><span class="aksrt-editor-media__meta">' + meta + '</span></button>';
|
||||
}
|
||||
function renderList() {
|
||||
if (!list) return;
|
||||
list.innerHTML = state.items.length ? state.items.map(renderItem).join('') : '';
|
||||
if (more) more.hidden = state.loading || state.page >= state.totalPages || !state.items.length;
|
||||
if (confirm) {
|
||||
confirm.hidden = !multiple || !state.selected.length;
|
||||
confirm.disabled = state.uploading;
|
||||
confirm.textContent = (i18n.confirmSelected || '确认选择(%d)').replace('%d', String(state.selected.length));
|
||||
}
|
||||
selection.textContent = files.length
|
||||
? (definition.multiple
|
||||
? (i18n.selectedFiles || '已选择 %d 个文件').replace('%d', String(files.length))
|
||||
: files[0].name)
|
||||
: '';
|
||||
uploadButton.disabled = files.length === 0;
|
||||
}
|
||||
function finish(value) { if (state.uploading) return; if (typeof options.onSelect === 'function') options.onSelect(multiple ? value.slice() : value[0]); closeMediaModal(true); }
|
||||
function selectItem(item) { var id = itemId(item), index = selectedIndex(id); if (index !== -1) state.selected.splice(index, 1); else { if (!multiple) state.selected = []; if (state.selected.length >= maxItems) return; state.selected.push(item); } renderList(); if (!multiple && state.selected.length) finish(state.selected); }
|
||||
function addItems(items) { (items || []).forEach(function (item) { var id = itemId(item); if (!id) return; if (state.exclude.indexOf(id) === -1) state.exclude.push(id); if (!state.items.some(function (old) { return itemId(old) === id; })) state.items.unshift(item); if (!state.pinned.some(function (old) { return itemId(old) === id; })) state.pinned.unshift(item); }); renderList(); }
|
||||
function activateTab(name) { var tab = root.querySelector('[data-editor-media-tab="' + name + '"]'); if (tab) tab.click(); }
|
||||
function request(page, replace) {
|
||||
var url = mediaUrl(type); if (!url) { statusText(i18n.mediaUnavailable || '媒体库暂不可用', 'error'); return; }
|
||||
if (replace) { state.items = state.search.length >= 2 ? [] : state.pinned.slice(); state.page = 0; }
|
||||
state.loading = true; renderList(); statusText(i18n.loading || '加载中…', 'loading');
|
||||
var requestId = ++state.requestId;
|
||||
var params = new URLSearchParams(); params.set('paged', String(page)); params.set('per_page', '48'); if (currentPostId()) params.set('post_id', String(currentPostId())); if (state.search.length >= 2) params.set('search', state.search); if (state.exclude.length) params.set('exclude', state.exclude.join(','));
|
||||
fetch(url + (url.indexOf('?') === -1 ? '?' : '&') + params.toString(), { credentials: 'same-origin', headers: { 'X-WP-Nonce': cfg.restNonce || '' } }).then(function (response) { return response.json().catch(function () { return {}; }).then(function (payload) { if (!response.ok) throw new Error((payload && (payload.message || (payload.data && payload.data.message))) || i18n.error || '加载失败'); return payload || {}; }); }).then(function (payload) {
|
||||
if (requestId !== state.requestId) return;
|
||||
var incoming = Array.isArray(payload.items) ? payload.items : []; if (replace) state.items = state.search.length >= 2 ? [] : state.pinned.slice(); incoming.forEach(function (item) { if (state.exclude.indexOf(itemId(item)) === -1) state.items.push(item); }); state.page = Number(payload.page || page); state.totalPages = Number(payload.total_pages || 0); state.loading = false; renderList(); statusText(state.items.length ? '' : (i18n.emptyMedia || '暂无媒体文件'), state.items.length ? '' : 'empty');
|
||||
}).catch(function (error) { if (requestId !== state.requestId) return; state.loading = false; renderList(); statusText(error.message || i18n.mediaError || '媒体加载失败', 'error'); });
|
||||
}
|
||||
|
||||
function setFiles(nextFiles) {
|
||||
var candidates = Array.prototype.slice.call(nextFiles || []);
|
||||
var uploadKey = type === 'file' ? 'resource' : type;
|
||||
var upload = (cfg.uploads || {})[uploadKey] || {};
|
||||
var rejected = false;
|
||||
files = candidates.filter(function (file) {
|
||||
return acceptsFile(file, type);
|
||||
var valid = acceptsFile(file, type) && (!upload.maxSize || file.size <= upload.maxSize);
|
||||
rejected = rejected || !valid;
|
||||
return valid;
|
||||
});
|
||||
if (candidates.length && !files.length) {
|
||||
notify(i18n.invalidFile || '请选择有效文件', 'warning');
|
||||
if (rejected) notify(i18n.invalidFile || i18n.fileTooLarge || '部分文件类型或大小不符合要求', 'warning');
|
||||
if (!multiple) files = files.slice(0, 1);
|
||||
if (files.length > maxItems) {
|
||||
files = files.slice(0, maxItems);
|
||||
notify((i18n.maxMediaItems || '最多选择 %d 个文件').replace('%d', String(maxItems)), 'warning');
|
||||
}
|
||||
if (!definition.multiple && files.length > 1) {
|
||||
files = files.slice(0, 1);
|
||||
}
|
||||
showSelection();
|
||||
renderSelection();
|
||||
}
|
||||
function uploadSelected() {
|
||||
if (!files.length || state.uploading) return;
|
||||
state.uploading = true; renderSelection(); renderList();
|
||||
if (uploadButton) uploadButton.textContent = i18n.uploading || '正在上传…';
|
||||
if (progress) { progress.hidden = false; progress.textContent = i18n.uploading || '正在上传…'; progress.style.setProperty('--aksrt-upload-progress', '0%'); }
|
||||
var complete = 0, total = files.length, nextIndex = 0, results = [];
|
||||
var toastId = 'aksrt-front-submit-editor-media-toast';
|
||||
notify(i18n.uploading || '正在上传…', 'load', '', toastId);
|
||||
function worker() {
|
||||
var index = nextIndex++;
|
||||
if (index >= total) return Promise.resolve();
|
||||
return uploadMedia(files[index], type).then(function (item) {
|
||||
results[index] = { item: item };
|
||||
}).catch(function (error) {
|
||||
results[index] = { error: error };
|
||||
}).finally(function () {
|
||||
complete += 1;
|
||||
if (progress) progress.style.setProperty('--aksrt-upload-progress', Math.round((complete / total) * 100) + '%');
|
||||
}).then(worker);
|
||||
}
|
||||
var workers = Math.min(4, total);
|
||||
Promise.all(Array.apply(null, Array(workers)).map(function () { return worker(); })).then(function () {
|
||||
var items = results.map(function (result) { return result && result.item; }).filter(Boolean);
|
||||
var failure = results.find(function (result) { return result && result.error; });
|
||||
addItems(items);
|
||||
state.selected = items.slice(0, maxItems);
|
||||
state.uploading = false;
|
||||
renderList();
|
||||
files = [];
|
||||
renderSelection();
|
||||
if (items.length) notify(i18n.uploaded || '上传成功', 'success', 5, toastId);
|
||||
if (failure) notify(failure.error.message || i18n.error || '部分文件上传失败', 'danger', 5, toastId);
|
||||
if (!items.length) return;
|
||||
if (!multiple) finish(state.selected);
|
||||
else activateTab('mine');
|
||||
}).finally(function () {
|
||||
state.uploading = false;
|
||||
renderList();
|
||||
if (uploadButton) { uploadButton.disabled = !files.length; uploadButton.textContent = i18n.confirmUpload || '确认上传'; }
|
||||
if (progress) progress.hidden = true;
|
||||
});
|
||||
}
|
||||
function externalSelect() { var textarea = root.querySelector('[data-editor-media-urls]'), urls = String(textarea ? textarea.value : '').split(/\r?\n/).map(function (url) { var valid = validHttpUrl(url); return valid ? { url: valid } : null; }).filter(Boolean).slice(0, maxItems); if (!urls.length) { notify(i18n.invalidMediaUrl || '请填写有效地址', 'warning'); return; } finish(urls); }
|
||||
function embedSelect() { var input = root.querySelector('[data-editor-media-embed]'), html = embedVideoMarkup(input ? input.value : ''); if (!html) { notify(i18n.invalidVideoUrl || '请填写有效的视频嵌入地址', 'warning'); return; } if (typeof options.onEmbed === 'function') options.onEmbed(html); else if (typeof options.onSelect === 'function') options.onSelect({ embed: html }); closeMediaModal(true); }
|
||||
|
||||
root.addEventListener('click', function (event) {
|
||||
var close = event.target.closest('[data-editor-media-close]');
|
||||
if (close) {
|
||||
event.preventDefault();
|
||||
closeMediaModal();
|
||||
return;
|
||||
}
|
||||
|
||||
var tab = event.target.closest('[data-editor-media-tab]');
|
||||
if (tab) {
|
||||
var name = tab.getAttribute('data-editor-media-tab');
|
||||
root.querySelectorAll('[data-editor-media-tab]').forEach(function (item) {
|
||||
var active = item === tab;
|
||||
item.classList.toggle('is-active', active);
|
||||
item.setAttribute('aria-selected', active ? 'true' : 'false');
|
||||
});
|
||||
root.querySelectorAll('[data-editor-media-panel]').forEach(function (panel) {
|
||||
panel.classList.toggle('is-active', panel.getAttribute('data-editor-media-panel') === name);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.target.closest('[data-editor-media-external]')) {
|
||||
var textarea = root.querySelector('[data-editor-media-urls]');
|
||||
var urls = String(textarea ? textarea.value : '').split(/\r?\n/);
|
||||
if (!definition.multiple) {
|
||||
urls = urls.slice(0, 1);
|
||||
}
|
||||
var html = urls.map(function (url) {
|
||||
return mediaMarkup(type, { url: url });
|
||||
}).join('');
|
||||
if (!html) {
|
||||
notify(i18n.invalidMediaUrl || '请填写有效地址', 'warning');
|
||||
return;
|
||||
}
|
||||
editor.insertContent(html + '<p></p>');
|
||||
editor.nodeChanged();
|
||||
closeMediaModal();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.target.closest('[data-editor-media-embed-submit]')) {
|
||||
var embedInput = root.querySelector('[data-editor-media-embed]');
|
||||
var embedHtml = embedVideoMarkup(embedInput ? embedInput.value : '');
|
||||
if (!embedHtml) {
|
||||
notify(i18n.invalidVideoUrl || '请填写有效的视频嵌入地址', 'warning');
|
||||
return;
|
||||
}
|
||||
editor.insertContent(embedHtml + '<p></p>');
|
||||
editor.nodeChanged();
|
||||
closeMediaModal();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.target.closest('[data-editor-media-upload]')) {
|
||||
if (!files.length || !uploadButton) {
|
||||
return;
|
||||
}
|
||||
uploadButton.disabled = true;
|
||||
uploadButton.textContent = i18n.uploading || '正在上传…';
|
||||
notify(i18n.uploading || '正在上传…', 'load', '');
|
||||
Promise.all(files.map(function (file) {
|
||||
return uploadMedia(file, type);
|
||||
})).then(function (items) {
|
||||
var html = items.map(function (item) {
|
||||
return mediaMarkup(type, item);
|
||||
}).join('');
|
||||
if (!html) {
|
||||
throw new Error(i18n.error || '文件上传失败');
|
||||
}
|
||||
editor.insertContent(html + '<p></p>');
|
||||
editor.nodeChanged();
|
||||
notify(i18n.uploaded || '上传成功', 'success');
|
||||
closeMediaModal();
|
||||
}).catch(function (error) {
|
||||
notify(error.message || i18n.error || '文件上传失败', 'danger');
|
||||
uploadButton.disabled = false;
|
||||
uploadButton.textContent = i18n.confirmUpload || '确认上传';
|
||||
});
|
||||
}
|
||||
var close = event.target.closest('[data-editor-media-close]'); if (close) { event.preventDefault(); closeMediaModal(); return; }
|
||||
var tab = event.target.closest('[data-editor-media-tab]'); if (tab) { var name = tab.getAttribute('data-editor-media-tab'); root.querySelectorAll('[data-editor-media-tab]').forEach(function (button) { var active = button === tab; button.classList.toggle('is-active', active); button.setAttribute('aria-selected', active ? 'true' : 'false'); }); root.querySelectorAll('[data-editor-media-panel]').forEach(function (panel) { panel.classList.toggle('is-active', panel.getAttribute('data-editor-media-panel') === name); }); if (name === 'mine' && state.page === 0) request(1, true); return; }
|
||||
var itemButton = event.target.closest('[data-editor-media-item]'); if (itemButton && !itemButton.disabled) { var item = state.items.find(function (entry) { return itemId(entry) === Number(itemButton.getAttribute('data-editor-media-item')); }); if (item) selectItem(item); return; }
|
||||
if (event.target.closest('[data-editor-media-clear]')) { if (search) search.value = ''; window.clearTimeout(state.searchTimer); state.search = ''; request(1, true); return; }
|
||||
if (event.target.closest('[data-editor-media-confirm]')) { if (state.selected.length) finish(state.selected); return; }
|
||||
if (event.target.closest('[data-editor-media-more]')) { if (!state.loading) request(state.page + 1, false); return; }
|
||||
if (event.target.closest('[data-editor-media-external]')) { externalSelect(); return; }
|
||||
if (event.target.closest('[data-editor-media-embed-submit]')) { embedSelect(); return; }
|
||||
if (event.target.closest('[data-editor-media-upload]')) uploadSelected();
|
||||
});
|
||||
|
||||
if (fileInput) {
|
||||
fileInput.addEventListener('change', function () {
|
||||
setFiles(fileInput.files);
|
||||
});
|
||||
}
|
||||
|
||||
if (drop) {
|
||||
['dragenter', 'dragover'].forEach(function (name) {
|
||||
drop.addEventListener(name, function (event) {
|
||||
event.preventDefault();
|
||||
drop.classList.add('is-dragging');
|
||||
});
|
||||
});
|
||||
['dragleave', 'drop'].forEach(function (name) {
|
||||
drop.addEventListener(name, function (event) {
|
||||
event.preventDefault();
|
||||
drop.classList.remove('is-dragging');
|
||||
});
|
||||
});
|
||||
drop.addEventListener('drop', function (event) {
|
||||
setFiles(event.dataTransfer && event.dataTransfer.files);
|
||||
});
|
||||
}
|
||||
|
||||
var onKeydown = function (event) {
|
||||
if (event.key === 'Escape') {
|
||||
closeMediaModal();
|
||||
}
|
||||
};
|
||||
activeModal = { root: root, onKeydown: onKeydown };
|
||||
document.addEventListener('keydown', onKeydown);
|
||||
var focusTarget = root.querySelector('.aksrt-editor-media__dialog');
|
||||
if (focusTarget) {
|
||||
focusTarget.focus({ preventScroll: true });
|
||||
}
|
||||
if (search) search.addEventListener('input', function () {
|
||||
state.search = String(search.value || '').trim();
|
||||
window.clearTimeout(state.searchTimer);
|
||||
state.searchTimer = window.setTimeout(function () {
|
||||
if (state.search.length === 1) {
|
||||
state.items = [];
|
||||
state.page = 0;
|
||||
state.totalPages = 0;
|
||||
state.loading = false;
|
||||
renderList();
|
||||
statusText(i18n.searchMin || '请输入至少 2 个字符进行搜索', 'empty');
|
||||
return;
|
||||
}
|
||||
request(1, true);
|
||||
}, 600);
|
||||
});
|
||||
if (fileInput) fileInput.addEventListener('change', function () { setFiles(fileInput.files); });
|
||||
if (drop) { ['dragenter', 'dragover'].forEach(function (name) { drop.addEventListener(name, function (event) { event.preventDefault(); drop.classList.add('is-dragging'); }); }); ['dragleave', 'drop'].forEach(function (name) { drop.addEventListener(name, function (event) { event.preventDefault(); drop.classList.remove('is-dragging'); }); }); drop.addEventListener('drop', function (event) { setFiles(event.dataTransfer && event.dataTransfer.files); }); }
|
||||
var onKeydown = function (event) { if (event.key === 'Escape') closeMediaModal(); }; state.onKeydown = onKeydown; activeModal = state; document.addEventListener('keydown', onKeydown);
|
||||
var focusTarget = root.querySelector('.aksrt-editor-media__dialog'); if (focusTarget) focusTarget.focus({ preventScroll: true }); request(1, true);
|
||||
}
|
||||
|
||||
window.AksrtSubmitMedia = { open: openMediaModal, close: function () { closeMediaModal(); }, upload: uploadMedia };
|
||||
|
||||
function selectedContent(editor) {
|
||||
var content = String(editor.selection.getContent() || '').trim();
|
||||
return content ? '<p>' + content + '</p>' : '<p>' + escapeAttr(i18n.hiddenPlaceholder || '隐藏内容') + '</p>';
|
||||
@@ -623,109 +565,154 @@
|
||||
});
|
||||
}
|
||||
|
||||
window.tinymce.PluginManager.add('aksrt_editor_tools', function (editor) {
|
||||
bindCharacterCount(editor);
|
||||
|
||||
if (editorCfg.canUploadImage) {
|
||||
editor.addButton('aksrt_image', {
|
||||
text: '',
|
||||
icon: 'image',
|
||||
tooltip: i18n.insertImage || '插入图片',
|
||||
onclick: function () {
|
||||
createMediaModal(editor, 'image');
|
||||
},
|
||||
});
|
||||
function registerEditorTools() {
|
||||
if (!window.tinymce || !window.tinymce.PluginManager || window.aksrtSubmitEditorToolsRegistered) {
|
||||
return false;
|
||||
}
|
||||
window.aksrtSubmitEditorToolsRegistered = true;
|
||||
|
||||
editor.addButton('aksrt_video', {
|
||||
text: '',
|
||||
icon: 'media',
|
||||
tooltip: i18n.insertVideo || '插入视频',
|
||||
onclick: function () {
|
||||
createMediaModal(editor, 'video');
|
||||
},
|
||||
});
|
||||
window.tinymce.PluginManager.add('aksrt_editor_tools', function (editor) {
|
||||
bindCharacterCount(editor);
|
||||
|
||||
if (editorCfg.canUploadFile) {
|
||||
editor.addButton('aksrt_file', {
|
||||
text: '',
|
||||
icon: 'upload',
|
||||
tooltip: i18n.insertFile || '上传附件',
|
||||
onclick: function () {
|
||||
createMediaModal(editor, 'file');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
editor.addButton('aksrt_quote', {
|
||||
text: '',
|
||||
icon: 'blockquote',
|
||||
tooltip: i18n.quote || '引言',
|
||||
type: 'menubutton',
|
||||
stateSelector: '.quote_q',
|
||||
menu: [
|
||||
{ text: i18n.quoteGray || '灰色', onclick: function () { insertQuote(editor, ''); } },
|
||||
{ text: i18n.quoteRed || '红色', onclick: function () { insertQuote(editor, 'qe_wzk_c-red'); } },
|
||||
{ text: i18n.quoteBlue || '蓝色', onclick: function () { insertQuote(editor, 'qe_wzk_lan'); } },
|
||||
{ text: i18n.quoteGreen || '绿色', onclick: function () { insertQuote(editor, 'qe_wzk_lv'); } },
|
||||
],
|
||||
});
|
||||
|
||||
editor.addButton('aksrt_precode', {
|
||||
text: '',
|
||||
icon: 'code',
|
||||
tooltip: i18n.highlightCode || '高亮代码',
|
||||
stateSelector: 'pre.enlighter-pre',
|
||||
onclick: function () {
|
||||
openCodeModal(editor);
|
||||
},
|
||||
});
|
||||
|
||||
if (editorCfg.canHide) {
|
||||
var menu = [
|
||||
{
|
||||
text: i18n.replyVisible || '回复可见',
|
||||
type: 'reply',
|
||||
open: '[reply]',
|
||||
close: '[/reply]',
|
||||
},
|
||||
{
|
||||
text: i18n.loginVisible || '登录可见',
|
||||
type: 'login',
|
||||
open: '[aksrt_hide mode="login"]',
|
||||
close: '[/aksrt_hide]',
|
||||
},
|
||||
{
|
||||
text: i18n.vipVisible || 'VIP 可见',
|
||||
type: 'vip',
|
||||
open: '[vip]',
|
||||
close: '[/vip]',
|
||||
},
|
||||
];
|
||||
if (editorCfg.canPay) {
|
||||
menu.push({
|
||||
text: i18n.payVisible || '付费可见',
|
||||
type: 'payshow',
|
||||
open: '[payshow]',
|
||||
close: '[/payshow]',
|
||||
if (editorCfg.canUploadImage) {
|
||||
editor.addButton('aksrt_image', {
|
||||
text: '',
|
||||
icon: 'image',
|
||||
tooltip: i18n.insertImage || '插入图片',
|
||||
onclick: function () {
|
||||
window.AksrtSubmitMedia.open({
|
||||
type: 'image', multiple: true, maxItems: 100,
|
||||
onSelect: function (items) {
|
||||
editor.insertContent(items.map(function (item) { return mediaMarkup('image', item); }).join('') + '<p></p>');
|
||||
editor.nodeChanged();
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
menu = menu.map(function (item) {
|
||||
return {
|
||||
text: item.text,
|
||||
onclick: function () {
|
||||
insertHiddenContent(editor, item);
|
||||
},
|
||||
};
|
||||
});
|
||||
editor.addButton('aksrt_hide', {
|
||||
|
||||
editor.addButton('aksrt_video', {
|
||||
text: '',
|
||||
icon: 'preview',
|
||||
tooltip: i18n.hiddenContent || '隐藏内容',
|
||||
type: 'menubutton',
|
||||
stateSelector: '.tinymce-hide',
|
||||
menu: menu,
|
||||
icon: 'media',
|
||||
tooltip: i18n.insertVideo || '插入视频',
|
||||
onclick: function () {
|
||||
window.AksrtSubmitMedia.open({
|
||||
type: 'video', multiple: false,
|
||||
onSelect: function (item) {
|
||||
editor.insertContent(mediaMarkup('video', item) + '<p></p>');
|
||||
editor.nodeChanged();
|
||||
},
|
||||
onEmbed: function (html) {
|
||||
editor.insertContent(html + '<p></p>');
|
||||
editor.nodeChanged();
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (editorCfg.canUploadFile) {
|
||||
editor.addButton('aksrt_file', {
|
||||
text: '',
|
||||
icon: 'upload',
|
||||
tooltip: i18n.insertFile || '上传附件',
|
||||
onclick: function () {
|
||||
window.AksrtSubmitMedia.open({
|
||||
type: 'file', multiple: false,
|
||||
onSelect: function (item) {
|
||||
editor.insertContent(mediaMarkup('file', item) + '<p></p>');
|
||||
editor.nodeChanged();
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
editor.addButton('aksrt_quote', {
|
||||
text: '',
|
||||
icon: 'blockquote',
|
||||
tooltip: i18n.quote || '引言',
|
||||
type: 'menubutton',
|
||||
stateSelector: '.quote_q',
|
||||
menu: [
|
||||
{ text: i18n.quoteGray || '灰色', onclick: function () { insertQuote(editor, ''); } },
|
||||
{ text: i18n.quoteRed || '红色', onclick: function () { insertQuote(editor, 'qe_wzk_c-red'); } },
|
||||
{ text: i18n.quoteBlue || '蓝色', onclick: function () { insertQuote(editor, 'qe_wzk_lan'); } },
|
||||
{ text: i18n.quoteGreen || '绿色', onclick: function () { insertQuote(editor, 'qe_wzk_lv'); } },
|
||||
],
|
||||
});
|
||||
|
||||
editor.addButton('aksrt_precode', {
|
||||
text: '',
|
||||
icon: 'code',
|
||||
tooltip: i18n.highlightCode || '高亮代码',
|
||||
stateSelector: 'pre.enlighter-pre',
|
||||
onclick: function () {
|
||||
openCodeModal(editor);
|
||||
},
|
||||
});
|
||||
|
||||
if (editorCfg.canHide) {
|
||||
var menu = [
|
||||
{
|
||||
text: i18n.replyVisible || '回复可见',
|
||||
type: 'reply',
|
||||
open: '[reply]',
|
||||
close: '[/reply]',
|
||||
},
|
||||
{
|
||||
text: i18n.loginVisible || '登录可见',
|
||||
type: 'login',
|
||||
open: '[aksrt_hide mode="login"]',
|
||||
close: '[/aksrt_hide]',
|
||||
},
|
||||
{
|
||||
text: i18n.vipVisible || 'VIP 可见',
|
||||
type: 'vip',
|
||||
open: '[vip]',
|
||||
close: '[/vip]',
|
||||
},
|
||||
];
|
||||
if (editorCfg.canPay) {
|
||||
menu.push({
|
||||
text: i18n.payVisible || '付费可见',
|
||||
type: 'payshow',
|
||||
open: '[payshow]',
|
||||
close: '[/payshow]',
|
||||
});
|
||||
}
|
||||
menu = menu.map(function (item) {
|
||||
return {
|
||||
text: item.text,
|
||||
onclick: function () {
|
||||
insertHiddenContent(editor, item);
|
||||
},
|
||||
};
|
||||
});
|
||||
editor.addButton('aksrt_hide', {
|
||||
text: '',
|
||||
icon: 'preview',
|
||||
tooltip: i18n.hiddenContent || '隐藏内容',
|
||||
type: 'menubutton',
|
||||
stateSelector: '.tinymce-hide',
|
||||
menu: menu,
|
||||
});
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
registerEditorTools();
|
||||
if (!window.aksrtSubmitEditorToolsRegistered) {
|
||||
var retryCount = 0;
|
||||
var retryRegistration = function () {
|
||||
if (registerEditorTools()) {
|
||||
return;
|
||||
}
|
||||
retryCount += 1;
|
||||
if (retryCount < 100) {
|
||||
window.setTimeout(retryRegistration, 50);
|
||||
}
|
||||
};
|
||||
retryRegistration();
|
||||
}
|
||||
})(window, document);
|
||||
@@ -6,7 +6,7 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var fields = ['url', 'extract_code', 'copy_key', 'copy_val', 'label', 'class'];
|
||||
var fields = ['url', 'attachment_id', 'extract_code', 'copy_key', 'copy_val', 'label', 'class'];
|
||||
var buttonClasses = [
|
||||
'',
|
||||
'c-red', 'c-yellow', 'c-cyan', 'c-blue', 'c-green', 'c-purple',
|
||||
@@ -96,6 +96,7 @@
|
||||
'<div class="mini-scrollbar scroll-y max-vh7 pay-dawnload-edit-fields">' +
|
||||
'<div class="mb20"><div class="muted-color mb6">' + escapeHtml(i18n.downloadUrl || '下载地址') + '</div>' +
|
||||
'<div class="flex ac pay-dawnload-url-row"><input type="url" class="form-control" data-pay-resource-field="url" placeholder="' + escapeHtml(i18n.enterDownloadUrl || '请输入资源下载地址') + '">' +
|
||||
'<input type="hidden" data-pay-resource-field="attachment_id">' +
|
||||
'<button type="button" class="flex0 ml6 pay-upload-btn but hollow c-blue" data-pay-resource-upload><i class="fa fas fa-upload" aria-hidden="true"></i>' + escapeHtml(i18n.uploadFile || '上传附件') + '</button></div>' +
|
||||
'<div class="px12 muted-3-color mt6">' + escapeHtml(i18n.pasteLinkHint || '支持直接粘贴网盘分享链接,并自动识别提取码') + '</div></div>' +
|
||||
'<div class="mb20"><div class="muted-color mb6">' + escapeHtml(i18n.resourceNote || '资源备注') + '</div>' +
|
||||
@@ -243,7 +244,10 @@
|
||||
}
|
||||
});
|
||||
modal.querySelector('[data-pay-download-submit]').addEventListener('click', saveResource);
|
||||
inputMap.url.addEventListener('input', syncActions);
|
||||
inputMap.url.addEventListener('input', function () {
|
||||
inputMap.attachment_id.value = '';
|
||||
syncActions();
|
||||
});
|
||||
inputMap.url.addEventListener('paste', function (event) {
|
||||
var text = event.clipboardData ? event.clipboardData.getData('text') : '';
|
||||
if (!text) {
|
||||
@@ -260,35 +264,30 @@
|
||||
inputMap.copy_key.value = i18n.extractCode || '提取码';
|
||||
inputMap.copy_val.value = codeMatch[1];
|
||||
}
|
||||
inputMap.attachment_id.value = '';
|
||||
syncActions();
|
||||
});
|
||||
|
||||
var canUpload = !!((cfg.uploads || {}).resource && typeof options.pickUpload === 'function' && typeof options.uploadFile === 'function');
|
||||
uploadButton.hidden = !canUpload;
|
||||
if (canUpload) {
|
||||
uploadButton.addEventListener('click', function () {
|
||||
var toastId = 'aksrt-front-submit-resource-upload-toast';
|
||||
options.pickUpload('resource', '*/*').then(function (file) {
|
||||
if (!file) {
|
||||
return null;
|
||||
}
|
||||
uploadButton.disabled = true;
|
||||
notify(i18n.uploading || '正在上传附件…', 'load', '', toastId);
|
||||
return options.uploadFile('resource', file);
|
||||
}).then(function (file) {
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
inputMap.url.value = file.url || '';
|
||||
var canUseMediaPicker = !!(window.AksrtSubmitMedia && typeof window.AksrtSubmitMedia.open === 'function');
|
||||
uploadButton.hidden = false;
|
||||
uploadButton.addEventListener('click', function () {
|
||||
if (!canUseMediaPicker) {
|
||||
notify(i18n.mediaPickerUnavailable || '媒体选择器加载失败,请刷新页面后重试', 'danger');
|
||||
return;
|
||||
}
|
||||
window.AksrtSubmitMedia.open({
|
||||
type: 'file',
|
||||
multiple: false,
|
||||
allowExternal: false,
|
||||
onSelect: function (item) {
|
||||
if (!item) return;
|
||||
inputMap.url.value = item.url || '';
|
||||
inputMap.attachment_id.value = String(item.attachment_id || item.id || 0);
|
||||
syncActions();
|
||||
notify(i18n.uploaded || '附件上传成功', 'success', 5, toastId);
|
||||
}).catch(function (error) {
|
||||
notify(error.message || i18n.error || '附件上传失败', 'danger', 5, toastId);
|
||||
}).finally(function () {
|
||||
uploadButton.disabled = false;
|
||||
});
|
||||
notify(i18n.uploaded || '附件上传成功', 'success', 5, 'aksrt-front-submit-resource-upload-toast');
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', function (event) {
|
||||
if (!modal.hidden && event.key === 'Escape') {
|
||||
|
||||
+86
-88
@@ -21,6 +21,15 @@
|
||||
return Array.prototype.slice.call((root || document).querySelectorAll(sel));
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value || '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function getEditorContent() {
|
||||
if (window.tinymce) {
|
||||
var ed = window.tinymce.get('post_content');
|
||||
@@ -82,9 +91,10 @@
|
||||
|
||||
init: function () {
|
||||
this.form = document.getElementById('aksrt-submit-form');
|
||||
if (!this.form) {
|
||||
if (!this.form || this.form.getAttribute('data-aksrt-submit-ready') === '1') {
|
||||
return;
|
||||
}
|
||||
this.form.setAttribute('data-aksrt-submit-ready', '1');
|
||||
this.bindDirty();
|
||||
this.bindAutoHeight();
|
||||
this.bindSubmitButtons();
|
||||
@@ -258,19 +268,27 @@
|
||||
if (d.time) {
|
||||
var timeEl = qs('.aksrt-submit-modified-time');
|
||||
if (timeEl) {
|
||||
timeEl.innerHTML =
|
||||
'<span class="badg">' + (i18n.lastSaved || 'Last saved: ') + d.time + '</span>';
|
||||
timeEl.textContent = '';
|
||||
var timeBadge = document.createElement('span');
|
||||
timeBadge.className = 'badg';
|
||||
timeBadge.textContent = (i18n.lastSaved || '最后保存:') + d.time;
|
||||
timeEl.appendChild(timeBadge);
|
||||
}
|
||||
}
|
||||
if (d.url) {
|
||||
var view = qs('.aksrt-submit-view-btn');
|
||||
if (view) {
|
||||
view.innerHTML =
|
||||
'<a class="but c-blue" target="_blank" href="' +
|
||||
d.url +
|
||||
'"><i class="fa fas fa-file-alt"></i> ' +
|
||||
(i18n.preview || 'Preview') +
|
||||
'</a>';
|
||||
view.textContent = '';
|
||||
var previewLink = document.createElement('a');
|
||||
previewLink.className = 'but c-blue';
|
||||
previewLink.target = '_blank';
|
||||
previewLink.rel = 'noopener';
|
||||
previewLink.href = String(d.url);
|
||||
var previewIcon = document.createElement('i');
|
||||
previewIcon.className = 'fa fas fa-file-alt';
|
||||
previewLink.appendChild(previewIcon);
|
||||
previewLink.appendChild(document.createTextNode(' ' + (i18n.preview || 'Preview')));
|
||||
view.appendChild(previewLink);
|
||||
}
|
||||
}
|
||||
notyf(
|
||||
@@ -398,16 +416,16 @@
|
||||
}
|
||||
var html = '';
|
||||
if (t === 'image' && d.url) {
|
||||
html = '<img src="' + d.url + '" alt="">';
|
||||
html = '<img src="' + escapeHtml(d.url) + '" alt="">';
|
||||
} else if (t === 'slide' && Array.isArray(d) && d[0] && d[0].url) {
|
||||
html =
|
||||
'<img src="' +
|
||||
d[0].url +
|
||||
escapeHtml(d[0].url) +
|
||||
'" alt=""><span class="featured-type-badge"><i class="fa fas fa-image"></i></span>';
|
||||
} else if (t === 'video') {
|
||||
html =
|
||||
(d.pic
|
||||
? '<img src="' + d.pic + '" alt="">'
|
||||
? '<img src="' + escapeHtml(d.pic) + '" alt="">'
|
||||
: '<div class="featured-video-placeholder"><i class="fa fas fa-play"></i></div>') +
|
||||
'<span class="featured-type-badge"><i class="fa fas fa-video"></i></span>';
|
||||
}
|
||||
@@ -418,41 +436,13 @@
|
||||
}
|
||||
},
|
||||
|
||||
uploadFile: function (kind, file) {
|
||||
var upload = (cfg.uploads || {})[kind] || null;
|
||||
if (!upload || !upload.url || !file) {
|
||||
return Promise.reject(new Error(i18n.error || 'Upload unavailable'));
|
||||
openMediaPicker: function (options) {
|
||||
if (!window.AksrtSubmitMedia || typeof window.AksrtSubmitMedia.open !== 'function') {
|
||||
notyf(i18n.mediaPickerUnavailable || '媒体选择器加载失败,请刷新页面后重试', 'danger');
|
||||
return false;
|
||||
}
|
||||
if (upload.maxSize && file.size > upload.maxSize) {
|
||||
return Promise.reject(new Error(i18n.fileTooLarge || '文件大小超过限制'));
|
||||
}
|
||||
var body = new FormData();
|
||||
body.append('file', file);
|
||||
return fetch(upload.url, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'X-WP-Nonce': cfg.restNonce || '' },
|
||||
body: body,
|
||||
}).then(function (response) {
|
||||
return response.json().catch(function () { return {}; }).then(function (payload) {
|
||||
if (!response.ok || !payload || !payload.success) {
|
||||
throw new Error((payload && payload.message) || i18n.error || 'Upload failed');
|
||||
}
|
||||
return payload;
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
pickUpload: function (kind, accept) {
|
||||
return new Promise(function (resolve) {
|
||||
var input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = accept;
|
||||
input.addEventListener('change', function () {
|
||||
resolve(input.files && input.files[0] ? input.files[0] : null);
|
||||
}, { once: true });
|
||||
input.click();
|
||||
});
|
||||
window.AksrtSubmitMedia.open(options);
|
||||
return true;
|
||||
},
|
||||
|
||||
bindFeatured: function () {
|
||||
@@ -473,54 +463,64 @@
|
||||
return;
|
||||
}
|
||||
if (act === 'image') {
|
||||
var imageToastId = 'aksrt-front-submit-featured-upload-toast';
|
||||
self.pickUpload('image', 'image/*').then(function (file) {
|
||||
if (!file) return null;
|
||||
notyf(i18n.uploading || '正在上传封面…', 'load', '', imageToastId);
|
||||
return self.uploadFile('image', file);
|
||||
}).then(function (file) {
|
||||
if (!file) return;
|
||||
self.setFeatured('image', { url: file.url, id: file.attachment_id });
|
||||
notyf(i18n.uploaded || '封面上传成功', 'success', 5, imageToastId);
|
||||
}).catch(function (error) {
|
||||
notyf(error.message || i18n.error || '封面上传失败', 'danger', 5, imageToastId);
|
||||
self.openMediaPicker({
|
||||
type: 'image',
|
||||
multiple: false,
|
||||
allowExternal: false,
|
||||
onSelect: function (item) {
|
||||
if (!item) return;
|
||||
self.setFeatured('image', { url: item.url || '', id: item.attachment_id || item.id || 0 });
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (act === 'slide') {
|
||||
var slideToastId = 'aksrt-front-submit-slide-upload-toast';
|
||||
self.pickUpload('image', 'image/*').then(function (file) {
|
||||
if (!file) return null;
|
||||
notyf(i18n.uploading || '正在上传幻灯片封面…', 'load', '', slideToastId);
|
||||
return self.uploadFile('image', file);
|
||||
}).then(function (file) {
|
||||
if (!file) return;
|
||||
self.setFeatured('slide', [{ url: file.url, id: file.attachment_id }]);
|
||||
notyf(i18n.uploaded || '幻灯片封面上传成功', 'success', 5, slideToastId);
|
||||
}).catch(function (error) {
|
||||
notyf(error.message || i18n.error || '幻灯片封面上传失败', 'danger', 5, slideToastId);
|
||||
self.openMediaPicker({
|
||||
type: 'image',
|
||||
multiple: true,
|
||||
maxItems: 30,
|
||||
allowExternal: false,
|
||||
onSelect: function (items) {
|
||||
var slides = (Array.isArray(items) ? items : []).map(function (item) {
|
||||
return { url: item.url || '', id: item.attachment_id || item.id || 0 };
|
||||
}).filter(function (item) { return item.url || item.id; });
|
||||
if (slides.length) self.setFeatured('slide', slides);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (act === 'video') {
|
||||
var url = window.prompt(i18n.videoUrl || 'Video URL');
|
||||
if (!url) {
|
||||
return;
|
||||
}
|
||||
var videoToastId = 'aksrt-front-submit-video-cover-toast';
|
||||
self.pickUpload('image', 'image/*').then(function (file) {
|
||||
if (!file) {
|
||||
self.setFeatured('video', { url: url, pic: '' });
|
||||
return null;
|
||||
}
|
||||
notyf(i18n.uploading || '正在上传视频封面…', 'load', '', videoToastId);
|
||||
return self.uploadFile('image', file);
|
||||
}).then(function (file) {
|
||||
if (!file) return;
|
||||
self.setFeatured('video', { url: url, pic: file.url });
|
||||
notyf(i18n.uploaded || '视频封面上传成功', 'success', 5, videoToastId);
|
||||
}).catch(function (error) {
|
||||
notyf(error.message || i18n.error || '视频封面上传失败', 'danger', 5, videoToastId);
|
||||
self.openMediaPicker({
|
||||
type: 'video',
|
||||
multiple: false,
|
||||
allowExternal: true,
|
||||
allowEmbed: false,
|
||||
onSelect: function (item) {
|
||||
if (!item || !item.url) return;
|
||||
var video = {
|
||||
url: item.url,
|
||||
pic: '',
|
||||
pic_id: 0,
|
||||
id: item.attachment_id || item.id || 0,
|
||||
};
|
||||
self.setFeatured('video', video);
|
||||
window.setTimeout(function () {
|
||||
self.openMediaPicker({
|
||||
type: 'image',
|
||||
multiple: false,
|
||||
allowExternal: false,
|
||||
title: i18n.pickVideoCover || '选择视频封面(可选)',
|
||||
onSelect: function (cover) {
|
||||
self.setFeatured('video', {
|
||||
url: video.url,
|
||||
pic: cover && cover.url ? cover.url : '',
|
||||
pic_id: cover ? (cover.attachment_id || cover.id || 0) : 0,
|
||||
id: video.id,
|
||||
});
|
||||
},
|
||||
});
|
||||
}, 0);
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -572,8 +572,6 @@
|
||||
|
||||
window.aksrtSubmitPayDownloads.init({
|
||||
root: box,
|
||||
pickUpload: this.pickUpload.bind(this),
|
||||
uploadFile: this.uploadFile.bind(this),
|
||||
notify: notyf,
|
||||
markDirty: function () {
|
||||
App.isDirty = true;
|
||||
|
||||
@@ -1,328 +0,0 @@
|
||||
/**
|
||||
* AKSRT Mini Upload — 小型文件上传器
|
||||
*
|
||||
* 提供拖拽上传、进度显示、预览功能。
|
||||
* 用于前台投稿、商品编辑等需要文件上传的页面。
|
||||
*
|
||||
* @package AKSRT
|
||||
*/
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 初始化小型上传器
|
||||
*
|
||||
* @param {HTMLElement} container 上传器容器
|
||||
* @param {Object} options 配置项
|
||||
*/
|
||||
function MiniUpload(container, options) {
|
||||
if (!container) return;
|
||||
|
||||
this.options = Object.assign({
|
||||
maxFileSize: 5 * 1024 * 1024, // 5MB
|
||||
allowedTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
|
||||
multiple: false,
|
||||
uploadUrl: '',
|
||||
fieldName: 'file',
|
||||
nonce: '',
|
||||
onSelect: null,
|
||||
onSuccess: null,
|
||||
onError: null,
|
||||
}, options || {});
|
||||
|
||||
this.container = container;
|
||||
this.files = [];
|
||||
this.init();
|
||||
}
|
||||
|
||||
MiniUpload.prototype.init = function () {
|
||||
var self = this;
|
||||
|
||||
// 创建文件输入
|
||||
this.input = document.createElement('input');
|
||||
this.input.type = 'file';
|
||||
this.input.accept = this.options.allowedTypes.join(',');
|
||||
this.input.multiple = this.options.multiple;
|
||||
this.input.style.display = 'none';
|
||||
this.container.appendChild(this.input);
|
||||
|
||||
// 创建拖拽区域
|
||||
this.dropzone = document.createElement('div');
|
||||
this.dropzone.className = 'aksrt-mini-upload__dropzone';
|
||||
this.dropzone.innerHTML =
|
||||
'<div class="aksrt-mini-upload__icon"><i class="fa fas fa-cloud-upload-alt"></i></div>' +
|
||||
'<div class="aksrt-mini-upload__text">点击或拖拽文件到此处上传</div>' +
|
||||
'<div class="aksrt-mini-upload__hint">支持 ' + this.options.allowedTypes.map(function (t) {
|
||||
return t.split('/')[1].toUpperCase();
|
||||
}).join(', ') + ',最大 ' + Math.round(this.options.maxFileSize / 1024 / 1024) + 'MB</div>';
|
||||
this.container.appendChild(this.dropzone);
|
||||
|
||||
// 创建预览区域
|
||||
this.preview = document.createElement('div');
|
||||
this.preview.className = 'aksrt-mini-upload__preview';
|
||||
this.container.appendChild(this.preview);
|
||||
|
||||
// 事件绑定
|
||||
this.dropzone.addEventListener('click', function () {
|
||||
self.input.click();
|
||||
});
|
||||
|
||||
this.dropzone.addEventListener('dragover', function (e) {
|
||||
e.preventDefault();
|
||||
self.dropzone.classList.add('aksrt-mini-upload__dropzone--dragover');
|
||||
});
|
||||
|
||||
this.dropzone.addEventListener('dragleave', function () {
|
||||
self.dropzone.classList.remove('aksrt-mini-upload__dropzone--dragover');
|
||||
});
|
||||
|
||||
this.dropzone.addEventListener('drop', function (e) {
|
||||
e.preventDefault();
|
||||
self.dropzone.classList.remove('aksrt-mini-upload__dropzone--dragover');
|
||||
if (e.dataTransfer.files.length > 0) {
|
||||
self.handleFiles(e.dataTransfer.files);
|
||||
}
|
||||
});
|
||||
|
||||
this.input.addEventListener('change', function () {
|
||||
if (self.input.files.length > 0) {
|
||||
self.handleFiles(self.input.files);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
MiniUpload.prototype.handleFiles = function (fileList) {
|
||||
var self = this;
|
||||
var files = Array.prototype.slice.call(fileList);
|
||||
|
||||
files.forEach(function (file) {
|
||||
// 验证文件类型
|
||||
if (self.options.allowedTypes.length > 0 && self.options.allowedTypes.indexOf(file.type) === -1) {
|
||||
self.showError('不支持的文件类型: ' + file.type);
|
||||
return;
|
||||
}
|
||||
|
||||
// 验证文件大小
|
||||
if (file.size > self.options.maxFileSize) {
|
||||
self.showError('文件大小超过限制: ' + Math.round(file.size / 1024 / 1024) + 'MB');
|
||||
return;
|
||||
}
|
||||
|
||||
self.files.push(file);
|
||||
self.addPreview(file);
|
||||
|
||||
if (typeof self.options.onSelect === 'function') {
|
||||
self.options.onSelect(file);
|
||||
}
|
||||
|
||||
// 如果有上传 URL,自动上传
|
||||
if (self.options.uploadUrl) {
|
||||
self.uploadFile(file);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
MiniUpload.prototype.addPreview = function (file) {
|
||||
var self = this;
|
||||
var item = document.createElement('div');
|
||||
item.className = 'aksrt-mini-upload__item';
|
||||
|
||||
if (file.type.startsWith('image/')) {
|
||||
var reader = new FileReader();
|
||||
reader.onload = function (e) {
|
||||
item.innerHTML =
|
||||
'<img src="' + e.target.result + '" class="aksrt-mini-upload__thumb">' +
|
||||
'<div class="aksrt-mini-upload__info">' +
|
||||
'<span class="aksrt-mini-upload__name">' + file.name + '</span>' +
|
||||
'<span class="aksrt-mini-upload__size">' + self.formatSize(file.size) + '</span>' +
|
||||
'</div>' +
|
||||
'<button type="button" class="aksrt-mini-upload__remove"><i class="fa fas fa-times"></i></button>' +
|
||||
'<div class="aksrt-mini-upload__progress"><div class="aksrt-mini-upload__progress-bar"></div></div>';
|
||||
self.bindRemove(item, file);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
} else {
|
||||
item.innerHTML =
|
||||
'<div class="aksrt-mini-upload__file-icon"><i class="fa fas fa-file"></i></div>' +
|
||||
'<div class="aksrt-mini-upload__info">' +
|
||||
'<span class="aksrt-mini-upload__name">' + file.name + '</span>' +
|
||||
'<span class="aksrt-mini-upload__size">' + self.formatSize(file.size) + '</span>' +
|
||||
'</div>' +
|
||||
'<button type="button" class="aksrt-mini-upload__remove"><i class="fa fas fa-times"></i></button>' +
|
||||
'<div class="aksrt-mini-upload__progress"><div class="aksrt-mini-upload__progress-bar"></div></div>';
|
||||
this.bindRemove(item, file);
|
||||
}
|
||||
|
||||
this.preview.appendChild(item);
|
||||
};
|
||||
|
||||
MiniUpload.prototype.bindRemove = function (item, file) {
|
||||
var self = this;
|
||||
var removeBtn = item.querySelector('.aksrt-mini-upload__remove');
|
||||
if (removeBtn) {
|
||||
removeBtn.addEventListener('click', function () {
|
||||
var index = self.files.indexOf(file);
|
||||
if (index > -1) self.files.splice(index, 1);
|
||||
item.remove();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
MiniUpload.prototype.uploadFile = function (file) {
|
||||
var self = this;
|
||||
var formData = new FormData();
|
||||
formData.append(this.options.fieldName, file);
|
||||
|
||||
if (this.options.nonce) {
|
||||
formData.append('_wpnonce', this.options.nonce);
|
||||
}
|
||||
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', this.options.uploadUrl, true);
|
||||
|
||||
// 进度更新
|
||||
var item = this.preview.lastElementChild;
|
||||
var progressBar = item ? item.querySelector('.aksrt-mini-upload__progress-bar') : null;
|
||||
|
||||
xhr.upload.onprogress = function (e) {
|
||||
if (e.lengthComputable && progressBar) {
|
||||
var percent = Math.round((e.loaded / e.total) * 100);
|
||||
progressBar.style.width = percent + '%';
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onload = function () {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
try {
|
||||
var response = JSON.parse(xhr.responseText);
|
||||
if (typeof self.options.onSuccess === 'function') {
|
||||
self.options.onSuccess(response, file);
|
||||
}
|
||||
if (item) item.classList.add('aksrt-mini-upload__item--success');
|
||||
} catch (e) {
|
||||
self.showError('上传响应解析失败');
|
||||
}
|
||||
} else {
|
||||
self.showError('上传失败: HTTP ' + xhr.status);
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onerror = function () {
|
||||
self.showError('网络错误,上传失败');
|
||||
if (item) item.classList.add('aksrt-mini-upload__item--error');
|
||||
};
|
||||
|
||||
xhr.send(formData);
|
||||
};
|
||||
|
||||
MiniUpload.prototype.showError = function (msg) {
|
||||
if (typeof this.options.onError === 'function') {
|
||||
this.options.onError(msg);
|
||||
}
|
||||
console.error('[AKSRT MiniUpload]', msg);
|
||||
};
|
||||
|
||||
MiniUpload.prototype.formatSize = function (bytes) {
|
||||
if (bytes < 1024) return bytes + ' B';
|
||||
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
|
||||
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
|
||||
};
|
||||
|
||||
MiniUpload.prototype.getFiles = function () {
|
||||
return this.files;
|
||||
};
|
||||
|
||||
MiniUpload.prototype.clear = function () {
|
||||
this.files = [];
|
||||
this.preview.innerHTML = '';
|
||||
this.input.value = '';
|
||||
};
|
||||
|
||||
/**
|
||||
* 分片上传大文件
|
||||
* @param {File} file - 要上传的文件
|
||||
* @param {Object} opts - { chunkSize, uploadUrl, fieldName, nonce, onProgress, onComplete, onError }
|
||||
*/
|
||||
MiniUpload.prototype.uploadChunked = function (file, opts) {
|
||||
var chunkSize = (opts.chunkSize || 2) * 1024 * 1024; // default 2MB
|
||||
var totalChunks = Math.ceil(file.size / chunkSize);
|
||||
var currentChunk = 0;
|
||||
var fileId = file.name + '-' + file.size + '-' + file.lastModified;
|
||||
|
||||
function uploadNext() {
|
||||
if (currentChunk >= totalChunks) {
|
||||
if (opts.onComplete) opts.onComplete({ fileId: fileId, totalChunks: totalChunks });
|
||||
return;
|
||||
}
|
||||
|
||||
var start = currentChunk * chunkSize;
|
||||
var end = Math.min(start + chunkSize, file.size);
|
||||
var blob = file.slice(start, end);
|
||||
|
||||
var formData = new FormData();
|
||||
formData.append(opts.fieldName || 'file', blob, file.name);
|
||||
formData.append('chunk', currentChunk);
|
||||
formData.append('total_chunks', totalChunks);
|
||||
formData.append('file_id', fileId);
|
||||
formData.append('file_name', file.name);
|
||||
formData.append('file_size', file.size);
|
||||
if (opts.nonce) formData.append('_ajax_nonce', opts.nonce);
|
||||
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', opts.uploadUrl, true);
|
||||
|
||||
xhr.upload.onprogress = function (e) {
|
||||
if (e.lengthComputable && opts.onProgress) {
|
||||
var chunkProgress = e.loaded / e.total;
|
||||
var totalProgress = (currentChunk + chunkProgress) / totalChunks;
|
||||
opts.onProgress(totalProgress, currentChunk, totalChunks);
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onload = function () {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
currentChunk++;
|
||||
uploadNext();
|
||||
} else {
|
||||
if (opts.onError) opts.onError('上传失败: HTTP ' + xhr.status);
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onerror = function () {
|
||||
if (opts.onError) opts.onError('网络错误');
|
||||
};
|
||||
|
||||
xhr.send(formData);
|
||||
}
|
||||
|
||||
uploadNext();
|
||||
};
|
||||
|
||||
/**
|
||||
* 快速文件标识(替代 spark-md5,用文件名+大小+最后修改时间生成简易 hash)
|
||||
*/
|
||||
MiniUpload.prototype.getFileId = function (file) {
|
||||
return file.name + '-' + file.size + '-' + file.lastModified;
|
||||
};
|
||||
|
||||
// 自动初始化
|
||||
function autoInit() {
|
||||
document.querySelectorAll('[data-aksrt-mini-upload]').forEach(function (el) {
|
||||
if (el.dataset.miniUploadInit) return;
|
||||
el.dataset.miniUploadInit = '1';
|
||||
|
||||
var options = {};
|
||||
try {
|
||||
options = JSON.parse(el.dataset.aksrtMiniUpload || '{}');
|
||||
} catch (e) {}
|
||||
|
||||
new MiniUpload(el, options);
|
||||
});
|
||||
}
|
||||
|
||||
jQuery(document).off('auto_fun.aksrt-mini-upload').on('auto_fun.aksrt-mini-upload', autoInit);
|
||||
|
||||
// 暴露到全局
|
||||
window.AksrtMiniUpload = MiniUpload;
|
||||
})();
|
||||
@@ -446,7 +446,7 @@
|
||||
type: 'string',
|
||||
source: 'attribute',
|
||||
selector: '.file-download-btn',
|
||||
attribute: 'data-download-file',
|
||||
attribute: 'data-aksrt-file-id',
|
||||
default: 0,
|
||||
},
|
||||
url: {
|
||||
@@ -921,7 +921,7 @@
|
||||
href: url,
|
||||
};
|
||||
if (file_id) {
|
||||
a_attr['data-download-file'] = file_id;
|
||||
a_attr['data-aksrt-file-id'] = file_id;
|
||||
}
|
||||
|
||||
var desc_lists = desc.map(function (item) {
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
!function(e,t,a){e(document).ready(function(){console.log(Z("gutenberg_editor_enhanced"));var l=t.blocks,r=t.components,n=t.element,o=t.blockEditor?t.blockEditor:t.editor,i=t.richText.registerFormatType,s=t.data,c=s.dispatch,u=s.select,b=c("core/block-editor")?c("core/block-editor"):c("core/editor"),d=u("core/block-editor")?u("core/block-editor"):u("core/editor"),g=d.getBlockOrder,_=d.getBlock,p=b.insertBlock,m=b.removeBlock,v=b.updateBlockAttributes,h=n.createElement,f=l.registerBlockType,y=l.createBlock,k=o.InnerBlocks,N=o.RichTextToolbarButton,C=n.Component,w=t.dom.getRectangleFromRange,x=r.Popover,z=r.Button,q=o.RichText,M=o.PlainText,j=o.MediaUpload,A=n.Fragment,H=o.InspectorControls,V=r.PanelBody,S=r.ClipboardButton,L=r.TextControl,B=r.RadioControl,T=r.Toolbar,F=r.SelectControl,P=r.ToggleControl,R=r.RangeControl,I=r.DropdownMenu,O=o.BlockControls,E=o.AlignmentToolbar,D=a.lodash||a._,G=a.wpApiSettings,K=D.times,$=D.debounce;function Z(e){var t=a.aksrt_block_var&&a.aksrt_block_var.i18n;return t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:e}function J(e){var t=Array.prototype.slice.call(arguments,1),a=Z(e),l=0;return a.replace(/%(\d+\$)?s/g,function(e,a){var r=a?parseInt(a,10)-1:l++;return void 0!==t[r]&&null!==t[r]?t[r]:e})}var Q={},U="#1fbc45",W=function(e){return{viewBox:e=e||"0 0 1024 1024",className:"svg-icon",xmlns:X}},X="http://www.w3.org/2000/svg";Q.legacy=h("svg",{width:"16px",height:"16px",viewBox:"0 0 80 90",className:"svg-icon mb10",xmlns:X,fillRule:"evenodd",clipRule:"evenodd",strokeLinejoin:"round",strokeMiterlimit:"1.414"},h("g",{fillRule:"nonzero",transform:"scale(0.19785394)"},h("path",{d:"m 408.68862,333.8044 0.009,0.59315 0.004,0.29795 c 0.18694,71.91774 -59.58485,130.93907 -134.53126,132.29044 -0.85543,0.0154 -1.71097,0.0231 -2.56654,0.0231 H 21.034693 C 11.007191,467.00905 2.5761396,460.42672 0.14656613,451.50411 L 338.63176,215.013 c 45.60925,25.97569 68.96153,65.57282 70.05686,118.7914 z M 231.25625,0 C 278.01331,0 321.188,23.909861 344.73248,62.682399 L 0,303.53751 V 20.793975 C 0,9.3097796 9.6674353,0 21.592821,0 Z",fill:U}))),Q.productbox=h("svg",W(),h("path",{d:"M975.36 400.64A88.32 88.32 0 0 0 887.68 320h-57.6c0-176.64-142.72-320-318.08-320-175.36 0-318.08 143.36-318.08 320h-57.6c-45.44 0-83.2 34.56-87.68 80.64l-44.16 446.08c-4.48 45.44 10.24 90.88 40.96 124.8 30.08 33.28 72.96 52.48 118.4 52.48h696.32c45.44 0 88.96-19.2 119.04-53.12 30.08-33.92 45.44-79.36 40.96-124.8l-44.8-445.44zM512 64c140.16 0 254.08 114.56 254.08 256H257.92c0-141.44 113.92-256 254.08-256z m419.84 864c-18.56 20.48-44.16 32-71.68 32H163.84c-27.52 0-53.12-11.52-71.68-32-18.56-20.48-27.52-47.36-24.96-75.52l44.16-446.08c1.28-12.8 12.16-22.4 24.96-22.4h57.6v96c0 17.92 14.08 32 32 32 17.28 0 32-14.08 32-32V384h508.8v96c0 17.92 14.08 32 32 32 17.28 0 32-14.08 32-32V384h57.6c12.8 0 23.68 9.6 24.96 22.4l44.16 446.08c1.92 28.16-7.04 54.4-25.6 75.52z",fill:U}),h("path",{d:"M752 679.04a536.768 536.768 0 0 1-480 0 31.744 31.744 0 0 0-42.88 14.08c-7.68 16-1.28 35.2 14.08 42.88 83.84 42.24 176.64 63.36 268.8 63.36 92.16 0 184.32-21.12 268.8-63.36 16-7.68 21.76-26.88 14.08-42.88a31.744 31.744 0 0 0-42.88-14.08z",fill:U})),Q.video=h("svg",W(),h("path",{d:"M704 874.666667H128c-46.933333 0-85.333333-38.4-85.333333-85.333334V234.666667c0-46.933333 38.4-85.333333 85.333333-85.333334h576c46.933333 0 85.333333 38.4 85.333333 85.333334v554.666666c0 46.933333-38.4 85.333333-85.333333 85.333334zM128 213.333333c-12.8 0-21.333333 8.533333-21.333333 21.333334v554.666666c0 12.8 8.533333 21.333333 21.333333 21.333334h576c12.8 0 21.333333-8.533333 21.333333-21.333334V234.666667c0-12.8-8.533333-21.333333-21.333333-21.333334H128z",fill:U}),h("path",{d:"M277.333333 490.666667c-59.733333 0-106.666667-46.933333-106.666666-106.666667s46.933333-106.666667 106.666666-106.666667 106.666667 46.933333 106.666667 106.666667-46.933333 106.666667-106.666667 106.666667z m0-149.333334c-23.466667 0-42.666667 19.2-42.666666 42.666667s19.2 42.666667 42.666666 42.666667 42.666667-19.2 42.666667-42.666667-19.2-42.666667-42.666667-42.666667zM938.666667 800c-8.533333 0-14.933333-2.133333-21.333334-6.4L725.333333 682.666667V341.333333l192-110.933333c10.666667-6.4 21.333333-6.4 32-4.266667 10.666667 2.133333 21.333333 8.533333 25.6 19.2 4.266667 6.4 6.4 14.933333 6.4 21.333334v490.666666c0 23.466667-19.2 42.666667-42.666666 42.666667z m-149.333334-153.6l128 74.666667V302.933333l-128 74.666667v268.8z",fill:U})),Q.iframe=h("svg",W(),h("path",{d:"M885.76 52.053333h-364.8c-47.786667 0-86.186667 38.826667-86.186667 86.186667v82.346667H139.093333c-48.213333 0-87.466667 39.253333-87.466666 87.04v576.426666c0 48.213333 39.253333 87.466667 87.466666 87.466667h576.426667c48.213333 0 87.04-39.253333 87.04-87.466667v-294.826666h82.773333c47.786667 0 86.186667-38.826667 86.186667-86.186667V138.666667c0.426667-47.786667-37.973333-86.613333-85.76-86.613334z m-151.04 832.426667c0 10.666667-8.533333 19.2-19.2 19.2H139.093333c-10.666667 0-19.2-8.533333-19.2-19.2V308.053333cLine truncated
|
||||
!function(e,t,a){e(document).ready(function(){console.log(Z("gutenberg_editor_enhanced"));var l=t.blocks,r=t.components,n=t.element,o=t.blockEditor?t.blockEditor:t.editor,i=t.richText.registerFormatType,s=t.data,c=s.dispatch,u=s.select,b=c("core/block-editor")?c("core/block-editor"):c("core/editor"),d=u("core/block-editor")?u("core/block-editor"):u("core/editor"),g=d.getBlockOrder,_=d.getBlock,p=b.insertBlock,m=b.removeBlock,v=b.updateBlockAttributes,h=n.createElement,f=l.registerBlockType,y=l.createBlock,k=o.InnerBlocks,N=o.RichTextToolbarButton,C=n.Component,w=t.dom.getRectangleFromRange,x=r.Popover,z=r.Button,q=o.RichText,M=o.PlainText,j=o.MediaUpload,A=n.Fragment,H=o.InspectorControls,V=r.PanelBody,S=r.ClipboardButton,L=r.TextControl,B=r.RadioControl,T=r.Toolbar,F=r.SelectControl,P=r.ToggleControl,R=r.RangeControl,I=r.DropdownMenu,O=o.BlockControls,E=o.AlignmentToolbar,D=a.lodash||a._,G=a.wpApiSettings,K=D.times,$=D.debounce;function Z(e){var t=a.aksrt_block_var&&a.aksrt_block_var.i18n;return t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:e}function J(e){var t=Array.prototype.slice.call(arguments,1),a=Z(e),l=0;return a.replace(/%(\d+\$)?s/g,function(e,a){var r=a?parseInt(a,10)-1:l++;return void 0!==t[r]&&null!==t[r]?t[r]:e})}var Q={},U="#1fbc45",W=function(e){return{viewBox:e=e||"0 0 1024 1024",className:"svg-icon",xmlns:X}},X="http://www.w3.org/2000/svg";Q.legacy=h("svg",{width:"16px",height:"16px",viewBox:"0 0 80 90",className:"svg-icon mb10",xmlns:X,fillRule:"evenodd",clipRule:"evenodd",strokeLinejoin:"round",strokeMiterlimit:"1.414"},h("g",{fillRule:"nonzero",transform:"scale(0.19785394)"},h("path",{d:"m 408.68862,333.8044 0.009,0.59315 0.004,0.29795 c 0.18694,71.91774 -59.58485,130.93907 -134.53126,132.29044 -0.85543,0.0154 -1.71097,0.0231 -2.56654,0.0231 H 21.034693 C 11.007191,467.00905 2.5761396,460.42672 0.14656613,451.50411 L 338.63176,215.013 c 45.60925,25.97569 68.96153,65.57282 70.05686,118.7914 z M 231.25625,0 C 278.01331,0 321.188,23.909861 344.73248,62.682399 L 0,303.53751 V 20.793975 C 0,9.3097796 9.6674353,0 21.592821,0 Z",fill:U}))),Q.productbox=h("svg",W(),h("path",{d:"M975.36 400.64A88.32 88.32 0 0 0 887.68 320h-57.6c0-176.64-142.72-320-318.08-320-175.36 0-318.08 143.36-318.08 320h-57.6c-45.44 0-83.2 34.56-87.68 80.64l-44.16 446.08c-4.48 45.44 10.24 90.88 40.96 124.8 30.08 33.28 72.96 52.48 118.4 52.48h696.32c45.44 0 88.96-19.2 119.04-53.12 30.08-33.92 45.44-79.36 40.96-124.8l-44.8-445.44zM512 64c140.16 0 254.08 114.56 254.08 256H257.92c0-141.44 113.92-256 254.08-256z m419.84 864c-18.56 20.48-44.16 32-71.68 32H163.84c-27.52 0-53.12-11.52-71.68-32-18.56-20.48-27.52-47.36-24.96-75.52l44.16-446.08c1.28-12.8 12.16-22.4 24.96-22.4h57.6v96c0 17.92 14.08 32 32 32 17.28 0 32-14.08 32-32V384h508.8v96c0 17.92 14.08 32 32 32 17.28 0 32-14.08 32-32V384h57.6c12.8 0 23.68 9.6 24.96 22.4l44.16 446.08c1.92 28.16-7.04 54.4-25.6 75.52z",fill:U}),h("path",{d:"M752 679.04a536.768 536.768 0 0 1-480 0 31.744 31.744 0 0 0-42.88 14.08c-7.68 16-1.28 35.2 14.08 42.88 83.84 42.24 176.64 63.36 268.8 63.36 92.16 0 184.32-21.12 268.8-63.36 16-7.68 21.76-26.88 14.08-42.88a31.744 31.744 0 0 0-42.88-14.08z",fill:U})),Q.video=h("svg",W(),h("path",{d:"M704 874.666667H128c-46.933333 0-85.333333-38.4-85.333333-85.333334V234.666667c0-46.933333 38.4-85.333333 85.333333-85.333334h576c46.933333 0 85.333333 38.4 85.333333 85.333334v554.666666c0 46.933333-38.4 85.333333-85.333333 85.333334zM128 213.333333c-12.8 0-21.333333 8.533333-21.333333 21.333334v554.666666c0 12.8 8.533333 21.333333 21.333333 21.333334h576c12.8 0 21.333333-8.533333 21.333333-21.333334V234.666667c0-12.8-8.533333-21.333333-21.333333-21.333334H128z",fill:U}),h("path",{d:"M277.333333 490.666667c-59.733333 0-106.666667-46.933333-106.666666-106.666667s46.933333-106.666667 106.666666-106.666667 106.666667 46.933333 106.666667 106.666667-46.933333 106.666667-106.666667 106.666667z m0-149.333334c-23.466667 0-42.666667 19.2-42.666666 42.666667s19.2 42.666667 42.666666 42.666667 42.666667-19.2 42.666667-42.666667-19.2-42.666667-42.666667-42.666667zM938.666667 800c-8.533333 0-14.933333-2.133333-21.333334-6.4L725.333333 682.666667V341.333333l192-110.933333c10.666667-6.4 21.333333-6.4 32-4.266667 10.666667 2.133333 21.333333 8.533333 25.6 19.2 4.266667 6.4 6.4 14.933333 6.4 21.333334v490.666666c0 23.466667-19.2 42.666667-42.666666 42.666667z m-149.333334-153.6l128 74.666667V302.933333l-128 74.666667v268.8z",fill:U})),Q.iframe=h("svg",W(),h("path",{d:"M885.76 52.053333h-364.8c-47.786667 0-86.186667 38.826667-86.186667 86.186667v82.346667H139.093333c-48.213333 0-87.466667 39.253333-87.466666 87.04v576.426666c0 48.213333 39.253333 87.466667 87.466666 87.466667h576.426667c48.213333 0 87.04-39.253333 87.04-87.466667v-294.826666h82.773333c47.786667 0 86.186667-38.826667 86.186667-86.186667V138.666667c0.426667-47.786667-37.973333-86.613333-85.76-86.613334z m-151.04 832.426667c0 10.666667-8.533333 19.2-19.2 19.2H139.093333c-10.666667 0-19.2-8.533333-19.2-19.2V308.053333cLine truncated
|
||||
@@ -1364,17 +1364,6 @@ _win.bd.on('click', '.switch-iframe', function () {
|
||||
_this.addClass('active').siblings().removeClass('active');
|
||||
});
|
||||
|
||||
//下载文件
|
||||
_win.bd.on('click', '.file-download-btn', function () {
|
||||
var _this = jQuery(this);
|
||||
var id = _this.attr('data-download-file');
|
||||
var nonce = _this.attr('download-nonce');
|
||||
_this.attr('target', '_blank');
|
||||
if (!id) return;
|
||||
var href = _win.ajax_url + '?action=download_file&file=' + id + '&nonce=' + nonce;
|
||||
_this.attr('target', '_blank').removeAttr('data-download-file').attr('href', href);
|
||||
});
|
||||
|
||||
//文章古腾堡TAB
|
||||
_win.bd.on('click', '.post-tab-toggle', function () {
|
||||
var _this = jQuery(this);
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
(function($,window2,document2){"use strict";function closeNotyf($element){$element.addClass("notyn-out"),window2.setTimeout(function(){$element.remove()},1e3)}function notyf2(message,type,time,id){var $body=jQuery(document2.body);jQuery(".notyn").length||$body.append('<div class="notyn"></div>'),type=type||"success",type==="error"&&(type="danger"),time=time||5e3,time=time<100?time*1e3:time;var idAttribute=id?' id="'+id+'"':"",$notification=jQuery('<div class="noty1"'+idAttribute+'><div class="notyf '+type+'">'+message+"</div></div>"),shouldClose=!id;id&&jQuery("#"+id).length?(jQuery("#"+id).find(".notyf").removeClass().addClass("notyf "+type).html(message),$notification=jQuery("#"+id),shouldClose=!0):jQuery(".notyn").append($notification),shouldClose&&window2.setTimeout(function(){closeNotyf($notification)},time)}jQuery(document2.body).on("click",".noty1",function(){closeNotyf(jQuery(this))}),window2.notyf=notyf2})(jQuery,window,document),(function(window2){"use strict";var allowedKinds={identity:!0,badges:!0,orders:!0,vip:!0},allowedEvents={click:!0,shell:!0,"first-content":!0,ready:!0,"action-start":!0,"action-end":!0,unauthorized:!0,error:!0},sessions=Object.create(null),sequence=0,maxSessions=100;function normalize(value,fallback){var normalized=String(value||fallback||"").toLowerCase().replace(/[^a-z0-9-]/g,"");return normalized||fallback}function now(){return window2.performance&&typeof window2.performance.now=="function"?window2.performance.now():0}function markName(session,event){return"aksrt-modal-"+session.kind+"-"+session.id+"-"+event}function emit(session,event){if(!(!window2.performance||typeof window2.performance.mark!="function")){var name=markName(session,event);if(window2.performance.mark(name),session.marks[event]=name,typeof window2.performance.measure=="function"&&session.marks.click&&event!=="click")try{window2.performance.measure("aksrt-modal-"+session.kind+"-"+session.id+"-click-to-"+event,session.marks.click,name)}catch{}}}function start(kind){var safeKind=normalize(kind,"unknown");allowedKinds[safeKind]||(safeKind="unknown"),sequence+=1;var id=String(sequence),session={id,kind:safeKind,startedAt:now(),marks:Object.create(null)};sessions[id]=session,emit(session,"click");for(var ids=Object.keys(sessions);ids.length>maxSessions;)delete sessions[ids.shift()];return id}function mark(id,event){var session=sessions[String(id||"")],safeEvent=normalize(event,"error");!session||!allowedEvents[safeEvent]||emit(session,safeEvent)}function finish(id){mark(id,"ready")}function fail(id){mark(id,"error")}window2.AksrtModalTelemetry={start,mark,finish,error:fail}})(window),(function(window2){"use strict";function data(){return window2.aksrtData||window2.aksrt||{}}function createIdempotencyKey(){if(window2.crypto&&typeof window2.crypto.randomUUID=="function")return window2.crypto.randomUUID();if(!window2.crypto||typeof window2.crypto.getRandomValues!="function")throw new Error("当前浏览器无法生成安全的操作标识");var bytes=new Uint8Array(16);window2.crypto.getRandomValues(bytes),bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;var hex=Array.prototype.map.call(bytes,function(value){return value.toString(16).padStart(2,"0")}).join("");return hex.slice(0,8)+"-"+hex.slice(8,12)+"-"+hex.slice(12,16)+"-"+hex.slice(16,20)+"-"+hex.slice(20)}function restBase(){var config=data(),raw=config.restUrl||config.apiUrl||config.rest_url||"",siteUrl=config.siteUrl||config.homeUrl||window2.location.origin+"/";return window2.location.protocol==="https:"&&siteUrl.substring(0,5)==="http:"&&(siteUrl="https:"+siteUrl.substring(5)),raw?String(raw).replace(/\/$/,""):String(siteUrl).replace(/\/$/,"")+"/index.php?rest_route=/aksrt/v1"}function appendQuery(url2,query){if(!query)return url2;var parts=[];return typeof query=="string"?parts=query.replace(/^\?/,"").split("&").filter(Boolean):typeof query=="object"&&Object.keys(query).forEach(function(key){query[key]===void 0||query[key]===null||parts.push(encodeURIComponent(key)+"="+encodeURIComponent(String(query[key])))}),parts.length?url2+(url2.indexOf("?")>=0?"&":"?")+parts.join("&"):url2}function url(path,query){path=String(path||"");var inlineQuery="",queryIndex=path.indexOf("?");if(queryIndex>=0&&(inlineQuery=path.slice(queryIndex+1),path=path.slice(0,queryIndex)),/^https?:\/\//i.test(path))return appendQuery(path,query||inlineQuery);path.charAt(0)!=="/"&&(path="/"+path);var base=restBase(),result=(base.indexOf("rest_route=")>=0,base+path);return appendQuery(result,query||inlineQuery)}function headers(options){var config=data(),source=options&&options.headers||{},result={},nonce=config.restNonce||config.nonce||"";return Object.keys(source).forEach(function(key){result[key]=source[key]}),result.Accept||(result.Accept="application/json, text/html;q=0.9, */*;q=0.8"),nonce&&!result["X-WP-Nonce"]&&(result["X-WP-Nonce"]=nonce),options&&options.body!==void 0&&options.body!==null&&!(window2.FormData&&options.body instanceof window2.FormData)&&!result["Content-Type"]&Line truncated
|
||||
(function($,window2,document2){"use strict";function closeNotyf($element){$element.addClass("notyn-out"),window2.setTimeout(function(){$element.remove()},1e3)}function notyf2(message,type,time,id){var $body=jQuery(document2.body);jQuery(".notyn").length||$body.append('<div class="notyn"></div>'),type=type||"success",type==="error"&&(type="danger"),time=time||5e3,time=time<100?time*1e3:time;var idAttribute=id?' id="'+id+'"':"",$notification=jQuery('<div class="noty1"'+idAttribute+'><div class="notyf '+type+'">'+message+"</div></div>"),shouldClose=!id;id&&jQuery("#"+id).length?(jQuery("#"+id).find(".notyf").removeClass().addClass("notyf "+type).html(message),$notification=jQuery("#"+id),shouldClose=!0):jQuery(".notyn").append($notification),shouldClose&&window2.setTimeout(function(){closeNotyf($notification)},time)}jQuery(document2.body).on("click",".noty1",function(){closeNotyf(jQuery(this))}),window2.notyf=notyf2})(jQuery,window,document),(function(window2){"use strict";var allowedKinds={identity:!0,badges:!0,orders:!0,vip:!0},allowedEvents={click:!0,shell:!0,"first-content":!0,ready:!0,"action-start":!0,"action-end":!0,unauthorized:!0,error:!0},sessions=Object.create(null),sequence=0,maxSessions=100;function normalize(value,fallback){var normalized=String(value||fallback||"").toLowerCase().replace(/[^a-z0-9-]/g,"");return normalized||fallback}function now(){return window2.performance&&typeof window2.performance.now=="function"?window2.performance.now():0}function markName(session,event){return"aksrt-modal-"+session.kind+"-"+session.id+"-"+event}function emit(session,event){if(!(!window2.performance||typeof window2.performance.mark!="function")){var name=markName(session,event);if(window2.performance.mark(name),session.marks[event]=name,typeof window2.performance.measure=="function"&&session.marks.click&&event!=="click")try{window2.performance.measure("aksrt-modal-"+session.kind+"-"+session.id+"-click-to-"+event,session.marks.click,name)}catch{}}}function start(kind){var safeKind=normalize(kind,"unknown");allowedKinds[safeKind]||(safeKind="unknown"),sequence+=1;var id=String(sequence),session={id,kind:safeKind,startedAt:now(),marks:Object.create(null)};sessions[id]=session,emit(session,"click");for(var ids=Object.keys(sessions);ids.length>maxSessions;)delete sessions[ids.shift()];return id}function mark(id,event){var session=sessions[String(id||"")],safeEvent=normalize(event,"error");!session||!allowedEvents[safeEvent]||emit(session,safeEvent)}function finish(id){mark(id,"ready")}function fail(id){mark(id,"error")}window2.AksrtModalTelemetry={start,mark,finish,error:fail}})(window),(function(window2){"use strict";function data(){return window2.aksrtData||window2.aksrt||{}}function createIdempotencyKey(){if(window2.crypto&&typeof window2.crypto.randomUUID=="function")return window2.crypto.randomUUID();if(!window2.crypto||typeof window2.crypto.getRandomValues!="function")throw new Error("当前浏览器无法生成安全的操作标识");var bytes=new Uint8Array(16);window2.crypto.getRandomValues(bytes),bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;var hex=Array.prototype.map.call(bytes,function(value){return value.toString(16).padStart(2,"0")}).join("");return hex.slice(0,8)+"-"+hex.slice(8,12)+"-"+hex.slice(12,16)+"-"+hex.slice(16,20)+"-"+hex.slice(20)}function restBase(){var config=data(),raw=config.restUrl||config.apiUrl||config.rest_url||"",siteUrl=config.siteUrl||config.homeUrl||window2.location.origin+"/";return window2.location.protocol==="https:"&&siteUrl.substring(0,5)==="http:"&&(siteUrl="https:"+siteUrl.substring(5)),raw?String(raw).replace(/\/$/,""):String(siteUrl).replace(/\/$/,"")+"/index.php?rest_route=/aksrt/v1"}function appendQuery(url2,query){if(!query)return url2;var parts=[];return typeof query=="string"?parts=query.replace(/^\?/,"").split("&").filter(Boolean):typeof query=="object"&&Object.keys(query).forEach(function(key){query[key]===void 0||query[key]===null||parts.push(encodeURIComponent(key)+"="+encodeURIComponent(String(query[key])))}),parts.length?url2+(url2.indexOf("?")>=0?"&":"?")+parts.join("&"):url2}function url(path,query){path=String(path||"");var inlineQuery="",queryIndex=path.indexOf("?");if(queryIndex>=0&&(inlineQuery=path.slice(queryIndex+1),path=path.slice(0,queryIndex)),/^https?:\/\//i.test(path))return appendQuery(path,query||inlineQuery);path.charAt(0)!=="/"&&(path="/"+path);var base=restBase(),result=(base.indexOf("rest_route=")>=0,base+path);return appendQuery(result,query||inlineQuery)}function headers(options){var config=data(),source=options&&options.headers||{},result={},nonce=config.restNonce||config.nonce||"";return Object.keys(source).forEach(function(key){result[key]=source[key]}),result.Accept||(result.Accept="application/json, text/html;q=0.9, */*;q=0.8"),nonce&&!result["X-WP-Nonce"]&&(result["X-WP-Nonce"]=nonce),options&&options.body!==void 0&&options.body!==null&&!(window2.FormData&&options.body instanceof window2.FormData)&&!result["Content-Type"]&Line truncated
|
||||
Reference in new issue
Block a user