fix(comments): align image upload with Zibll
Unify comment image upload settings, REST permissions, preview, progress, and response handling while removing obsolete compatibility paths.
This commit is contained in:
@@ -46,6 +46,7 @@
|
||||
!/tests/widget-system/front-submit-editor-contract.test.cjs
|
||||
!/tests/widget-system/comment-smilies-removal-contract.test.cjs
|
||||
!/tests/widget-system/comment-children-list-reset-contract.test.cjs
|
||||
!/tests/widget-system/comment-image-upload-contract.test.cjs
|
||||
!/tests/widget-system/pay-card-contract.test.cjs
|
||||
!/tests/widget-system/circular-button-icon-margin-contract.test.cjs
|
||||
!/tests/widget-system/frontend-lifecycle-contract.test.cjs
|
||||
|
||||
@@ -15,6 +15,7 @@ export const commentSchema = {
|
||||
comment_edit_window: 10,
|
||||
comment_code: true,
|
||||
comment_img: true,
|
||||
comment_upload_img: false,
|
||||
comment_link: false,
|
||||
comment_like_s: true,
|
||||
comment_hot_threshold: 10,
|
||||
|
||||
@@ -213,12 +213,62 @@
|
||||
*
|
||||
* 评论区布局样式已硬切换为自有版权(见 layout.css / mobile-item.css),
|
||||
* vendor main.min.css 不再提供评论区规则。
|
||||
* 本文件只放 AKSRT 特有标记的补充规则(identity chip/medal)。
|
||||
* 本文件放 AKSRT 特有标记与评论图片上传的补充规则。
|
||||
* 共享基础样式仍由 bundle 中更早加载的 bootstrap 3 与
|
||||
* core/tokens.css 提供。
|
||||
* ============================================================ */
|
||||
|
||||
/* 身份徽章(AKSRT 渲染于 <name> 内,对应 legacy 的认证/等级徽章位) */
|
||||
#comments .comment-image-tabs .comment-image-upload {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
#comments .comment-image-upload-label {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#comments .comment-image-upload .preview {
|
||||
width: 100%;
|
||||
height: 96px;
|
||||
min-height: 96px;
|
||||
margin-bottom: 6px;
|
||||
overflow: hidden;
|
||||
border: 1px dashed var(--muted-border-color);
|
||||
border-radius: var(--main-radius);
|
||||
background: var(--main-shadow);
|
||||
}
|
||||
|
||||
#comments .comment-image-upload .preview img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 96px;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
#comments .comment-image-upload .input-expand-upload {
|
||||
min-width: 88px;
|
||||
}
|
||||
|
||||
#comments .comment-image-upload .progress {
|
||||
position: static;
|
||||
inset: auto;
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 3px;
|
||||
margin-top: 4px;
|
||||
overflow: hidden;
|
||||
border-radius: 3px;
|
||||
background: rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
|
||||
#comments .comment-image-upload .progress-bar {
|
||||
position: static;
|
||||
inset: auto;
|
||||
display: block;
|
||||
height: 100%;
|
||||
width: 0;
|
||||
transition: width 0.2s ease;
|
||||
}
|
||||
#comments .comment-header .aksrt-identity-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -3,12 +3,62 @@
|
||||
*
|
||||
* 评论区布局样式已硬切换为自有版权(见 layout.css / mobile-item.css),
|
||||
* vendor main.min.css 不再提供评论区规则。
|
||||
* 本文件只放 AKSRT 特有标记的补充规则(identity chip/medal)。
|
||||
* 本文件放 AKSRT 特有标记与评论图片上传的补充规则。
|
||||
* 共享基础样式仍由 bundle 中更早加载的 bootstrap 3 与
|
||||
* core/tokens.css 提供。
|
||||
* ============================================================ */
|
||||
|
||||
/* 身份徽章(AKSRT 渲染于 <name> 内,对应 legacy 的认证/等级徽章位) */
|
||||
#comments .comment-image-tabs .comment-image-upload {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
#comments .comment-image-upload-label {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#comments .comment-image-upload .preview {
|
||||
width: 100%;
|
||||
height: 96px;
|
||||
min-height: 96px;
|
||||
margin-bottom: 6px;
|
||||
overflow: hidden;
|
||||
border: 1px dashed var(--muted-border-color);
|
||||
border-radius: var(--main-radius);
|
||||
background: var(--main-shadow);
|
||||
}
|
||||
|
||||
#comments .comment-image-upload .preview img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 96px;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
#comments .comment-image-upload .input-expand-upload {
|
||||
min-width: 88px;
|
||||
}
|
||||
|
||||
#comments .comment-image-upload .progress {
|
||||
position: static;
|
||||
inset: auto;
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 3px;
|
||||
margin-top: 4px;
|
||||
overflow: hidden;
|
||||
border-radius: 3px;
|
||||
background: rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
|
||||
#comments .comment-image-upload .progress-bar {
|
||||
position: static;
|
||||
inset: auto;
|
||||
display: block;
|
||||
height: 100%;
|
||||
width: 0;
|
||||
transition: width 0.2s ease;
|
||||
}
|
||||
#comments .comment-header .aksrt-identity-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
+251
-74
@@ -1,9 +1,11 @@
|
||||
/**
|
||||
* Comment expand tools — legacy-style shortcode inserts ([code] [img=]).
|
||||
* Comment expand tools — shortcode inserts and comment image upload.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var uploadStates = new WeakMap();
|
||||
|
||||
function findTextarea(from) {
|
||||
var form = from && from.closest ? from.closest('form') : null;
|
||||
if (form) {
|
||||
@@ -24,107 +26,282 @@
|
||||
textarea.dispatchEvent(new Event('input'));
|
||||
}
|
||||
|
||||
function restUpload(file) {
|
||||
var d = window.aksrtData || {};
|
||||
var url = d.commentUploadUrl || ((d.restUrl || '/wp-json/aksrt/v1').replace(/\/$/, '') + '/comment/upload-image');
|
||||
var fd = new FormData();
|
||||
fd.append('image', file);
|
||||
fd.append('file', file);
|
||||
return fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'X-WP-Nonce': d.restNonce || d.nonce || '' },
|
||||
credentials: 'same-origin',
|
||||
body: fd
|
||||
}).then(function (r) { return r.json(); });
|
||||
function notify(message, type) {
|
||||
if (typeof window.notyf === 'function') {
|
||||
window.notyf(message, type);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('click', function (e) {
|
||||
var linkBtn = e.target && e.target.closest ? e.target.closest('.input-link-submit') : null;
|
||||
function showImageTab(trigger) {
|
||||
var selector = trigger.getAttribute('data-image-tab');
|
||||
var wrapper = trigger.closest('.comment-image-tabs');
|
||||
if (!selector || !wrapper) return null;
|
||||
var target = wrapper.querySelector(selector);
|
||||
if (!target) return null;
|
||||
|
||||
wrapper.querySelectorAll('.tab-pane').forEach(function (pane) {
|
||||
pane.classList.remove('in', 'active');
|
||||
});
|
||||
target.classList.add('in', 'active');
|
||||
return target;
|
||||
}
|
||||
|
||||
function getUploadState(form) {
|
||||
var state = uploadStates.get(form);
|
||||
if (state) return state;
|
||||
|
||||
var preview = form.querySelector('.preview');
|
||||
state = {
|
||||
file: null,
|
||||
uploading: false,
|
||||
previewHtml: preview ? preview.innerHTML : ''
|
||||
};
|
||||
uploadStates.set(form, state);
|
||||
return state;
|
||||
}
|
||||
|
||||
function resetUpload(form) {
|
||||
var state = getUploadState(form);
|
||||
var input = form.querySelector('.comment-image-file');
|
||||
var preview = form.querySelector('.preview');
|
||||
|
||||
state.file = null;
|
||||
state.uploading = false;
|
||||
if (input) {
|
||||
input.disabled = false;
|
||||
input.value = '';
|
||||
}
|
||||
if (preview) preview.innerHTML = state.previewHtml;
|
||||
}
|
||||
|
||||
function restoreUploadButton(button, html) {
|
||||
button.disabled = false;
|
||||
button.innerHTML = html;
|
||||
}
|
||||
|
||||
function validateImage(input, file) {
|
||||
var accepts = (input.getAttribute('accept') || '')
|
||||
.split(',')
|
||||
.map(function (type) { return type.trim().toLowerCase(); })
|
||||
.filter(Boolean);
|
||||
var fileType = (file.type || '').toLowerCase();
|
||||
if (accepts.length && accepts.indexOf(fileType) === -1) {
|
||||
notify('图片格式错误:' + file.name, 'danger');
|
||||
return false;
|
||||
}
|
||||
|
||||
var maxSize = Number((window.aksrtData || {}).commentUploadMaxSize) || 0;
|
||||
if (maxSize > 0 && file.size > maxSize) {
|
||||
notify('图片大小不能超过 ' + Math.round(maxSize / 1024 / 1024) + 'MB', 'danger');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function previewImage(form, file) {
|
||||
var preview = form.querySelector('.preview');
|
||||
if (!preview) return;
|
||||
if (typeof FileReader === 'undefined') {
|
||||
notify('当前浏览器不支持图片预览', 'danger');
|
||||
return;
|
||||
}
|
||||
|
||||
var reader = new FileReader();
|
||||
reader.onload = function (event) {
|
||||
if (getUploadState(form).file !== file) return;
|
||||
var image = document.createElement('img');
|
||||
image.className = 'fit-cover';
|
||||
image.alt = '';
|
||||
image.src = event.target.result;
|
||||
preview.innerHTML = '';
|
||||
preview.appendChild(image);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
function parseUploadResponse(xhr) {
|
||||
try {
|
||||
return JSON.parse(xhr.responseText || '{}');
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function uploadImage(button) {
|
||||
var form = button.closest('.comment-image-upload');
|
||||
if (!form) return;
|
||||
|
||||
var input = form.querySelector('.comment-image-file');
|
||||
var state = getUploadState(form);
|
||||
if (!input || !state.file) {
|
||||
notify('请先选择待上传的图片', 'danger');
|
||||
return;
|
||||
}
|
||||
if (state.uploading) return;
|
||||
|
||||
var data = window.aksrtData || {};
|
||||
var uploadUrl = data.commentUploadUrl || '';
|
||||
if (!uploadUrl) {
|
||||
notify('图片上传服务不可用', 'danger');
|
||||
return;
|
||||
}
|
||||
|
||||
var originalHtml = button.innerHTML;
|
||||
var formData = new FormData();
|
||||
formData.append('image', state.file, state.file.name);
|
||||
|
||||
state.uploading = true;
|
||||
button.disabled = true;
|
||||
input.disabled = true;
|
||||
button.innerHTML = '<span class="miniupload-ing"><i class="loading mr3 c-white"></i><span class="loading-text c-white">上传中<count class="px12 ml3"></count></span><span class="progress progress-striped active"><span class="progress-bar progress-bar-success" role="progressbar" style="width:0"></span></span></span>';
|
||||
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', uploadUrl, true);
|
||||
if (data.restNonce) xhr.setRequestHeader('X-WP-Nonce', data.restNonce);
|
||||
|
||||
xhr.upload.onprogress = function (event) {
|
||||
if (!event.lengthComputable) return;
|
||||
var percent = Math.round((event.loaded / event.total) * 100);
|
||||
var count = button.querySelector('count');
|
||||
var progress = button.querySelector('.progress-bar');
|
||||
var loadingText = button.querySelector('.loading-text');
|
||||
if (count) count.textContent = percent + '%';
|
||||
if (progress) progress.style.width = percent + '%';
|
||||
if (percent >= 100 && loadingText) loadingText.firstChild.nodeValue = '处理中';
|
||||
};
|
||||
|
||||
xhr.onload = function () {
|
||||
var response = parseUploadResponse(xhr);
|
||||
var url = response && response.success === true && response.data
|
||||
? response.data.url
|
||||
: '';
|
||||
|
||||
if (xhr.status < 200 || xhr.status >= 300 || typeof url !== 'string' || url.length < 6) {
|
||||
var message = response && response.message ? response.message : '图片上传失败';
|
||||
notify(message, 'danger');
|
||||
restoreUploadButton(button, originalHtml);
|
||||
resetUpload(form);
|
||||
return;
|
||||
}
|
||||
|
||||
notify(response.message || '图片已上传', 'success');
|
||||
insertAtCursor(findTextarea(button), '[img=' + url + ']\n');
|
||||
restoreUploadButton(button, originalHtml);
|
||||
resetUpload(form);
|
||||
};
|
||||
|
||||
xhr.onerror = function () {
|
||||
notify('网络错误,图片上传失败', 'danger');
|
||||
restoreUploadButton(button, originalHtml);
|
||||
resetUpload(form);
|
||||
};
|
||||
|
||||
xhr.send(formData);
|
||||
}
|
||||
|
||||
document.addEventListener('change', function (event) {
|
||||
var input = event.target && event.target.closest
|
||||
? event.target.closest('.comment-image-file')
|
||||
: null;
|
||||
if (!input) return;
|
||||
|
||||
var form = input.closest('.comment-image-upload');
|
||||
var file = input.files && input.files[0];
|
||||
if (!form || !file) return;
|
||||
if (!validateImage(input, file)) {
|
||||
resetUpload(form);
|
||||
return;
|
||||
}
|
||||
|
||||
var state = getUploadState(form);
|
||||
state.file = file;
|
||||
previewImage(form, file);
|
||||
var button = form.querySelector('[data-comment-upload-submit]');
|
||||
if (button) uploadImage(button);
|
||||
});
|
||||
|
||||
document.addEventListener('click', function (event) {
|
||||
var linkBtn = event.target && event.target.closest ? event.target.closest('.input-link-submit') : null;
|
||||
if (linkBtn) {
|
||||
e.preventDefault();
|
||||
var lbox = linkBtn.closest('.dropdown-link');
|
||||
var lta = lbox ? lbox.querySelector('textarea.link-textarea') : null;
|
||||
var url = lta ? (lta.value || '').trim() : '';
|
||||
if (!/^https?:\/\/\S+$/i.test(url)) {
|
||||
notyf('请输入有效链接地址', 'warning');
|
||||
event.preventDefault();
|
||||
var linkBox = linkBtn.closest('.dropdown-link');
|
||||
var linkTextarea = linkBox ? linkBox.querySelector('textarea.link-textarea') : null;
|
||||
var linkUrl = linkTextarea ? (linkTextarea.value || '').trim() : '';
|
||||
if (!/^https?:\/\/\S+$/i.test(linkUrl)) {
|
||||
notify('请输入有效链接地址', 'warning');
|
||||
return;
|
||||
}
|
||||
var ltext = lbox ? (lbox.querySelector('.link-text') || {}).value || '' : '';
|
||||
insertAtCursor(findTextarea(linkBtn), '[link=' + url + ']' + (ltext.trim() || url) + '[/link]');
|
||||
if (lta) lta.value = '';
|
||||
var lt = lbox ? lbox.querySelector('.link-text') : null;
|
||||
if (lt) lt.value = '';
|
||||
var lw = linkBtn.closest('span.dropup');
|
||||
if (lw) lw.classList.remove('open');
|
||||
var linkTextInput = linkBox ? linkBox.querySelector('.link-text') : null;
|
||||
var linkText = linkTextInput ? linkTextInput.value || '' : '';
|
||||
insertAtCursor(findTextarea(linkBtn), '[link=' + linkUrl + ']' + (linkText.trim() || linkUrl) + '[/link]');
|
||||
if (linkTextarea) linkTextarea.value = '';
|
||||
if (linkTextInput) linkTextInput.value = '';
|
||||
var linkWrapper = linkBtn.closest('span.dropup');
|
||||
if (linkWrapper) linkWrapper.classList.remove('open');
|
||||
return;
|
||||
}
|
||||
|
||||
var codeBtn = e.target && e.target.closest ? e.target.closest('.input-code-submit') : null;
|
||||
var codeBtn = event.target && event.target.closest ? event.target.closest('.input-code-submit') : null;
|
||||
if (codeBtn) {
|
||||
e.preventDefault();
|
||||
var box = codeBtn.closest('.dropdown-code, .input-expand-code');
|
||||
var ta = box ? box.querySelector('textarea') : null;
|
||||
var code = ta ? ta.value : '';
|
||||
event.preventDefault();
|
||||
var codeBox = codeBtn.closest('.dropdown-code, .input-expand-code');
|
||||
var codeTextarea = codeBox ? codeBox.querySelector('textarea') : null;
|
||||
var code = codeTextarea ? codeTextarea.value : '';
|
||||
if (!code || code.length < 2) {
|
||||
notyf('请输入代码', 'warning');
|
||||
notify('请输入代码', 'warning');
|
||||
return;
|
||||
}
|
||||
insertAtCursor(findTextarea(codeBtn), '[code]\n' + code + '\n[/code]\n');
|
||||
if (ta) ta.value = '';
|
||||
var w = codeBtn.closest('span.dropup');
|
||||
if (w) w.classList.remove('open');
|
||||
if (codeTextarea) codeTextarea.value = '';
|
||||
var codeWrapper = codeBtn.closest('span.dropup');
|
||||
if (codeWrapper) codeWrapper.classList.remove('open');
|
||||
return;
|
||||
}
|
||||
|
||||
var imgBtn = e.target && e.target.closest ? e.target.closest('.input-image-submit') : null;
|
||||
if (imgBtn) {
|
||||
e.preventDefault();
|
||||
var ibox = imgBtn.closest('.dropdown-image, .input-expand-image');
|
||||
var input = ibox ? ibox.querySelector('.input-image-url') : null;
|
||||
var url = input ? (input.value || '').trim() : '';
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
notyf('请输入有效图片地址', 'warning');
|
||||
var imageSubmit = event.target && event.target.closest ? event.target.closest('.input-image-submit') : null;
|
||||
if (imageSubmit) {
|
||||
event.preventDefault();
|
||||
var imageBox = imageSubmit.closest('.dropdown-image');
|
||||
var imageInput = imageBox ? imageBox.querySelector('.input-image-url') : null;
|
||||
var imageUrl = imageInput ? (imageInput.value || '').trim() : '';
|
||||
if (imageUrl.length < 6) {
|
||||
notify('请输入有效图片地址', 'warning');
|
||||
return;
|
||||
}
|
||||
insertAtCursor(findTextarea(imgBtn), '[img=' + url + ']');
|
||||
if (input) input.value = '';
|
||||
var iw = imgBtn.closest('span.dropup');
|
||||
if (iw) iw.classList.remove('open');
|
||||
insertAtCursor(findTextarea(imageSubmit), '[img=' + imageUrl + ']\n');
|
||||
return;
|
||||
}
|
||||
|
||||
var upBtn = e.target && e.target.closest ? e.target.closest('.input-image-upload') : null;
|
||||
if (upBtn) {
|
||||
e.preventDefault();
|
||||
var fileInput = document.createElement('input');
|
||||
fileInput.type = 'file';
|
||||
fileInput.accept = 'image/jpeg,image/png,image/gif,image/webp';
|
||||
fileInput.addEventListener('change', function () {
|
||||
var file = fileInput.files && fileInput.files[0];
|
||||
if (!file) return;
|
||||
restUpload(file)
|
||||
.then(function (json) {
|
||||
var u = (json && (json.url || json.source_url || (json.data && (json.data.url || json.data.source_url)))) || '';
|
||||
if (!u) {
|
||||
notyf((json && json.message) || '上传失败', 'danger');
|
||||
var uploadTab = event.target && event.target.closest ? event.target.closest('.input-image-upload-tab') : null;
|
||||
if (uploadTab) {
|
||||
event.preventDefault();
|
||||
var uploadPane = showImageTab(uploadTab);
|
||||
var uploadInput = uploadPane ? uploadPane.querySelector('.comment-image-file') : null;
|
||||
if (uploadInput) uploadInput.click();
|
||||
return;
|
||||
}
|
||||
insertAtCursor(findTextarea(upBtn), '[img=' + u + ']');
|
||||
})
|
||||
.catch(function () { notyf('上传失败', 'danger'); });
|
||||
});
|
||||
fileInput.click();
|
||||
|
||||
var addressTab = event.target && event.target.closest ? event.target.closest('.input-image-address-tab') : null;
|
||||
if (addressTab) {
|
||||
event.preventDefault();
|
||||
showImageTab(addressTab);
|
||||
return;
|
||||
}
|
||||
|
||||
var uploadButton = event.target && event.target.closest ? event.target.closest('[data-comment-upload-submit]') : null;
|
||||
if (uploadButton) {
|
||||
event.preventDefault();
|
||||
uploadImage(uploadButton);
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if (!(e.ctrlKey || e.metaKey) || e.key !== 'Enter') return;
|
||||
var ta = e.target;
|
||||
if (!ta || ta.id !== 'comment') return;
|
||||
var form = ta.closest('#commentform');
|
||||
document.addEventListener('keydown', function (event) {
|
||||
if (!(event.ctrlKey || event.metaKey) || event.key !== 'Enter') return;
|
||||
var textarea = event.target;
|
||||
if (!textarea || textarea.id !== 'comment') return;
|
||||
var form = textarea.closest('#commentform');
|
||||
if (!form) return;
|
||||
e.preventDefault();
|
||||
event.preventDefault();
|
||||
var submit = form.querySelector('#submit, [type="submit"]');
|
||||
if (submit) submit.click();
|
||||
});
|
||||
|
||||
@@ -59,19 +59,6 @@
|
||||
return formData;
|
||||
}
|
||||
|
||||
// 从 wp_die() HTML 中提取错误信息
|
||||
function extractErrorMessage(html) {
|
||||
// WordPress wp_die() 输出格式: <p>错误信息</p>
|
||||
var match = html.match(/<p[^>]*>([^<]+)<\/p>/i);
|
||||
return match ? match[1].trim() : '未知错误';
|
||||
}
|
||||
|
||||
// 从错误消息中提取等待时间(秒)
|
||||
function extractWaitTime(msg) {
|
||||
var match = msg.match(/(\d+)\s*秒/);
|
||||
return match ? parseInt(match[1]) : 0;
|
||||
}
|
||||
|
||||
// 启动倒计时(用于频率限制)
|
||||
function startCountdown(seconds) {
|
||||
if (countdownTimer) clearInterval(countdownTimer);
|
||||
@@ -106,93 +93,6 @@
|
||||
var nextCount = Math.max(0, parseInt(match[1], 10) + delta);
|
||||
countEl.textContent = text.replace(match[1], String(nextCount));
|
||||
}
|
||||
function handleResponse(responseText, statusCode) {
|
||||
try {
|
||||
// 情况1: 成功提交 - 包含评论ID或成功标记
|
||||
if (statusCode === 200 || statusCode === 201) {
|
||||
if (responseText.includes('comment-submitted') ||
|
||||
responseText.indexOf('id="comment-') !== -1 ||
|
||||
responseText.indexOf('awaiting-moderation') !== -1) {
|
||||
|
||||
// 区分是否需要审核
|
||||
if (responseText.indexOf('审核') !== -1 ||
|
||||
responseText.indexOf('moderation') !== -1 ||
|
||||
responseText.includes('awaiting-moderation')) {
|
||||
notyf('评论已提交,等待管理员审核', 'info');
|
||||
} else {
|
||||
notyf('评论发布成功', 'success');
|
||||
}
|
||||
|
||||
// 清空文本框
|
||||
var textarea = form.querySelector('#comment');
|
||||
if (textarea) textarea.value = '';
|
||||
|
||||
// 重置回复状态
|
||||
var replyInfo = document.getElementById('comment-reply-info');
|
||||
if (replyInfo) replyInfo.style.display = 'none';
|
||||
|
||||
// 刷新评论列表(延迟执行,确保后端处理完成)
|
||||
setTimeout(function () {
|
||||
reloadCommentList();
|
||||
}, 500);
|
||||
setLoading(false);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 情况2: HTTP 429 频率限制
|
||||
if (statusCode === 429) {
|
||||
var errorMsg = extractErrorMessage(responseText);
|
||||
var waitSeconds = extractWaitTime(errorMsg);
|
||||
|
||||
notyf(errorMsg, 'warning');
|
||||
|
||||
if (waitSeconds > 0) {
|
||||
startCountdown(waitSeconds);
|
||||
} else {
|
||||
setLoading(false); // 无具体等待时间时恢复按钮
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// 情况3: HTTP 403 权限不足(地区/IP/关键词等)
|
||||
if (statusCode === 403) {
|
||||
var forbiddenMsg = extractErrorMessage(responseText);
|
||||
notyf(forbiddenMsg, 'danger');
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 情况4: 包含WordPress错误信息
|
||||
var errorMatch = responseText.match(/<p[^>]*>([^<]*(?:错误|失败|error|Error)[^<]*)<\/p>/i);
|
||||
if (errorMatch) {
|
||||
notyf(errorMatch[1].trim(), 'danger');
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
// 默认情况:可能是成功或其他
|
||||
notyf('评论已提交', 'success');
|
||||
var textarea2 = form.querySelector('#comment');
|
||||
if (textarea2) textarea2.value = '';
|
||||
|
||||
// 局部刷新评论列表(不再整页 reload)
|
||||
setTimeout(function () {
|
||||
reloadCommentList();
|
||||
}, 500);
|
||||
setLoading(false);
|
||||
|
||||
return true;
|
||||
|
||||
} catch (e) {
|
||||
console.error('[AKSRT Comment] 解析响应失败:', e);
|
||||
notyf('响应解析异常,请重试', 'danger');
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行实际的 REST 请求 — local insert instead of full-page re-fetch
|
||||
function performSubmit(captchaPayload) {
|
||||
setLoading(true);
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -70,17 +70,32 @@ if (!function_exists('aksrt_get_input_expand_but')) :
|
||||
|
||||
case 'image':
|
||||
$upload = !empty($arg1) || !empty($ctx['upload']);
|
||||
$upload_id = 'comment';
|
||||
$but = '<a class="but btn-input-expand input-image mr6" href="javascript:;"><i class="fa fas fa-fw fa-image" aria-hidden="true"></i><span class="hide-sm">' . esc_html__('图片', 'aksrt') . '</span></a>';
|
||||
|
||||
$dropdown = '<div class="dropdown-image">';
|
||||
$dropdown = '<div class="tab-content comment-image-tabs">';
|
||||
$dropdown .= '<div class="tab-pane fade in active dropdown-image" id="image-tab-' . esc_attr($upload_id) . '-1">';
|
||||
$dropdown .= '<p>' . esc_html__('请填写图片地址:', 'aksrt') . '</p>';
|
||||
$dropdown .= '<p><textarea rows="2" tabindex="1" class="form-control input-textarea input-image-url" style="height:95px;" placeholder="http://..."></textarea></p>';
|
||||
$dropdown .= '<div class="text-right">';
|
||||
if ($upload) {
|
||||
$dropdown .= '<a class="but c-yellow mr10 pw-1em input-image-upload" href="javascript:;">' . esc_html__('上传图片', 'aksrt') . '</a>';
|
||||
$dropdown .= '<a class="but c-yellow mr10 pw-1em input-image-upload-tab" data-image-tab="#image-tab-' . esc_attr($upload_id) . '-2" href="javascript:;">' . esc_html__('上传图片', 'aksrt') . '</a>';
|
||||
}
|
||||
$dropdown .= '<a type="submit" class="but c-blue pw-1em input-image-submit" href="javascript:;">' . esc_html__('确认', 'aksrt') . '</a>';
|
||||
$dropdown .= '</div>';
|
||||
$dropdown .= '</div></div>';
|
||||
|
||||
if ($upload) {
|
||||
$placeholder = get_template_directory_uri() . '/assets/img/upload-add.svg';
|
||||
$dropdown .= '<div class="tab-pane fade dropdown-image" id="image-tab-' . esc_attr($upload_id) . '-2">';
|
||||
$dropdown .= '<p><a class="muted-color input-image-address-tab" data-image-tab="#image-tab-' . esc_attr($upload_id) . '-1" href="javascript:;"><i class="fa fa-angle-left mr6" aria-hidden="true"></i>' . esc_html__('填写图片地址', 'aksrt') . '</a></p>';
|
||||
$dropdown .= '<div class="form-upload comment-image-upload">';
|
||||
$dropdown .= '<label class="pointer comment-image-upload-label">';
|
||||
$dropdown .= '<div class="preview text-center mb6"><img src="' . esc_url($placeholder) . '" alt="" /></div>';
|
||||
$dropdown .= '<input class="hide comment-image-file" type="file" id="input_' . esc_attr($upload_id) . '_image_upload" accept="image/gif,image/jpeg,image/jpg,image/png" name="image">';
|
||||
$dropdown .= '</label>';
|
||||
$dropdown .= '<div class="text-right"><button type="button" class="but jb-blue pw-1em input-expand-upload" data-comment-upload-submit="1">' . esc_html__('确认上传', 'aksrt') . '</button></div>';
|
||||
$dropdown .= '</div></div>';
|
||||
}
|
||||
$dropdown .= '</div>';
|
||||
break;
|
||||
|
||||
|
||||
@@ -224,7 +224,8 @@ class SchemaPostList {
|
||||
]],
|
||||
['key' => 'toolbar', 'title' => '评论工具栏', 'fields' => [
|
||||
['key' => 'comment_code', 'label' => '代码插入', 'type' => 'switch', 'default' => true],
|
||||
['key' => 'comment_img', 'label' => '图片上传', 'type' => 'switch', 'default' => true],
|
||||
['key' => 'comment_img', 'label' => '图片按钮', 'type' => 'switch', 'default' => true],
|
||||
['key' => 'comment_upload_img', 'label' => '评论图片上传', 'type' => 'switch', 'default' => false],
|
||||
['key' => 'comment_link', 'label' => '链接按钮', 'type' => 'switch', 'default' => false],
|
||||
]],
|
||||
['key' => 'interaction', 'title' => '互动功能', 'fields' => [
|
||||
|
||||
@@ -50,11 +50,11 @@ class UserController extends ControllerBase {
|
||||
],
|
||||
]);
|
||||
|
||||
// Comment inline image upload (logged-in users)
|
||||
// Comment inline image upload (logged-in users with the comment upload setting enabled).
|
||||
register_rest_route(self::API_NAMESPACE, '/comment/upload-image', [
|
||||
'methods' => 'POST',
|
||||
'callback' => [$this, 'rest_upload_comment_image'],
|
||||
'permission_callback' => function () { return is_user_logged_in(); },
|
||||
'permission_callback' => [$this, 'check_comment_image_upload_permission'],
|
||||
]);
|
||||
|
||||
// Notification settings
|
||||
@@ -476,22 +476,38 @@ class UserController extends ControllerBase {
|
||||
return $this->success(['message' => __('消息清理任务已受理', 'aksrt')]);
|
||||
}
|
||||
|
||||
public function check_comment_image_upload_permission(?\WP_REST_Request $request = null) {
|
||||
if (!is_user_logged_in()) {
|
||||
return new \WP_Error('aksrt_auth_required', __('请先登录', 'aksrt'), ['status' => 401]);
|
||||
}
|
||||
if ($request !== null) {
|
||||
$nonce = (string) $request->get_header('X-WP-Nonce');
|
||||
if ($nonce === '' || !wp_verify_nonce($nonce, 'wp_rest')) {
|
||||
return new \WP_Error('aksrt_rest_nonce', __('安全验证失败,请刷新页面后重试', 'aksrt'), ['status' => 403]);
|
||||
}
|
||||
}
|
||||
$settings = class_exists('\\AKSRT\\Settings\\Settings') ? \AKSRT\Settings\Settings::get_all() : [];
|
||||
$image_enabled = !isset($settings['comment_img']) || !empty($settings['comment_img']);
|
||||
if (!$image_enabled || empty($settings['comment_upload_img'])) {
|
||||
return new \WP_Error('aksrt_comment_upload_disabled', __('评论图片上传功能未开启', 'aksrt'), ['status' => 403]);
|
||||
}
|
||||
$user_id = get_current_user_id();
|
||||
if (!function_exists('aksrt_user_can') || !aksrt_user_can('upload_comment_image', $user_id)) {
|
||||
return new \WP_Error('aksrt_comment_upload_forbidden', __('当前账号没有上传评论图片的权限', 'aksrt'), ['status' => 403]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rest_upload_comment_image(\WP_REST_Request $request): \WP_REST_Response {
|
||||
$user_id = get_current_user_id();
|
||||
if ($user_id <= 0) {
|
||||
return $this->error(__('请先登录', 'aksrt'), 401);
|
||||
}
|
||||
if (!function_exists('aksrt_user_can') || !aksrt_user_can('upload_comment_image', $user_id)) {
|
||||
return $this->error(__('当前账号没有上传评论图片的权限', 'aksrt'), 403);
|
||||
}
|
||||
if (empty($_FILES['image']) && empty($_FILES['file'])) {
|
||||
if (empty($_FILES['image'])) {
|
||||
return $this->error(__('请选择要上传的图片', 'aksrt'), 400);
|
||||
}
|
||||
require_once ABSPATH . 'wp-admin/includes/file.php';
|
||||
require_once ABSPATH . 'wp-admin/includes/media.php';
|
||||
require_once ABSPATH . 'wp-admin/includes/image.php';
|
||||
|
||||
$file_key = !empty($_FILES['image']) ? 'image' : 'file';
|
||||
$file_key = 'image';
|
||||
$file = $_FILES[$file_key];
|
||||
$upload_error = isset($file['error']) ? (int) $file['error'] : UPLOAD_ERR_NO_FILE;
|
||||
if ($upload_error !== UPLOAD_ERR_OK) {
|
||||
@@ -537,13 +553,13 @@ class UserController extends ControllerBase {
|
||||
}
|
||||
$url = wp_get_attachment_url((int) $attachment_id);
|
||||
if (!$url) {
|
||||
wp_delete_attachment((int) $attachment_id, true);
|
||||
return $this->error(__('上传失败', 'aksrt'), 500);
|
||||
}
|
||||
return $this->success([
|
||||
'message' => __('图片上传成功', 'aksrt'),
|
||||
'data' => [
|
||||
'url' => $url,
|
||||
'attachment_id' => (int) $attachment_id,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -208,7 +208,6 @@ trait ScriptsPart1c {
|
||||
'post_action_nonce' => wp_create_nonce('post_action'),
|
||||
'is_split_upload' => false,
|
||||
'split_minimum_size' => 10,
|
||||
'comment_upload_img' => false,
|
||||
'translate_config' => [],
|
||||
'i18n' => [
|
||||
'load_more' => __('加载更多', 'aksrt'),
|
||||
@@ -489,9 +488,12 @@ trait ScriptsPart1c {
|
||||
'ajaxLoading' => __('正在加载...', 'aksrt'),
|
||||
'iasMax' => class_exists('\AKSRT\Settings\Settings') ? \AKSRT\Settings\Settings::get_post_list_style_settings()['ias_max'] : 3,
|
||||
'commentIasAuto' => class_exists('\AKSRT\Settings\Settings') ? \AKSRT\Settings\Settings::get_comment_display_settings()['paging_ajax_ias'] : true,
|
||||
'commentUploadEnabled' => class_exists('\AKSRT\Settings\Settings') ? !empty((\AKSRT\Settings\Settings::get_comment_display_settings()['toolbar']['upload_img'] ?? false)) : false,
|
||||
'commentUploadUrl' => esc_url_raw(rest_url('aksrt/v1/comment/upload-image')),
|
||||
'commentUploadMaxSize' => 2 * 1024 * 1024,
|
||||
'commentUploadMaxSize' => (function () {
|
||||
$settings = class_exists('\\AKSRT\\Settings\\Settings') ? \AKSRT\Settings\Settings::get_all() : [];
|
||||
$max_size_mb = max(1, min(10, (int) ($settings['comment_image_max_size'] ?? 2)));
|
||||
return $max_size_mb * MB_IN_BYTES;
|
||||
})(),
|
||||
'commentIasMax' => class_exists('\AKSRT\Settings\Settings') ? \AKSRT\Settings\Settings::get_comment_display_settings()['paging_ajax_ias_max'] : 3,
|
||||
'restUrl' => esc_url_raw(rest_url('aksrt/v1')),
|
||||
// Alias used by modal-auth / follow / report (same value as restUrl).
|
||||
|
||||
@@ -385,7 +385,11 @@ class PostDisplay {
|
||||
'code' => !isset($settings['comment_code']) || !empty($settings['comment_code']),
|
||||
'image' => !isset($settings['comment_img']) || !empty($settings['comment_img']),
|
||||
'link' => !empty($settings['comment_link']),
|
||||
'upload_img' => function_exists('aksrt_user_can') && aksrt_user_can('upload_comment_image', get_current_user_id()),
|
||||
'upload_img' => (!isset($settings['comment_img']) || !empty($settings['comment_img']))
|
||||
&& !empty($settings['comment_upload_img'])
|
||||
&& is_user_logged_in()
|
||||
&& function_exists('aksrt_user_can')
|
||||
&& aksrt_user_can('upload_comment_image', get_current_user_id()),
|
||||
],
|
||||
'like_enabled' => !isset($settings['comment_like_s']) || !empty($settings['comment_like_s']),
|
||||
'author_tag' => !isset($settings['comment_author_tag']) || !empty($settings['comment_author_tag']),
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const test = require('node:test');
|
||||
|
||||
const root = path.resolve(__dirname, '..', '..');
|
||||
const read = (file) => fs.readFileSync(path.join(root, file), 'utf8');
|
||||
|
||||
const formParts = read('inc/helpers/comments/form-parts.php');
|
||||
const tools = read('assets/js/comment-tools.js');
|
||||
const controller = read('src/Admin/UserController.php');
|
||||
const display = read('src/Settings/PostDisplay.php');
|
||||
const phpSchema = read('src/Admin/Schema/SchemaPostList.php');
|
||||
const adminSchema = read('assets/admin/src/schema/sections/post-list/comment.js');
|
||||
const runtime = read('src/Core/ScriptsPart1c.php');
|
||||
const commentsCss = read('assets/css/build/comments.css');
|
||||
const runtimeBundle = read('assets/js/runtime/main.min.js');
|
||||
|
||||
test('comment image settings use one two-switch contract', () => {
|
||||
for (const source of [phpSchema, adminSchema]) {
|
||||
assert.match(source, /comment_img/);
|
||||
assert.match(source, /comment_upload_img/);
|
||||
}
|
||||
assert.match(display, /!empty\(\$settings\['comment_upload_img'\]\)/);
|
||||
assert.match(display, /is_user_logged_in\(\)/);
|
||||
assert.match(display, /aksrt_user_can\('upload_comment_image'/);
|
||||
assert.doesNotMatch(runtime, /commentUploadEnabled/);
|
||||
assert.doesNotMatch(runtime, /'comment_upload_img'\s*=>/);
|
||||
});
|
||||
|
||||
test('comment image form matches the single-file reference interaction', () => {
|
||||
assert.match(formParts, /comment-image-tabs/);
|
||||
assert.match(formParts, /input-image-upload-tab/);
|
||||
assert.match(formParts, /input-image-address-tab/);
|
||||
assert.match(formParts, /class="form-upload comment-image-upload"/);
|
||||
assert.match(formParts, /class="preview text-center mb6"/);
|
||||
assert.match(formParts, /class="hide comment-image-file"/);
|
||||
assert.match(formParts, /accept="image\/gif,image\/jpeg,image\/jpg,image\/png"/);
|
||||
assert.match(formParts, /name="image"/);
|
||||
assert.match(formParts, /data-comment-upload-submit/);
|
||||
assert.equal((formParts.match(/name="image"/g) || []).length, 1);
|
||||
});
|
||||
|
||||
test('comment uploader validates, previews, tracks progress, and inserts only a valid URL', () => {
|
||||
assert.match(tools, /FileReader/);
|
||||
assert.match(tools, /commentUploadMaxSize/);
|
||||
assert.match(tools, /validateImage/);
|
||||
assert.match(tools, /XMLHttpRequest/);
|
||||
assert.match(tools, /xhr\.upload\.onprogress/);
|
||||
assert.match(tools, /formData\.append\('image'/);
|
||||
assert.match(tools, /response\.success === true/);
|
||||
assert.match(tools, /response\.data\.url/);
|
||||
assert.match(tools, /'\[img=' \+ url \+ '\]\\n'/);
|
||||
assert.doesNotMatch(tools, /formData\.append\(['"]file['"]/);
|
||||
assert.doesNotMatch(tools, /source_url/);
|
||||
assert.doesNotMatch(tools, /attachment_id/);
|
||||
assert.doesNotMatch(tools, /input-image-upload(?!-tab)/);
|
||||
});
|
||||
|
||||
test('comment upload REST endpoint has explicit nonce, switch, capability, and image-only guards', () => {
|
||||
assert.match(controller, /check_comment_image_upload_permission/);
|
||||
assert.match(controller, /wp_verify_nonce\(\$nonce, 'wp_rest'\)/);
|
||||
assert.match(controller, /\$settings\['comment_img'\]/);
|
||||
assert.match(controller, /\$settings\['comment_upload_img'\]/);
|
||||
assert.match(controller, /aksrt_user_can\('upload_comment_image'/);
|
||||
assert.match(controller, /empty\(\$_FILES\['image'\]\)/);
|
||||
assert.match(controller, /\$file_key = 'image'/);
|
||||
assert.match(controller, /wp_delete_attachment\(\(int\) \$attachment_id, true\)/);
|
||||
assert.match(controller, /'url' => \$url/);
|
||||
assert.doesNotMatch(controller, /\$_FILES\['file'\]/);
|
||||
assert.doesNotMatch(controller, /'attachment_id'\s*=>/);
|
||||
});
|
||||
|
||||
test('built comment assets carry the upload contract and no removed submit handler', () => {
|
||||
assert.match(commentsCss, /comment-image-upload/);
|
||||
assert.match(commentsCss, /progress-bar/);
|
||||
assert.doesNotMatch(runtimeBundle, /handleResponse/);
|
||||
});
|
||||
Reference in New Issue
Block a user