Files
comment/js/comment.js
2025-12-18 09:51:12 +05:00

432 lines
20 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* ====================================================================
ОБЕРТКА ДЛЯ ОЖИДАНИЯ JQUERY
==================================================================== */
(function waitForJQuery() {
if (typeof jQuery === 'undefined') {
setTimeout(waitForJQuery, 10);
} else {
(function($){
if (typeof aveabspath !== 'undefined') {
// aveabspath = 'https://bag.local/';
}
/* Limit symbols */
(function($){
$.fn.extend({
limit: function(limit, element){
var interval, f;
var self = $(this);
function substring(){
var val = $(self).val();
var length = val.length;
if(length > limit){
$(self).val($(self).val().substring(0,limit));
length = limit;
}
if(typeof element !== 'undefined'){
if($(element).html() != limit - length){
$(element).html((limit - length <= 0) ? '0' : limit - length);
}
}
}
$(this).focus(function(){
interval = window.setInterval(substring, 100);
});
$(this).blur(function(){
clearInterval(interval);
substring();
});
substring();
}
})
})(jQuery);
function getCaptha(){
var now = new Date();
$('#captcha img').attr('src', aveabspath + 'inc/captcha.php?cd=' + now.getTime());
}
function cAction(obj, action){
var cid;
if (action === 'open' || action === 'close') {
cid = DOC_ID;
} else {
var $link = $(obj).closest('a.mod_comment_answer');
cid = $link.attr('rel');
if (typeof cid === 'undefined' || cid === false || cid === '') {
cid = $(obj).parents('.mod_comment_box').attr('id');
}
}
if (typeof cid === 'undefined' || cid === false || cid === '') {
console.error("Comment ID not found for action: " + action);
return;
}
if (action === 'answer'){
$('#parent_id').val(cid);
$('#mod_comment_new').insertBefore('#end' + cid).show();
return;
}
if (UGROUP == 1){
$.get(aveabspath + 'index.php', {
module: 'comment',
action: action,
docid: DOC_ID,
Id: cid
}, function(){
if (action === 'delete'){
$(obj).parents('.mod_comment_comment').eq(0).remove();
}
if (action === 'open'){
var $openButton = $('#mod_comment_open');
$openButton.attr('id', 'mod_comment_close').html('<i class="bi bi-unlock-fill me-1"></i> ' + COMMENT_SITE_CLOSE);
$openButton.removeClass('btn-outline-success').addClass('btn-outline-danger');
}
if (action === 'close'){
var $closeButton = $('#mod_comment_close');
$closeButton.attr('id', 'mod_comment_open').html('<i class="bi bi-lock-fill me-1"></i> ' + COMMENT_SITE_OPEN);
$closeButton.removeClass('btn-outline-danger').addClass('btn-outline-success');
}
if (action === 'unlock'){
$(obj).removeClass('mod_comment_unlock text-success')
.addClass('mod_comment_lock text-dark')
.attr('title', COMMENT_LOCK_LINK)
.find('i')
.removeClass('bi-unlock-fill').addClass('bi-lock-fill');
}
if (action === 'lock'){
$(obj).removeClass('mod_comment_lock text-dark')
.addClass('mod_comment_unlock text-success')
.attr('title', COMMENT_UNLOCK_LINK)
.find('i')
.removeClass('bi-lock-fill').addClass('bi-unlock-fill');
}
});
}
}
function validate(formData, jqForm, options){
$('.alert').remove();
var form = jqForm ? jqForm[0] : $('#mod_comment_new form')[0];
if (form.comment_author_name && !form.comment_author_name.value){
alert(COMMENT_ERROR_AUTHOR);
$(form.comment_author_name).focus();
return false;
}
if (form.comment_author_email && !form.comment_author_email.value){
alert(COMMENT_ERROR_EMAIL);
$(form.comment_author_email).focus();
return false;
}
if (typeof REQ_F1 !== 'undefined' && REQ_F1 == '1') {
if (form.comment_author_website && !form.comment_author_website.value) {
alert("Пожалуйста, заполните поле: " + NAME_F1);
$(form.comment_author_website).focus();
return false;
}
}
if (typeof REQ_F2 !== 'undefined' && REQ_F2 == '1') {
if (form.comment_author_city && !form.comment_author_city.value) {
alert("Пожалуйста, заполните поле: " + NAME_F2);
$(form.comment_author_city).focus();
return false;
}
}
if (!form.comment_text || !form.comment_text.value){
alert(COMMENT_ERROR_TEXT);
if (form.comment_text) $(form.comment_text).focus();
return false;
}
if (IS_IM && form.securecode && !form.securecode.value){
alert(COMMENT_ERROR_CAPTCHA);
$(form.securecode).focus();
return false;
}
return true;
}
// Функция для создания формы редактирования
function createEditForm(cid, revert, targetElement) {
var currentImg = $('#' + cid).find('.mod_comment_attached_image img').attr('src');
var deletePhotoHtml = '';
if (currentImg) {
deletePhotoHtml = '<div class="form-check mb-2 mt-2">' +
'<input class="form-check-input" type="checkbox" id="del_img_' + cid + '" value="1">' +
'<label class="form-check-label text-danger small" for="del_img_' + cid + '">' +
'<i class="bi bi-trash me-1"></i>Удалить текущее фото</label>' +
'</div>';
}
// Блок для превью нового фото (добавлен класс edit-preview-img)
var editPreviewHtml = '<div id="edit_preview_wrapper_' + cid + '" class="d-none mt-2 mb-2">' +
'<img id="edit_preview_img_' + cid + '" src="#" class="img-thumbnail" style="max-height: 100px; object-fit: contain;">' +
'</div>';
// Поле для загрузки НОВОГО фото (добавлен класс edit-file-input и data-cid)
var uploadNewPhotoHtml = '<div class="mb-3 mt-2">' +
'<label class="form-label small fw-bold mb-1">Заменить или добавить фото:</label>' +
'<input type="file" id="new_file_' + cid + '" class="form-control form-control-sm edit-file-input" data-cid="' + cid + '" accept="image/*">' +
editPreviewHtml +
'</div>';
var textarea = '<p><textarea rows="7" id="ta_' + cid + '" class="editable form-control">' + revert + '</textarea></p>';
var charsLeft = '<p>' + COMMENT_CHARS_LEFT + ' <span class="charsLeft badge bg-secondary" id="charsLeft_' + cid + '"></span></p>';
var buttonSave = '<button type="button" class="btn btn-primary saveButton">' + COMMENT_BUTTON_EDIT + '</button> ';
var buttonReset = '<button type="button" class="btn btn-secondary cancelButton">' + COMMENT_BUTTON_CANCEL + '</button>';
targetElement.after(
'<div class="box"><div class="block" id="forms"><fieldset><legend class="h6">' + COMMENT_EDIT_TITLE
+ '</legend>' + textarea + deletePhotoHtml + uploadNewPhotoHtml + charsLeft + buttonSave + buttonReset + '</fieldset></div></div>'
).remove();
$('.saveButton').off('click').on('click', function(){saveChanges(this, false, cid);});
$('.cancelButton').off('click').on('click', function(){saveChanges(this, revert, cid);});
$('#ta_' + cid).limit(MAX_CHARS, '#charsLeft_' + cid);
}
function setClickable(){
$('.editable_text').off('click');
$('.editable_text').click(function(){
var $this = $(this);
var cid = $this.parents('.mod_comment_box').attr('id');
var revert = $this.html();
createEditForm(cid, revert, $this);
})
.attr('title', COMMENT_EDIT_LINK)
.mouseover(function(){$(this).addClass('editable');})
.mouseout(function(){$(this).removeClass('editable');});
$('#in_message').limit(MAX_CHARS, '#charsLeft_new');
}
function saveChanges(obj, cancel, cid){
var $box = $(obj).parents('.box');
if (!cancel){
var t = $box.find('#ta_' + cid).val();
var deleteImg = $('#del_img_' + cid).is(':checked') ? 1 : 0;
var fd = new FormData();
fd.append('module', 'comment');
fd.append('action', 'edit');
fd.append('Id', cid);
fd.append('text', t);
fd.append('delete_image', deleteImg);
var fileInput = $('#new_file_' + cid)[0];
if (fileInput && fileInput.files[0]) {
// Ключ 'comment_image' должен совпадать с PHP $_FILES['comment_image']
fd.append('comment_image', fileInput.files[0]);
}
$.ajax({
url: aveabspath + 'index.php?ajax=1',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function(txt){
// Если были операции с файлом, перезагружаем страницу
if (deleteImg == 1 || (fileInput && fileInput.files[0])) {
location.reload();
} else {
$box.after('<div class="mod_comment_text editable_text">' + txt + '</div>').remove();
var now = new Date();
var date = now.toLocaleString();
$('#' + cid).find('.mod_comment_changed').html(' (' + COMMENT_TEXT_CHANGED + ' ' + date + ')');
setClickable();
}
},
error: function(xhr, status, error) {
console.error("AJAX Error (Edit):", status, error);
alert("Ошибка при сохранении.");
}
});
}
else {
$box.after('<div class="mod_comment_text editable_text">' + cancel + '</div>').remove();
setClickable();
}
}
function displayNewComment(data){
if (data === 'wrong_securecode'){
$('#captcha').after('<div class="alert alert-danger">'+COMMENT_WRONG_CODE+'</div>');
$('#securecode').focus();
}
else {
$('#end' + $('#parent_id').val()).before(data);
$('#parent_id').val('');
$('#mod_comment_new form')[0].reset();
$('#image_preview_wrapper').addClass('d-none');
$('#image_preview_img').attr('src', '#');
$('#mod_comment_new').insertAfter('#end');
setClickable();
}
getCaptha();
}
$(document).ready(function(){
setClickable();
// ЛОГИКА ПРЕДПРОСМОТРА ДЛЯ ФОРМ РЕДАКТИРОВАНИЯ (Делегирование)
$(document).on('change', '.edit-file-input', function() {
var cid = $(this).data('cid');
var file = this.files[0];
var previewWrapper = $('#edit_preview_wrapper_' + cid);
var previewImg = $('#edit_preview_img_' + cid);
if (file) {
var reader = new FileReader();
reader.onload = function(e) {
previewImg.attr('src', e.target.result);
previewWrapper.removeClass('d-none');
}
reader.readAsDataURL(file);
} else {
previewWrapper.addClass('d-none');
}
});
// ЛОГИКА ПРЕДПРОСМОТРА ДЛЯ НОВОГО КОММЕНТАРИЯ
$(document).on('change', '#comment_image', function() {
const file = this.files[0];
const previewWrapper = $('#image_preview_wrapper');
const previewImg = $('#image_preview_img');
const errorDiv = $('#file_error');
if (errorDiv.length) errorDiv.addClass('d-none').text('');
if (file) {
if (file.size > 2 * 1024 * 1024) {
if (errorDiv.length) errorDiv.removeClass('d-none').text('Файл слишком большой (макс. 2Мб)');
this.value = '';
previewWrapper.addClass('d-none');
return;
}
const reader = new FileReader();
reader.onload = function(e) {
previewImg.attr('src', e.target.result);
previewWrapper.removeClass('d-none');
}
reader.readAsDataURL(file);
}
});
$(document).on('click', '#remove_image_btn', function() {
$('#comment_image').val('');
$('#image_preview_wrapper').addClass('d-none');
$('#image_preview_img').attr('src', '#');
});
$(document).on('click', '#captcha img', function(){getCaptha();});
$(document).on('click', '#reload_captcha', function(e){
e.preventDefault();
getCaptha();
});
$(document).on('click', '.mod_comment_answer', function(e){
e.preventDefault();
cAction(this, 'answer');
});
$(document).on('click', '.mod_comment_edit', function(e){
e.preventDefault();
var cid = $(this).parents('.mod_comment_box').attr('id');
var commentTextBlock = $('#' + cid).find('.mod_comment_text');
var revert = commentTextBlock.html();
createEditForm(cid, revert, commentTextBlock);
});
if (UGROUP == 1) {
$(document).on('click', '.mod_comment_delete', function(e){
e.preventDefault();
var $deleteButton = $(this);
var $modal = $('#deleteCommentModal');
$('#confirmDeleteButton').off('click').on('click', function() {
cAction($deleteButton[0], 'delete');
var modalInstance = bootstrap.Modal.getInstance($modal[0]) || new bootstrap.Modal($modal[0]);
modalInstance.hide();
});
var modal = new bootstrap.Modal($modal[0]);
modal.show();
});
$(document).on('click', '.mod_comment_lock', function(e){e.preventDefault(); cAction(this, 'lock');});
$(document).on('click', '.mod_comment_unlock', function(e){e.preventDefault(); cAction(this, 'unlock');});
$(document).on('click', '#mod_comment_open', function(e){e.preventDefault(); cAction(this, 'open');});
$(document).on('click', '#mod_comment_close', function(e){e.preventDefault(); cAction(this, 'close');});
}
$('#mod_comment_new form').on('submit', function(e){
e.preventDefault();
var form = $(this);
if (!validate(null, form, null)) return false;
var submitButton = form.find('input[type="submit"], button[type="submit"]').first();
var originalButtonText = submitButton.text();
var formData = new FormData(this);
$.ajax({
url: aveabspath + 'index.php?ajax=1',
type: 'POST',
data: formData,
processData: false,
contentType: false,
beforeSend: function() {
submitButton.prop('disabled', true).text('Отправка...');
},
success: function(data) {
displayNewComment(data);
submitButton.prop('disabled', false).text(originalButtonText);
},
error: function() {
alert("Ошибка при отправке.");
submitButton.prop('disabled', false).text(originalButtonText);
}
});
return false;
});
$('#buttonReset').click(function(){
$('#parent_id').val('');
$('#mod_comment_new form')[0].reset();
$('#image_preview_wrapper').addClass('d-none');
$('#mod_comment_new').insertAfter('#end');
});
});
})(jQuery);
}
})();