1555 lines
No EOL
73 KiB
PHP
1555 lines
No EOL
73 KiB
PHP
<?php
|
|
/**
|
|
* Ask question page
|
|
*
|
|
* @link https://anspress.net
|
|
* @since 0.1
|
|
*
|
|
* @package AnsPress
|
|
*/
|
|
|
|
if (!defined('ABSPATH')) {
|
|
exit;
|
|
}
|
|
|
|
?>
|
|
<div id="ap-ask-page" class="hesabix2-ap-ask clearfix">
|
|
<section class="ap-list-hero ap-hero-qa rounded-2xl mb-6 overflow-hidden">
|
|
<div class="relative z-10 px-4 sm:px-6 py-6 sm:py-8">
|
|
<a href="<?php echo esc_url( function_exists( 'hesabix2_anspress_base_url' ) ? hesabix2_anspress_base_url() : ap_get_link_to( '/' ) ); ?>" class="inline-flex items-center gap-2 text-slate-600 hover:text-brand-600 mb-4 font-medium transition-colors text-sm">
|
|
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
|
|
<span><?php esc_html_e( 'بازگشت به انجمن', 'hesabix2' ); ?></span>
|
|
</a>
|
|
<span class="ap-hero-badge">
|
|
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
|
|
<?php esc_html_e( 'سوال جدید', 'hesabix2' ); ?>
|
|
</span>
|
|
<h1 class="text-2xl sm:text-3xl font-extrabold text-slate-800 mb-2 tracking-tight">
|
|
<?php echo esc_html__( 'پرسیدن سوال جدید', 'anspress-question-answer' ); ?>
|
|
</h1>
|
|
<p class="text-slate-600 text-base max-w-2xl mb-0">
|
|
<?php echo esc_html__( 'سوال خود را مطرح کنید تا از تجربه دیگران استفاده کنید', 'anspress-question-answer' ); ?>
|
|
</p>
|
|
</div>
|
|
</section>
|
|
|
|
<div class="max-w-4xl mx-auto">
|
|
|
|
<div class="bg-white rounded-2xl shadow-sm overflow-hidden">
|
|
<div class="p-8">
|
|
<?php if (ap_user_can_ask()): ?>
|
|
<?php ap_ask_form(); ?>
|
|
<style>
|
|
#ap-ask-page form {
|
|
display: none
|
|
}
|
|
|
|
.ap-form-errors {
|
|
background: transparent !important;
|
|
border: none !important;
|
|
}
|
|
|
|
.ap-form-errors {
|
|
margin-top: 1rem;
|
|
margin-bottom: 1rem;
|
|
}
|
|
|
|
.ap-form-errors .ap-form-error {
|
|
display: flex;
|
|
align-items: flex-start;
|
|
padding: 0.75rem;
|
|
background: linear-gradient(to right, #fef2f2, #ffffff);
|
|
border: 1px solid #fecaca;
|
|
border-radius: 0.75rem;
|
|
font-size: 0.875rem;
|
|
color: #991b1b;
|
|
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
|
|
}
|
|
|
|
.ap-form-errors .ap-form-error::before {
|
|
content: '';
|
|
display: inline-block;
|
|
width: 1rem;
|
|
height: 1rem;
|
|
margin-right: 0.5rem;
|
|
margin-top: 0.125rem;
|
|
flex-shrink: 0;
|
|
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23ef4444'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z'%3E%3C/path%3E%3C/svg%3E");
|
|
background-size: contain;
|
|
background-repeat: no-repeat;
|
|
background-position: center;
|
|
}
|
|
</style>
|
|
<div id="ap-form-preloader" class="flex items-center justify-center py-16">
|
|
<div class="flex items-center space-x-3 space-x-reverse text-slate-500">
|
|
<svg class="animate-spin h-6 w-6 text-brand-600" viewBox="0 0 24 24">
|
|
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
|
|
stroke-width="4"></circle>
|
|
<path class="opacity-75" fill="currentColor"
|
|
d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
|
|
</svg>
|
|
<span
|
|
class="text-sm"><?php echo esc_html__('در حال آمادهسازی فرم...', 'anspress-question-answer'); ?></span>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="ap-custom-form-ui" class="space-y-8 relative">
|
|
<!-- Loading Overlay -->
|
|
<div id="ap-form-loading-overlay"
|
|
class="hidden absolute inset-0 bg-white bg-opacity-90 backdrop-blur-sm z-50 flex items-center justify-center rounded-2xl"
|
|
style="top: -1rem; left: -1rem; right: -1rem; bottom: -1rem; margin: 1rem;">
|
|
<div class="text-center">
|
|
<svg class="animate-spin h-12 w-12 text-brand-600 mx-auto mb-4" viewBox="0 0 24 24">
|
|
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
|
|
stroke-width="4"></circle>
|
|
<path class="opacity-75" fill="currentColor"
|
|
d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
|
|
</svg>
|
|
<p class="text-slate-700 font-medium">
|
|
<?php echo esc_html__('در حال ارسال سوال...', 'anspress-question-answer'); ?>
|
|
</p>
|
|
<p class="text-sm text-slate-500 mt-2">
|
|
<?php echo esc_html__('لطفاً صبر کنید', 'anspress-question-answer'); ?></p>
|
|
</div>
|
|
</div>
|
|
<div id="ap-title-block">
|
|
<label
|
|
class="block text-sm font-medium text-slate-700 mb-2"><?php echo esc_html__('عنوان سوال', 'anspress-question-answer'); ?></label>
|
|
<div id="ap-title-container"></div>
|
|
<div id="ap-title-errors" class="mt-2"></div>
|
|
<p class="mt-2 text-sm text-slate-600">
|
|
<?php echo esc_html__('عنوان سوال باید واضح و مختصر باشد. سعی کنید مشکل خود را در یک جمله خلاصه کنید.', 'anspress-question-answer'); ?>
|
|
</p>
|
|
</div>
|
|
|
|
<div id="ap-content-block">
|
|
<label
|
|
class="block text-sm font-medium text-slate-700 mb-2"><?php echo esc_html__('محتوای سوال', 'anspress-question-answer'); ?></label>
|
|
<!-- <div class="flex flex-wrap gap-2 p-3 bg-light-50 border border-slate-200 rounded-t-xl" id="ap-editor-toolbar">
|
|
<button type="button" data-cmd="bold" class="p-2 text-slate-600 hover:text-slate-800 hover:bg-light-200 rounded-lg transition-colors duration-200" title="<?php echo esc_attr__('پررنگ', 'anspress-question-answer'); ?>"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 4h8a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 12h9a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"></path></svg></button>
|
|
<button type="button" data-cmd="italic" class="p-2 text-slate-600 hover:text-slate-800 hover:bg-light-200 rounded-lg transition-colors duration-200" title="<?php echo esc_attr__('کج', 'anspress-question-answer'); ?>"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><line x1="19" y1="4" x2="10" y2="4"></line><line x1="14" y1="20" x2="5" y2="20"></line><line x1="15" y1="4" x2="9" y2="20"></line></svg></button>
|
|
<button type="button" data-cmd="code" class="p-2 text-slate-600 hover:text-slate-800 hover:bg-light-200 rounded-lg transition-colors duration-200" title="<?php echo esc_attr__('کد', 'anspress-question-answer'); ?>"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><polyline points="16,18 22,12 16,6"></polyline><polyline points="8,6 2,12 8,18"></polyline></svg></button>
|
|
<button type="button" id="ap-insert-list" class="p-2 text-slate-600 hover:text-slate-800 hover:bg-light-200 rounded-lg transition-colors duration-200" title="<?php echo esc_attr__('لیست', 'anspress-question-answer'); ?>"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><line x1="8" y1="6" x2="21" y2="6"></line><line x1="8" y1="12" x2="21" y2="12"></line><line x1="8" y1="18" x2="21" y2="18"></line><line x1="3" y1="6" x2="3.01" y2="6"></line><line x1="3" y1="12" x2="3.01" y2="12"></line><line x1="3" y1="18" x2="3.01" y2="18"></line></svg></button>
|
|
</div> -->
|
|
<div id="ap-content-container"
|
|
style="border: 1px solid #ccc; border-radius: 10px; padding: 10px;"></div>
|
|
<div id="ap-content-errors" class="mt-2"></div>
|
|
<p class="mt-2 text-sm text-slate-600">
|
|
<?php echo esc_html__('سوال خود را به تفصیل شرح دهید. هرچه جزئیات بیشتری ارائه دهید، پاسخهای بهتری دریافت خواهید کرد.', 'anspress-question-answer'); ?><br><span
|
|
class="text-slate-500"><?php echo esc_html__('میتوانید از دکمههای بالا برای فرمت کردن متن استفاده کنید.', 'anspress-question-answer'); ?></span>
|
|
</p>
|
|
</div>
|
|
|
|
<div id="ap-tags-block">
|
|
<label class="block text-sm font-medium text-slate-700 mb-2"><?php echo esc_html__('تگها', 'anspress-question-answer'); ?> <span class="text-red-500">*</span></label>
|
|
<div class="border border-slate-200 rounded-xl p-6 bg-gradient-to-br from-light-50 to-brand-500/10">
|
|
<div class="mb-6">
|
|
<div class="flex items-center justify-between mb-3">
|
|
<h4 class="text-sm font-semibold text-slate-700"><?php echo esc_html__('تگهای انتخاب شده', 'anspress-question-answer'); ?></h4>
|
|
<span class="text-xs text-slate-500" id="tag-count">0 <?php echo esc_html__('تگ انتخاب شده', 'anspress-question-answer'); ?></span>
|
|
</div>
|
|
<div class="selected-tags min-h-12 flex flex-wrap gap-2 p-3 bg-white rounded-lg border-2 border-dashed border-slate-200" id="selected-tags">
|
|
<div class="flex items-center text-slate-400 text-sm"><svg class="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg><?php echo esc_html__('هیچ تگی انتخاب نشده است', 'anspress-question-answer'); ?></div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="mb-6">
|
|
<div class="relative">
|
|
<input type="text" class="w-full px-4 py-3 pr-12 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-500 focus:border-transparent transition-all duration-200 text-sm" id="tag-input" placeholder="<?php echo esc_attr__('هر تگی که میخواهید را تایپ کنید...', 'anspress-question-answer'); ?>" autocomplete="off">
|
|
<button class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors duration-200" type="button" id="search-icon" aria-label="search">
|
|
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
|
|
</button>
|
|
<!-- Dropdown for suggestions -->
|
|
<div id="tag-suggestions-dropdown" class="hidden absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-xl shadow-lg max-h-60 overflow-y-auto">
|
|
<div id="tag-suggestions-list" class="py-2"></div>
|
|
</div>
|
|
</div>
|
|
<div class="flex items-center justify-between mt-3">
|
|
<button class="px-4 py-2 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-all duration-200 text-sm font-medium flex items-center space-x-2 space-x-reverse disabled:opacity-50 disabled:cursor-not-allowed" type="button" id="add-tag-btn">
|
|
<svg id="add-tag-icon" class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
|
|
<svg id="add-tag-spinner" class="hidden w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
|
|
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
|
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
|
</svg>
|
|
<span id="add-tag-text"><?php echo esc_html__('افزودن تگ', 'anspress-question-answer'); ?></span>
|
|
</button>
|
|
<span class="text-xs text-slate-500"><?php printf(esc_html__('حداقل %d و حداکثر %d تگ', 'anspress-question-answer'), (int) ap_opt('min_tags'), (int) ap_opt('max_tags')); ?></span>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<div class="flex items-center justify-between mb-3">
|
|
<h4 class="text-sm font-semibold text-slate-700"><?php echo esc_html__('تگهای محبوب', 'anspress-question-answer'); ?></h4>
|
|
<button class="text-xs text-brand-600 hover:text-brand-700 transition-colors duration-200" type="button" id="show-all-tags"><?php echo esc_html__('نمایش همه', 'anspress-question-answer'); ?></button>
|
|
</div>
|
|
<div class="flex flex-wrap gap-2" id="tag-suggestions">
|
|
<?php
|
|
$popular_tags = get_terms(array('taxonomy' => 'question_tag', 'orderby' => 'count', 'order' => 'DESC', 'number' => 30, 'hide_empty' => false));
|
|
if (!is_wp_error($popular_tags) && !empty($popular_tags)) {
|
|
foreach ($popular_tags as $t) {
|
|
echo '<button type="button" class="inline-flex items-center px-3 py-2 bg-white text-slate-700 text-sm font-medium rounded-full border border-slate-200 hover:bg-brand-500/10 hover:border-brand-400 hover:text-brand-700 cursor-pointer transition-all duration-200 tag-suggestion" data-tag-id="' . esc_attr($t->term_id) . '" data-tag-name="' . esc_attr($t->name) . '"><svg class="w-3 h-3 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>' . esc_html($t->name) . '</button>';
|
|
}
|
|
}
|
|
?>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div id="ap-tags-container" style="display: none;"></div>
|
|
<div id="ap-tags-errors" class="mt-2"></div>
|
|
<p class="mt-2 text-sm text-slate-600"><?php echo esc_html__('تگهای مرتبط را انتخاب کنید تا دیگران راحتتر بتوانند سوال شما را پیدا کنند.', 'anspress-question-answer'); ?><br><span class="text-slate-500"><?php echo esc_html__('میتوانید هر تگی را که میخواهید ایجاد کنید یا از تگهای موجود انتخاب کنید.', 'anspress-question-answer'); ?></span></p>
|
|
</div>
|
|
|
|
<!-- <div id="ap-notify-block" class="space-y-2">
|
|
<div class="flex items-center space-x-3 space-x-reverse">
|
|
<div id="ap-notify-container"></div>
|
|
<label class="text-sm font-medium text-slate-700"><?php echo esc_html__('اطلاعرسانی ایمیل هنگام دریافت پاسخ', 'anspress-question-answer'); ?></label>
|
|
</div>
|
|
<p class="mt-2 text-sm text-slate-600"><?php echo esc_html__('در صورت انتخاب، هنگام دریافت پاسخ ایمیل دریافت میکنید.', 'anspress-question-answer'); ?></p>
|
|
</div> -->
|
|
|
|
<div id="ap-private-block" class="space-y-2">
|
|
<div class="flex items-center space-x-3 space-x-reverse">
|
|
<div id="ap-private-container"></div>
|
|
<label
|
|
class="text-sm font-medium text-slate-700"><?php echo esc_html__('خصوصی باشد؟', 'anspress-question-answer'); ?></label>
|
|
</div>
|
|
<div id="ap-private-errors" class="mt-2"></div>
|
|
<p class="mt-2 text-sm text-slate-600">
|
|
<?php echo esc_html__('فقط برای مدیر و ناظر قابل مشاهده خواهد بود.', 'anspress-question-answer'); ?>
|
|
</p>
|
|
</div>
|
|
|
|
<div id="ap-files-block">
|
|
<label
|
|
class="block text-sm font-medium text-slate-700 mb-2"><?php echo esc_html__('پیوست فایل', 'anspress-question-answer'); ?>
|
|
<span
|
|
class="text-slate-500"><?php echo esc_html__('(اختیاری)', 'anspress-question-answer'); ?></span></label>
|
|
<div
|
|
class="border-2 border-dashed border-slate-200 rounded-xl p-6 bg-light-50 hover:bg-light-100 transition-colors duration-200">
|
|
<input type="file" id="ap-file-input" class="w-full" multiple />
|
|
<div class="mt-4 text-center text-slate-500 text-sm">
|
|
<span><?php echo esc_html__('فایلهای خود را اینجا بکشید یا کلیک کنید', 'anspress-question-answer'); ?></span>
|
|
<p class="text-xs text-slate-400 mt-2">
|
|
<?php echo esc_html__('فرمتهای مجاز: JPG, PNG, GIF, PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, TXT | حداکثر 3 فایل، هر کدام 4MB', 'anspress-question-answer'); ?>
|
|
</p>
|
|
</div>
|
|
<div id="selected-files" class="mt-4 hidden">
|
|
<h4 class="text-sm font-medium text-slate-700 mb-2">
|
|
<?php echo esc_html__('فایلهای انتخاب شده:', 'anspress-question-answer'); ?>
|
|
</h4>
|
|
<div id="file-list" class="space-y-2"></div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="flex justify-between items-center pt-6 border-t border-slate-200">
|
|
<a id="ap-custom-cancel" href="<?php echo esc_url(ap_get_link_to('base')); ?>"
|
|
class="inline-flex items-center space-x-2 space-x-reverse px-6 py-3 bg-light-100 text-slate-700 rounded-xl hover:bg-light-200 transition-all duration-200 font-medium">
|
|
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
|
d="M19 12H5"></path>
|
|
<polyline points="12,19 5,12 12,5"></polyline>
|
|
</svg>
|
|
<span><?php echo esc_html__('انصراف', 'anspress-question-answer'); ?></span>
|
|
</a>
|
|
<button id="ap-custom-submit" type="button"
|
|
class="inline-flex items-center space-x-2 space-x-reverse px-8 py-3 bg-brand-500 text-white rounded-xl hover:bg-brand-600 transition-all duration-200 font-medium shadow-lg hover:shadow-xl transform hover:-translate-y-0.5">
|
|
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
|
<line x1="22" y1="2" x2="11" y2="13"></line>
|
|
<polygon points="22,2 15,22 11,13 2,9 22,2"></polygon>
|
|
</svg>
|
|
<span><?php echo esc_html__('ارسال سوال', 'anspress-question-answer'); ?></span>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<?php elseif (is_user_logged_in()): ?>
|
|
<div class="ap-no-permission">
|
|
<?php esc_attr_e('You do not have permission to ask a question.', 'anspress-question-answer'); ?>
|
|
</div>
|
|
<?php endif; ?>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="bg-white rounded-2xl shadow-sm mt-8 overflow-hidden">
|
|
<div class="bg-gradient-to-r from-brand-500/10 to-light-50 px-8 py-6">
|
|
<h3 class="text-xl font-semibold text-slate-800 flex items-center">
|
|
<svg class="w-6 h-6 text-brand-600 ml-2" fill="none" stroke="currentColor"
|
|
viewBox="0 0 24 24" aria-hidden="true">
|
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4">
|
|
</path>
|
|
<path d="M21 12c.552 0 1-.448 1-1s-.448-1-1-1-1 .448-1 1 .448 1 1 1z"></path>
|
|
<path d="M3 12c.552 0 1-.448 1-1s-.448-1-1-1-1 .448-1 1 .448 1 1 1z"></path>
|
|
<path d="M12 3c.552 0 1-.448 1-1s-.448-1-1-1-1 .448-1 1 .448 1 1 1z"></path>
|
|
<path d="M12 21c.552 0 1-.448 1-1s-.448-1-1-1-1 .448-1 1 .448 1 1 1z"></path>
|
|
</svg>
|
|
<?php echo esc_html__('راهنمای پرسیدن سوال خوب', 'anspress-question-answer'); ?>
|
|
</h3>
|
|
</div>
|
|
<div class="p-8">
|
|
<div class="grid grid-cols-1 md:grid-cols-2 gap-8">
|
|
<div>
|
|
<h4 class="text-lg font-semibold text-green-700 mb-4 flex items-center">
|
|
<svg class="w-5 h-5 text-green-600 ml-2" fill="none" stroke="currentColor"
|
|
viewBox="0 0 24 24" aria-hidden="true">
|
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
|
d="M5 13l4 4L19 7"></path>
|
|
</svg>
|
|
<?php echo esc_html__('کارهای درست', 'anspress-question-answer'); ?>
|
|
</h4>
|
|
<ul class="space-y-3">
|
|
<li class="flex items-center space-x-3 space-x-reverse"><svg
|
|
class="w-5 h-5 text-green-500" fill="none" stroke="currentColor"
|
|
viewBox="0 0 24 24" aria-hidden="true">
|
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
|
d="M5 13l4 4L19 7"></path>
|
|
</svg><span
|
|
class="text-slate-700"><?php echo esc_html__('عنوان واضح و مختصر', 'anspress-question-answer'); ?></span>
|
|
</li>
|
|
<li class="flex items-center space-x-3 space-x-reverse"><svg
|
|
class="w-5 h-5 text-green-500" fill="none" stroke="currentColor"
|
|
viewBox="0 0 24 24" aria-hidden="true">
|
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
|
d="M5 13l4 4L19 7"></path>
|
|
</svg><span
|
|
class="text-slate-700"><?php echo esc_html__('شرح کامل مشکل', 'anspress-question-answer'); ?></span>
|
|
</li>
|
|
<li class="flex items-center space-x-3 space-x-reverse"><svg
|
|
class="w-5 h-5 text-green-500" fill="none" stroke="currentColor"
|
|
viewBox="0 0 24 24" aria-hidden="true">
|
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
|
d="M5 13l4 4L19 7"></path>
|
|
</svg><span
|
|
class="text-slate-700"><?php echo esc_html__('انتخاب تگهای مناسب', 'anspress-question-answer'); ?></span>
|
|
</li>
|
|
<li class="flex items-center space-x-3 space-x-reverse"><svg
|
|
class="w-5 h-5 text-green-500" fill="none" stroke="currentColor"
|
|
viewBox="0 0 24 24" aria-hidden="true">
|
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
|
d="M5 13l4 4L19 7"></path>
|
|
</svg><span
|
|
class="text-slate-700"><?php echo esc_html__('استفاده از کلمات کلیدی', 'anspress-question-answer'); ?></span>
|
|
</li>
|
|
</ul>
|
|
</div>
|
|
<div>
|
|
<h4 class="text-lg font-semibold text-red-700 mb-4 flex items-center">
|
|
<svg class="w-5 h-5 text-red-600 ml-2" fill="none" stroke="currentColor"
|
|
viewBox="0 0 24 24" aria-hidden="true">
|
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
|
d="M6 18L18 6M6 6l12 12"></path>
|
|
</svg>
|
|
<?php echo esc_html__('کارهای نادرست', 'anspress-question-answer'); ?>
|
|
</h4>
|
|
<ul class="space-y-3">
|
|
<li class="flex items-center space-x-3 space-x-reverse"><svg
|
|
class="w-5 h-5 text-red-500" fill="none" stroke="currentColor"
|
|
viewBox="0 0 24 24" aria-hidden="true">
|
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
|
d="M6 18L18 6M6 6l12 12"></path>
|
|
</svg><span
|
|
class="text-slate-700"><?php echo esc_html__('عنوان مبهم', 'anspress-question-answer'); ?></span>
|
|
</li>
|
|
<li class="flex items-center space-x-3 space-x-reverse"><svg
|
|
class="w-5 h-5 text-red-500" fill="none" stroke="currentColor"
|
|
viewBox="0 0 24 24" aria-hidden="true">
|
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
|
d="M6 18L18 6M6 6l12 12"></path>
|
|
</svg><span
|
|
class="text-slate-700"><?php echo esc_html__('شرح ناکافی', 'anspress-question-answer'); ?></span>
|
|
</li>
|
|
<li class="flex items-center space-x-3 space-x-reverse"><svg
|
|
class="w-5 h-5 text-red-500" fill="none" stroke="currentColor"
|
|
viewBox="0 0 24 24" aria-hidden="true">
|
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
|
d="M6 18L18 6M6 6l12 12"></path>
|
|
</svg><span
|
|
class="text-slate-700"><?php echo esc_html__('عدم انتخاب تگ', 'anspress-question-answer'); ?></span>
|
|
</li>
|
|
<li class="flex items-center space-x-3 space-x-reverse"><svg
|
|
class="w-5 h-5 text-red-500" fill="none" stroke="currentColor"
|
|
viewBox="0 0 24 24" aria-hidden="true">
|
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
|
d="M6 18L18 6M6 6l12 12"></path>
|
|
</svg><span
|
|
class="text-slate-700"><?php echo esc_html__('سوال تکراری', 'anspress-question-answer'); ?></span>
|
|
</li>
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<?php ap_get_template_part( 'login-signup' ); ?>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
(function () {
|
|
function qs(sel, ctx) { return (ctx || document).querySelector(sel); }
|
|
function qsa(sel, ctx) { return Array.prototype.slice.call((ctx || document).querySelectorAll(sel)); }
|
|
function byNameEndsWith(suffix) { return qs('form [name$="' + suffix + '"]'); }
|
|
|
|
function moveFieldToContainer(field, containerId) {
|
|
var c = qs('#' + containerId);
|
|
if (field && c) {
|
|
// Store original name if not already stored
|
|
if (!field.hasAttribute('data-original-name') && field.name) {
|
|
field.setAttribute('data-original-name', field.name);
|
|
}
|
|
|
|
// Ensure field stays in form context
|
|
var form = qs('#ap-ask-page form');
|
|
if (form && !form.contains(field)) {
|
|
form.appendChild(field);
|
|
}
|
|
|
|
c.innerHTML = '';
|
|
c.appendChild(field);
|
|
|
|
// Ensure name and value are preserved
|
|
if (!field.hasAttribute('name')) {
|
|
var name = field.getAttribute('data-original-name');
|
|
if (name) { field.setAttribute('name', name); }
|
|
}
|
|
|
|
// Ensure field.form property points to the form
|
|
if (field.form !== form) {
|
|
// Force update form reference
|
|
var formInput = document.createElement('input');
|
|
formInput.type = 'hidden';
|
|
formInput.name = field.name || '';
|
|
formInput.value = field.value || '';
|
|
if (field.type === 'checkbox') {
|
|
formInput.type = 'checkbox';
|
|
formInput.checked = field.checked;
|
|
}
|
|
form.appendChild(formInput);
|
|
formInput.remove();
|
|
}
|
|
}
|
|
}
|
|
|
|
function enhanceForm() {
|
|
var form = qs('#ap-ask-page form');
|
|
if (!form) { return; }
|
|
form.setAttribute('novalidate', 'novalidate');
|
|
form.setAttribute('data-turbo', 'false');
|
|
form.setAttribute('enctype', 'multipart/form-data');
|
|
form.classList.add('space-y-8');
|
|
|
|
// Ensure form has apform attribute for AnsPress AJAX handling
|
|
if (!form.hasAttribute('apform')) {
|
|
form.setAttribute('apform', 'question');
|
|
}
|
|
|
|
// Move custom UI containers INSIDE form to keep fields in form context
|
|
var customUI = qs('#ap-custom-form-ui');
|
|
if (customUI) {
|
|
// Always ensure customUI is inside form
|
|
if (customUI.parentNode !== form) {
|
|
form.appendChild(customUI);
|
|
}
|
|
// Make sure customUI stays inside form even if moved
|
|
var observer = new MutationObserver(function (mutations) {
|
|
if (customUI.parentNode !== form && form.parentNode) {
|
|
form.appendChild(customUI);
|
|
}
|
|
});
|
|
observer.observe(document.body, { childList: true, subtree: true });
|
|
}
|
|
|
|
// Reveal form and hide preloader AS EARLY AS POSSIBLE to avoid being blocked by later JS
|
|
var preEarly = qs('#ap-form-preloader');
|
|
form.style.display = 'block';
|
|
if (preEarly) { preEarly.style.display = 'none'; }
|
|
|
|
function hideOriginalWrapper(field) {
|
|
if (!field) return;
|
|
// hide label linked to this field
|
|
var lid = field.getAttribute('id');
|
|
if (lid) { qsa('label[for="' + lid + '"]', form).forEach(function (l) { l.style.display = 'none'; }); }
|
|
// hide common wrappers
|
|
var wrap = field.closest('.ap-field, .ap-form-group, .ap-form-row, .ap-field-wrap, .ap-input');
|
|
if (wrap) { wrap.style.display = 'none'; return; }
|
|
// as fallback hide parent
|
|
if (field.parentElement) { field.parentElement.style.display = 'none'; }
|
|
}
|
|
|
|
function extractAndShowErrors(field, errorContainerId) {
|
|
if (!field) return;
|
|
var wrap = field.closest('.ap-field, .ap-form-group');
|
|
if (!wrap) return;
|
|
var errorsCont = qs('#' + errorContainerId);
|
|
if (!errorsCont) return;
|
|
// Find errors container - could be .ap-field-errors or direct .ap-field-error
|
|
var errorsBox = wrap.querySelector('.ap-field-errors, .ap-field-errorsc');
|
|
var errors = [];
|
|
if (errorsBox) {
|
|
errors = qsa('.ap-field-error', errorsBox);
|
|
} else {
|
|
// Try direct error elements
|
|
errors = qsa('.ap-field-error', wrap);
|
|
}
|
|
if (errors.length === 0) return;
|
|
errorsCont.innerHTML = '';
|
|
errors.forEach(function (err) {
|
|
var errMsg = err.textContent.trim();
|
|
if (!errMsg) return;
|
|
var errDiv = document.createElement('div');
|
|
errDiv.className = 'p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700 flex items-start';
|
|
errDiv.innerHTML = '<svg class="w-4 h-4 text-red-500 ml-2 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg><span>' + errMsg + '</span>';
|
|
errorsCont.appendChild(errDiv);
|
|
});
|
|
}
|
|
|
|
var title = byNameEndsWith('[post_title]');
|
|
if (title) {
|
|
extractAndShowErrors(title, 'ap-title-errors');
|
|
title.className = 'w-full px-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-500 focus:border-transparent transition-all duration-200';
|
|
hideOriginalWrapper(title);
|
|
moveFieldToContainer(title, 'ap-title-container');
|
|
}
|
|
|
|
var content = byNameEndsWith('[post_content]');
|
|
if (content) {
|
|
extractAndShowErrors(content, 'ap-content-errors');
|
|
content.className = 'w-full px-4 py-3 border border-slate-200 border-t-0 rounded-b-xl focus:ring-2 focus:ring-brand-500 focus:border-transparent transition-all duration-200';
|
|
hideOriginalWrapper(content);
|
|
moveFieldToContainer(content, 'ap-content-container');
|
|
}
|
|
|
|
var notify = byNameEndsWith('[notify_on_answer]');
|
|
if (notify) { notify.classList.add('form-check-input'); hideOriginalWrapper(notify); moveFieldToContainer(notify, 'ap-notify-container'); }
|
|
|
|
// Move and restyle private checkbox
|
|
var isPrivate = byNameEndsWith('[is_private]');
|
|
if (isPrivate) {
|
|
extractAndShowErrors(isPrivate, 'ap-private-errors');
|
|
isPrivate.classList.add('form-check-input');
|
|
hideOriginalWrapper(isPrivate);
|
|
moveFieldToContainer(isPrivate, 'ap-private-container');
|
|
}
|
|
|
|
// Handle tags field - hide AnsPress selectize tags input since we have custom UI
|
|
// Wait for Selectize to initialize
|
|
function moveTagsField() {
|
|
var tagsField = qs('input[name*="[tags]"].ap-tags-input, input[id*="[tags]"].ap-tags-input');
|
|
var tagsWrapper = qs('.ap-field-form_question-tags, .ap-form-group.ap-field-form_question-tags');
|
|
|
|
// Hide AnsPress tags field and wrapper since we have custom UI
|
|
if (tagsWrapper) {
|
|
tagsWrapper.style.display = 'none';
|
|
var originalLabel = tagsWrapper.querySelector('.ap-form-label');
|
|
if (originalLabel) { originalLabel.style.display = 'none'; }
|
|
|
|
// Extract and show errors from AnsPress field to our custom error container
|
|
if (tagsField) {
|
|
extractAndShowErrors(tagsField, 'ap-tags-errors');
|
|
}
|
|
}
|
|
|
|
if (tagsField) {
|
|
// Keep field in form but hidden
|
|
tagsField.style.display = 'none';
|
|
// Ensure the field stays in form context
|
|
if (form && !form.contains(tagsField)) {
|
|
form.appendChild(tagsField);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Try immediately and also after a delay for Selectize initialization
|
|
moveTagsField();
|
|
setTimeout(moveTagsField, 300);
|
|
setTimeout(moveTagsField, 1000);
|
|
|
|
// Keep select fallback hidden as backup (will be synced with our custom UI)
|
|
var tagsSelect = qs('select[id*="tags"], select[name$="[tags][]"]');
|
|
if (tagsSelect) { tagsSelect.classList.add('hidden'); tagsSelect.multiple = true; }
|
|
|
|
// Ensure action hidden field exists for form processing
|
|
var actionField = form.querySelector('input[name="action"]');
|
|
if (!actionField) {
|
|
var hiddenAction = document.createElement('input');
|
|
hiddenAction.type = 'hidden';
|
|
hiddenAction.name = 'action';
|
|
hiddenAction.value = 'ap_form_question';
|
|
form.appendChild(hiddenAction);
|
|
}
|
|
|
|
// Hide default plugin submit and extra labels/descs
|
|
var defaultSubmit = form.querySelector('button[type="submit"], input[type="submit"]');
|
|
if (defaultSubmit) { defaultSubmit.style.display = 'none'; var ps = defaultSubmit.closest('.ap-form-submit, .ap-field, .ap-form-group'); if (ps) { ps.style.display = 'none'; } }
|
|
qsa('.ap-field-label, .ap-field-desc, .ap-label, .ap-description', form).forEach(function (el) { el.style.display = 'none'; });
|
|
|
|
// Function to collect all form data manually
|
|
function collectFormData() {
|
|
var formData = new FormData();
|
|
|
|
// Save TinyMCE content to textarea before collecting
|
|
if (typeof tinymce !== 'undefined') {
|
|
tinymce.triggerSave();
|
|
}
|
|
|
|
// Collect title field - check both in form and in containers
|
|
var titleField = qs('input[name*="[post_title]"], textarea[name*="[post_title]"]', form) ||
|
|
qs('input[name*="[post_title]"], textarea[name*="[post_title]"]');
|
|
if (titleField) {
|
|
var fieldName = titleField.name || 'form_question[post_title]';
|
|
var titleValue = titleField.value || '';
|
|
formData.append(fieldName, titleValue);
|
|
}
|
|
|
|
// Collect content field - check both in form and in containers
|
|
// First check for TinyMCE instance
|
|
var contentField = null;
|
|
var contentValue = '';
|
|
|
|
if (typeof tinymce !== 'undefined') {
|
|
// Find TinyMCE editor instance for content field
|
|
var contentFieldId = null;
|
|
var tempField = qs('textarea[name*="[post_content]"], input[name*="[post_content]"]', form) ||
|
|
qs('textarea[name*="[post_content]"], input[name*="[post_content]"]');
|
|
if (tempField && tempField.id) {
|
|
contentFieldId = tempField.id;
|
|
}
|
|
|
|
// Get content from TinyMCE if available
|
|
if (contentFieldId && tinymce.get(contentFieldId)) {
|
|
contentValue = tinymce.get(contentFieldId).getContent();
|
|
contentField = tempField;
|
|
} else {
|
|
// Check all TinyMCE instances
|
|
tinymce.each(function(editor) {
|
|
var editorId = editor.id || '';
|
|
var editorElement = editor.getElement();
|
|
if (editorElement && (editorElement.name && editorElement.name.indexOf('[post_content]') !== -1)) {
|
|
contentValue = editor.getContent();
|
|
contentField = editorElement;
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
// Fallback to textarea if TinyMCE not available or didn't find content
|
|
if (!contentField || !contentValue) {
|
|
contentField = qs('textarea[name*="[post_content]"], input[name*="[post_content]"]', form) ||
|
|
qs('textarea[name*="[post_content]"], input[name*="[post_content]"]');
|
|
if (contentField) {
|
|
contentValue = contentField.value || '';
|
|
}
|
|
}
|
|
|
|
if (contentField) {
|
|
var fieldName = contentField.name || 'form_question[post_content]';
|
|
formData.append(fieldName, contentValue);
|
|
}
|
|
|
|
// Collect is_private checkbox
|
|
var isPrivateField = qs('input[name*="[is_private]"]', form) || qs('input[name*="[is_private]"]');
|
|
if (isPrivateField) {
|
|
var fieldName = isPrivateField.name || 'form_question[is_private]';
|
|
if (isPrivateField.checked) {
|
|
formData.append(fieldName, '1');
|
|
}
|
|
}
|
|
|
|
// Collect notify_on_answer checkbox
|
|
var notifyField = qs('input[name*="[notify_on_answer]"]', form) || qs('input[name*="[notify_on_answer]"]');
|
|
if (notifyField) {
|
|
var fieldName = notifyField.name || 'form_question[notify_on_answer]';
|
|
if (notifyField.checked) {
|
|
formData.append(fieldName, '1');
|
|
}
|
|
}
|
|
|
|
// Collect tags - first check our custom UI selected array
|
|
var tagsCollected = false;
|
|
|
|
// Method 1: Get from custom UI selected array (most reliable for our custom UI)
|
|
if (typeof selected !== 'undefined' && Array.isArray(selected) && selected.length > 0) {
|
|
var tagsSelect = qs('select[name*="[tags]"]', form) || qs('select[name*="[tags]"]');
|
|
var fieldName = 'form_question[tags]';
|
|
if (tagsSelect && tagsSelect.name) {
|
|
fieldName = tagsSelect.name;
|
|
}
|
|
|
|
selected.forEach(function(tag) {
|
|
if (tag && tag.id) {
|
|
// If id is a slug (not numeric), try to find real id from popular tags
|
|
var tagId = tag.id;
|
|
if (isNaN(parseInt(tagId))) {
|
|
var popularTag = qs('#tag-suggestions .tag-suggestion[data-tag-name="' + tag.name + '"]');
|
|
if (popularTag) {
|
|
tagId = popularTag.getAttribute('data-tag-id');
|
|
}
|
|
}
|
|
formData.append(fieldName, tagId);
|
|
tagsCollected = true;
|
|
}
|
|
});
|
|
}
|
|
|
|
// Method 2: Get from select dropdown (synced by syncSelect function)
|
|
if (!tagsCollected) {
|
|
var tagsSelect = qs('select[name*="[tags]"]', form) || qs('select[name*="[tags]"]');
|
|
if (tagsSelect) {
|
|
var fieldName = tagsSelect.name || 'form_question[tags][]';
|
|
var selectedTags = Array.from(tagsSelect.selectedOptions);
|
|
selectedTags.forEach(function(option) {
|
|
if (option.value) {
|
|
formData.append(fieldName, option.value);
|
|
tagsCollected = true;
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
// Method 3: Fallback to AnsPress selectize input
|
|
if (!tagsCollected) {
|
|
var tagsInput = qs('input[name*="[tags]"].ap-tags-input, input[id*="tags"].ap-tags-input', form) ||
|
|
qs('input[name*="[tags]"].ap-tags-input, input[id*="tags"].ap-tags-input');
|
|
|
|
if (typeof jQuery !== 'undefined' && tagsInput) {
|
|
var $tagsInput = jQuery(tagsInput);
|
|
var selectizeInstance = null;
|
|
|
|
// Try different methods to get Selectize instance
|
|
if ($tagsInput[0] && $tagsInput[0].selectize) {
|
|
selectizeInstance = $tagsInput[0].selectize;
|
|
} else if ($tagsInput.data('selectize')) {
|
|
selectizeInstance = $tagsInput.data('selectize');
|
|
} else {
|
|
// Try to get from Selectize control wrapper
|
|
var selectizeControl = $tagsInput.closest('.selectize-control');
|
|
if (selectizeControl.length > 0) {
|
|
var controlEl = selectizeControl[0];
|
|
if (controlEl.selectize) {
|
|
selectizeInstance = controlEl.selectize;
|
|
} else {
|
|
// Try jQuery method
|
|
var selectizeData = jQuery.data(controlEl, 'selectize');
|
|
if (selectizeData) {
|
|
selectizeInstance = selectizeData;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (selectizeInstance && selectizeInstance.items && selectizeInstance.items.length > 0) {
|
|
var fieldName = tagsInput.name || 'form_question[tags]';
|
|
selectizeInstance.items.forEach(function(item) {
|
|
if (item) {
|
|
formData.append(fieldName, item);
|
|
tagsCollected = true;
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
// Method 4: Get from input value (comma-separated)
|
|
if (!tagsCollected && tagsInput && tagsInput.value) {
|
|
var tagsValue = tagsInput.value.trim();
|
|
if (tagsValue) {
|
|
var tagsArray = tagsValue.split(',').map(function(t) { return t.trim(); }).filter(function(t) { return t; });
|
|
var fieldName = tagsInput.name || 'form_question[tags]';
|
|
|
|
// AnsPress expects tags as array, so append each tag separately
|
|
tagsArray.forEach(function(tag) {
|
|
if (tag) {
|
|
formData.append(fieldName, tag);
|
|
tagsCollected = true;
|
|
}
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// Collect files - make sure selectedFiles is accessible
|
|
// First check window.selectedFiles (set from file manager)
|
|
if (typeof window.selectedFiles !== 'undefined' && window.selectedFiles && window.selectedFiles.length > 0) {
|
|
window.selectedFiles.forEach(function(file) {
|
|
if (file instanceof File) {
|
|
formData.append('ap_attachments[]', file);
|
|
}
|
|
});
|
|
}
|
|
|
|
// Also check for file input in form (fallback)
|
|
var fileInputs = form.querySelectorAll('input[type="file"][name*="attachments"], input[type="file"][name*="ap_attachments"]');
|
|
fileInputs.forEach(function(fileInput) {
|
|
if (fileInput.files && fileInput.files.length > 0) {
|
|
for (var i = 0; i < fileInput.files.length; i++) {
|
|
formData.append(fileInput.name || 'ap_attachments[]', fileInput.files[i]);
|
|
}
|
|
}
|
|
});
|
|
|
|
// Collect ALL hidden fields from form (including nonce, form_name, etc.)
|
|
var hiddenFields = form.querySelectorAll('input[type="hidden"]');
|
|
hiddenFields.forEach(function(field) {
|
|
if (field.name && field.value !== null && field.value !== '') {
|
|
// Don't duplicate if already added
|
|
if (!formData.has(field.name)) {
|
|
formData.append(field.name, field.value);
|
|
}
|
|
}
|
|
});
|
|
|
|
// Also check for hidden fields outside form (in case they were moved)
|
|
var allHiddenFields = document.querySelectorAll('input[type="hidden"]');
|
|
allHiddenFields.forEach(function(field) {
|
|
var fieldName = field.name || '';
|
|
// Only add AnsPress related hidden fields
|
|
if (fieldName && (fieldName.indexOf('ap_') === 0 || fieldName.indexOf('form_question') === 0 || fieldName.indexOf('_nonce') !== -1)) {
|
|
if (!formData.has(fieldName) && field.value !== null && field.value !== '') {
|
|
formData.append(fieldName, field.value);
|
|
}
|
|
}
|
|
});
|
|
|
|
// Ensure action is set
|
|
if (!formData.has('action')) {
|
|
formData.append('action', 'ap_form_question');
|
|
}
|
|
|
|
// Debug: Log collected data
|
|
if (console && console.log) {
|
|
console.log('=== Collected form data ===');
|
|
for (var pair of formData.entries()) {
|
|
console.log(pair[0] + ': ' + (pair[1] instanceof File ? pair[1].name + ' (' + pair[1].size + ' bytes)' : pair[1]));
|
|
}
|
|
console.log('window.selectedFiles:', window.selectedFiles);
|
|
console.log('TinyMCE available:', typeof tinymce !== 'undefined');
|
|
console.log('========================');
|
|
}
|
|
|
|
return formData;
|
|
}
|
|
|
|
// Wire custom submit button
|
|
var customSubmit = qs('#ap-custom-submit');
|
|
if (customSubmit) {
|
|
customSubmit.addEventListener('click', function (e) {
|
|
e.preventDefault();
|
|
|
|
// trigger validation similar to submit handler
|
|
if (hasTagUI && selected.length < minTags) {
|
|
var old = qs('.tag-validation-error'); if (old) old.remove();
|
|
var err = document.createElement('div'); err.className = 'tag-validation-error mt-4 p-4 bg-gradient-to-r from-red-50 to-white border border-red-200 rounded-xl shadow-lg';
|
|
err.innerHTML = '\
|
|
<div class="flex items-start">\
|
|
<div class="flex-shrink-0"><svg class="w-6 h-6 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg></div>\
|
|
<div class="ml-3">\
|
|
<h3 class="text-sm font-semibold text-red-800"><?php echo esc_html__('خطا در اعتبارسنجی', 'anspress-question-answer'); ?></h3>\
|
|
<div class="mt-1 text-sm text-red-700"><?php echo esc_html(sprintf(__('حداقل %d تگ باید انتخاب کنید', 'anspress-question-answer'), (int) ap_opt('min_tags'))); ?></div>\
|
|
</div>\
|
|
<button type="button" class="ml-auto text-red-400 hover:text-red-600" aria-label="dismiss"><svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></button>\
|
|
</div>';
|
|
var btnWrap = customSubmit.parentNode; if (btnWrap) { btnWrap.insertBefore(err, customSubmit); }
|
|
var dis = err.querySelector('[aria-label="dismiss"]'); if (dis) { dis.addEventListener('click', function () { if (err && err.parentNode) { err.parentNode.removeChild(err); } }); }
|
|
setTimeout(function () { if (err && err.parentNode) { err.parentNode.removeChild(err); } }, 5000);
|
|
return;
|
|
}
|
|
|
|
// Sync tags to select before collecting data
|
|
if (hasTagUI) { syncSelect(); }
|
|
|
|
// Sync files to input before collecting data
|
|
if (typeof syncFilesToInput === 'function') {
|
|
syncFilesToInput();
|
|
}
|
|
|
|
// Show loading overlay and disable form
|
|
showFormLoading();
|
|
|
|
// Collect all form data manually
|
|
var formData = collectFormData();
|
|
|
|
// Ensure ajaxurl is defined
|
|
var ajaxUrl = (typeof ajaxurl !== 'undefined' && ajaxurl) ? ajaxurl : '<?php echo esc_url(admin_url("admin-ajax.php")); ?>';
|
|
|
|
// Send AJAX request manually
|
|
fetch(ajaxUrl, {
|
|
method: 'POST',
|
|
body: formData,
|
|
credentials: 'include'
|
|
})
|
|
.then(function(response) {
|
|
return response.json();
|
|
})
|
|
.then(function(data) {
|
|
// Hide loading overlay
|
|
hideFormLoading();
|
|
|
|
// Handle response similar to AnsPress handler
|
|
if (data.snackbar) {
|
|
if (typeof AnsPress !== 'undefined' && typeof AnsPress.trigger === 'function') {
|
|
AnsPress.trigger('snackbar', data);
|
|
}
|
|
}
|
|
|
|
if (typeof AnsPress !== 'undefined' && typeof AnsPress.trigger === 'function') {
|
|
AnsPress.trigger('formPosted', data);
|
|
}
|
|
|
|
if (data.form_errors) {
|
|
var $form = jQuery(form);
|
|
var $formError = jQuery('<div class="ap-form-errors"></div>').prependTo($form);
|
|
|
|
jQuery.each(data.form_errors, function (i, err) {
|
|
$formError.append('<span class="ap-form-error ecode-' + i + '">' + err + '</div>');
|
|
});
|
|
|
|
jQuery.each(data.fields_errors, function (i, errs) {
|
|
jQuery('.ap-field-' + i).addClass('ap-have-errors');
|
|
jQuery('.ap-field-' + i).find('.ap-field-errorsc').html('<div class="ap-field-errors"></div>');
|
|
|
|
jQuery.each(errs.error, function (code, err) {
|
|
jQuery('.ap-field-' + i).find('.ap-field-errors').append('<span class="ap-field-error ecode-' + code + '">' + err + '</span>');
|
|
});
|
|
});
|
|
|
|
// Show field-specific errors
|
|
if (data.fields_errors) {
|
|
for (var fieldName in data.fields_errors) {
|
|
var errors = data.fields_errors[fieldName];
|
|
var errorContainer = null;
|
|
|
|
if (fieldName.indexOf('post_title') !== -1) {
|
|
errorContainer = qs('#ap-title-errors');
|
|
} else if (fieldName.indexOf('post_content') !== -1) {
|
|
errorContainer = qs('#ap-content-errors');
|
|
} else if (fieldName.indexOf('is_private') !== -1) {
|
|
errorContainer = qs('#ap-private-errors');
|
|
} else if (fieldName.indexOf('tags') !== -1) {
|
|
errorContainer = qs('#ap-tags-errors');
|
|
}
|
|
|
|
if (errorContainer && errors.error) {
|
|
errorContainer.innerHTML = '';
|
|
for (var code in errors.error) {
|
|
var errMsg = errors.error[code];
|
|
var errDiv = document.createElement('div');
|
|
errDiv.className = 'p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700 flex items-start';
|
|
errDiv.innerHTML = '<svg class="w-4 h-4 text-red-500 ml-2 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg><span>' + errMsg + '</span>';
|
|
errorContainer.appendChild(errDiv);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Scroll to first error
|
|
var firstError = qs('#ap-title-errors div, #ap-content-errors div, #ap-private-errors div, #ap-tags-errors div, .ap-form-errors');
|
|
if (firstError) {
|
|
firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
|
}
|
|
} else if (data.redirect) {
|
|
window.location = data.redirect;
|
|
}
|
|
})
|
|
.catch(function(error) {
|
|
console.error('Error submitting form:', error);
|
|
hideFormLoading();
|
|
|
|
if (typeof AnsPress !== 'undefined' && typeof AnsPress.trigger === 'function' && typeof aplang !== 'undefined' && aplang.ajax_error && aplang.ajax_error.snackbar) {
|
|
AnsPress.trigger('snackbar', aplang.ajax_error);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
// Editor toolbar actions (for plain textarea) — safe if toolbar removed
|
|
function format(command) { if (!content) return; var start = content.selectionStart, end = content.selectionEnd; var selected = content.value.substring(start, end) || ''; var rep = selected; if (command === 'bold') { rep = '**' + selected + '**'; } else if (command === 'italic') { rep = '*' + selected + '*'; } else if (command === 'code') { rep = '`' + selected + '`'; } content.value = content.value.substring(0, start) + rep + content.value.substring(end); content.focus(); content.setSelectionRange(start + rep.length, start + rep.length); }
|
|
qsa('#ap-editor-toolbar [data-cmd]').forEach(function (b) { b.addEventListener('click', function () { format(b.getAttribute('data-cmd')); }); });
|
|
var insertListBtn = qs('#ap-insert-list'); if (insertListBtn) { insertListBtn.addEventListener('click', function () { if (!content) return; var s = content.selectionStart, e = content.selectionEnd; var t = content.value.substring(s, e); var list = t.split('\n').map(function (l) { return l ? ('- ' + l) : l; }).join('\n'); content.value = content.value.substring(0, s) + list + content.value.substring(e); content.focus(); }); }
|
|
|
|
// Tag manager — tolerate when tags UI is disabled/removed
|
|
var hasTagUI = !!qs('#selected-tags');
|
|
var maxTags = <?php echo (int) ap_opt('max_tags'); ?>, minTags = <?php echo (int) ap_opt('min_tags'); ?>;
|
|
if (!hasTagUI) { minTags = 0; }
|
|
var selected = [];
|
|
var tagInput = hasTagUI ? qs('#tag-input') : null;
|
|
var selectedWrap = hasTagUI ? qs('#selected-tags') : null;
|
|
var tagCount = hasTagUI ? qs('#tag-count') : null;
|
|
function updateTagCount() { if (tagCount) { tagCount.textContent = selected.length + ' <?php echo esc_js(__('تگ انتخاب شده', 'anspress-question-answer')); ?>'; } }
|
|
function renderSelected() {
|
|
if (!selectedWrap) { return; }
|
|
selectedWrap.innerHTML = '';
|
|
if (selected.length === 0) {
|
|
selectedWrap.innerHTML = '<div class="flex items-center text-slate-400 text-sm"><svg class="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg><?php echo esc_js(__('هیچ تگی انتخاب نشده است', 'anspress-question-answer')); ?>';
|
|
return;
|
|
}
|
|
selected.forEach(function (t) {
|
|
var el = document.createElement('div');
|
|
el.className = 'inline-flex items-center px-3 py-2 bg-brand-500 text-white text-sm font-medium rounded-full shadow-sm';
|
|
el.innerHTML = '<svg class="w-3 h-3 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path></svg>' + t.name + '<button type="button" class="tag-remove mr-2 text-white hover:text-red-200" data-id="' + t.id + '"><svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></button>';
|
|
selectedWrap.appendChild(el);
|
|
});
|
|
qsa('.tag-remove', selectedWrap).forEach(function (b) { b.addEventListener('click', function () { removeTag(b.getAttribute('data-id')); }); });
|
|
}
|
|
function syncSelect() { var sel = qs('select[id*="tags"], select[name$="[tags][]"]'); if (!sel) return; sel.innerHTML = ''; selected.forEach(function (t) { var opt = document.createElement('option'); opt.value = t.id; opt.selected = true; opt.textContent = t.name; sel.appendChild(opt); }); }
|
|
function setSuggestionState(id, active) {
|
|
var btn = qs('[data-tag-id="' + id + '"]');
|
|
if (!btn) {
|
|
// Try to find by name if id didn't match
|
|
var selectedTag = selected.find(function(t) { return t.id == id; });
|
|
if (selectedTag && selectedTag.name) {
|
|
btn = qs('#tag-suggestions .tag-suggestion[data-tag-name="' + selectedTag.name + '"]');
|
|
}
|
|
}
|
|
if (!btn) return;
|
|
btn.classList.toggle('bg-brand-500', active);
|
|
btn.classList.toggle('text-white', active);
|
|
btn.classList.toggle('border-blue-600', active);
|
|
btn.classList.toggle('bg-white', !active);
|
|
btn.classList.toggle('text-slate-700', !active);
|
|
btn.classList.toggle('border-slate-200', !active);
|
|
}
|
|
function addTag(id, name) {
|
|
if (selected.length >= maxTags) {
|
|
return;
|
|
}
|
|
|
|
// Normalize id: if id is a slug (not numeric), try to find real id from popular tags
|
|
var normalizedId = id;
|
|
if (isNaN(parseInt(id))) {
|
|
var popularTag = qs('#tag-suggestions .tag-suggestion[data-tag-name="' + name + '"]');
|
|
if (popularTag) {
|
|
normalizedId = popularTag.getAttribute('data-tag-id');
|
|
}
|
|
}
|
|
|
|
// Check for duplicate by id OR by name (case-insensitive)
|
|
if (selected.some(function (t) {
|
|
return t.id == normalizedId ||
|
|
t.id == id ||
|
|
t.name.toLowerCase() === name.toLowerCase();
|
|
})) {
|
|
return;
|
|
}
|
|
|
|
selected.push({ id: String(normalizedId || id), name: String(name) });
|
|
updateTagCount();
|
|
renderSelected();
|
|
syncSelect();
|
|
setSuggestionState(normalizedId || id, true);
|
|
}
|
|
function removeTag(id) {
|
|
var i = selected.findIndex(function (t) { return t.id == id; });
|
|
if (i > -1) {
|
|
var r = selected.splice(i, 1)[0];
|
|
updateTagCount();
|
|
renderSelected();
|
|
syncSelect();
|
|
setSuggestionState(id, false);
|
|
// Also try to remove by name if id didn't match
|
|
if (r && r.name) {
|
|
var popularTag = qs('#tag-suggestions .tag-suggestion[data-tag-name="' + r.name + '"]');
|
|
if (popularTag) {
|
|
setSuggestionState(popularTag.getAttribute('data-tag-id'), false);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (hasTagUI) {
|
|
qsa('#tag-suggestions .tag-suggestion').forEach(function (btn) {
|
|
btn.addEventListener('click', function () {
|
|
var id = btn.getAttribute('data-tag-id');
|
|
var name = btn.getAttribute('data-tag-name');
|
|
// Check if tag is already selected by id OR by name (case-insensitive)
|
|
var isSelected = selected.some(function (t) {
|
|
return t.id == id || t.name.toLowerCase() === name.toLowerCase();
|
|
});
|
|
if (isSelected) {
|
|
removeTag(id);
|
|
} else {
|
|
addTag(id, name);
|
|
}
|
|
});
|
|
});
|
|
|
|
// Autocomplete suggestions
|
|
var suggestionsDropdown = qs('#tag-suggestions-dropdown');
|
|
var suggestionsList = qs('#tag-suggestions-list');
|
|
var searchTimeout = null;
|
|
var currentSuggestions = [];
|
|
|
|
function showSuggestions(suggestions) {
|
|
if (!suggestionsDropdown || !suggestionsList) return;
|
|
|
|
suggestionsList.innerHTML = '';
|
|
currentSuggestions = suggestions;
|
|
|
|
if (suggestions.length === 0) {
|
|
var noResult = document.createElement('div');
|
|
noResult.className = 'px-4 py-2 text-sm text-slate-500';
|
|
noResult.textContent = '<?php echo esc_js(__('تگی یافت نشد', 'anspress-question-answer')); ?>';
|
|
suggestionsList.appendChild(noResult);
|
|
} else {
|
|
suggestions.forEach(function(suggestion) {
|
|
var item = document.createElement('div');
|
|
item.className = 'px-4 py-2 hover:bg-brand-500/10 cursor-pointer transition-colors duration-200 flex items-center space-x-2 space-x-reverse';
|
|
item.innerHTML = '<svg class="w-4 h-4 text-brand-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path></svg><span class="text-sm text-slate-700">' + suggestion.name + '</span>';
|
|
item.addEventListener('click', function() {
|
|
// Check if id is numeric (real id) or slug (string)
|
|
var tagId = suggestion.id;
|
|
// If id is not numeric, try to find real id from popular tags
|
|
if (isNaN(parseInt(tagId))) {
|
|
var popularTag = qs('#tag-suggestions .tag-suggestion[data-tag-name="' + suggestion.name + '"]');
|
|
if (popularTag) {
|
|
tagId = popularTag.getAttribute('data-tag-id');
|
|
}
|
|
}
|
|
addTag(tagId, suggestion.name);
|
|
tagInput.value = '';
|
|
hideSuggestions();
|
|
});
|
|
suggestionsList.appendChild(item);
|
|
});
|
|
}
|
|
|
|
suggestionsDropdown.classList.remove('hidden');
|
|
}
|
|
|
|
function hideSuggestions() {
|
|
if (suggestionsDropdown) {
|
|
suggestionsDropdown.classList.add('hidden');
|
|
}
|
|
}
|
|
|
|
function searchTags(keyword) {
|
|
if (!keyword || keyword.length < 2) {
|
|
hideSuggestions();
|
|
return;
|
|
}
|
|
|
|
var formData = new FormData();
|
|
formData.append('action', 'ap_tags_suggestion');
|
|
formData.append('q', keyword);
|
|
|
|
fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', {
|
|
method: 'POST',
|
|
body: formData,
|
|
credentials: 'include',
|
|
})
|
|
.then(function(r) { return r.json(); })
|
|
.then(function(data) {
|
|
if (data && data.status && data.items && data.items.length > 0) {
|
|
// Use slugs directly as suggestions
|
|
var tags = data.items.map(function(slug) {
|
|
// Decode slug if needed
|
|
var decodedSlug = decodeURIComponent(slug);
|
|
// Convert slug to readable name
|
|
var name = decodedSlug.replace(/-/g, ' ');
|
|
name = name.replace(/\b\w/g, function(l) { return l.toUpperCase(); });
|
|
// Use slug as temporary id, will be resolved when tag is added
|
|
return { id: decodedSlug, name: name, slug: decodedSlug };
|
|
});
|
|
showSuggestions(tags);
|
|
} else {
|
|
showSuggestions([]);
|
|
}
|
|
})
|
|
.catch(function(error) {
|
|
hideSuggestions();
|
|
});
|
|
}
|
|
|
|
// Input event listener for autocomplete
|
|
if (tagInput) {
|
|
tagInput.addEventListener('input', function(e) {
|
|
var value = (e.target.value || '').trim();
|
|
|
|
if (searchTimeout) {
|
|
clearTimeout(searchTimeout);
|
|
}
|
|
|
|
if (value.length >= 2) {
|
|
searchTimeout = setTimeout(function() {
|
|
searchTags(value);
|
|
}, 300);
|
|
} else {
|
|
hideSuggestions();
|
|
}
|
|
});
|
|
|
|
// Hide dropdown when clicking outside
|
|
document.addEventListener('click', function(e) {
|
|
if (suggestionsDropdown && !suggestionsDropdown.contains(e.target) && e.target !== tagInput) {
|
|
hideSuggestions();
|
|
}
|
|
});
|
|
}
|
|
|
|
// Function to add tag from input
|
|
function addTagFromInput() {
|
|
if (!tagInput) return;
|
|
var name = (tagInput.value || '').trim();
|
|
if (!name) return;
|
|
|
|
// Check if tag is already selected (case-insensitive)
|
|
if (selected.some(function (t) { return t.name.toLowerCase() === name.toLowerCase(); })) {
|
|
tagInput.value = '';
|
|
hideSuggestions();
|
|
return;
|
|
}
|
|
|
|
// Check if tag exists in current suggestions
|
|
var foundSuggestion = currentSuggestions.find(function(s) {
|
|
return s.name.toLowerCase() === name.toLowerCase();
|
|
});
|
|
|
|
if (foundSuggestion) {
|
|
// Use existing tag from suggestions
|
|
addTag(foundSuggestion.id, foundSuggestion.name);
|
|
tagInput.value = '';
|
|
hideSuggestions();
|
|
return;
|
|
}
|
|
|
|
// Check if tag exists in popular suggestions
|
|
var suggestions = Array.prototype.slice.call(qsa('#tag-suggestions .tag-suggestion'));
|
|
var ex = suggestions.find(function (b) {
|
|
return (b.getAttribute('data-tag-name') || '').toLowerCase() === name.toLowerCase();
|
|
});
|
|
|
|
if (ex) {
|
|
addTag(ex.getAttribute('data-tag-id'), ex.getAttribute('data-tag-name'));
|
|
tagInput.value = '';
|
|
hideSuggestions();
|
|
return;
|
|
}
|
|
|
|
// Create new tag
|
|
var addBtn = qs('#add-tag-btn');
|
|
var addBtnIcon = qs('#add-tag-icon');
|
|
var addBtnSpinner = qs('#add-tag-spinner');
|
|
var addBtnText = qs('#add-tag-text');
|
|
|
|
// Check if already processing
|
|
if (addBtn && addBtn.disabled) {
|
|
return; // Prevent duplicate requests
|
|
}
|
|
|
|
// Show loading state
|
|
if (addBtn) {
|
|
addBtn.disabled = true;
|
|
addBtn.classList.add('opacity-50', 'cursor-not-allowed');
|
|
}
|
|
if (addBtnIcon) {
|
|
addBtnIcon.classList.add('hidden');
|
|
}
|
|
if (addBtnSpinner) {
|
|
addBtnSpinner.classList.remove('hidden');
|
|
}
|
|
if (addBtnText) {
|
|
addBtnText.textContent = '<?php echo esc_js(__('در حال ایجاد...', 'anspress-question-answer')); ?>';
|
|
}
|
|
if (tagInput) {
|
|
tagInput.disabled = true;
|
|
}
|
|
|
|
var formData = new URLSearchParams();
|
|
formData.append('action', 'ap_create_tag');
|
|
formData.append('name', name);
|
|
formData.append('nonce', '<?php echo wp_create_nonce('ap_create_tag'); ?>');
|
|
|
|
fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', {
|
|
method: 'POST',
|
|
body: formData,
|
|
credentials: 'include',
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
},
|
|
})
|
|
.then(function (r) {
|
|
if (!r.ok) {
|
|
return r.text().then(function(text) {
|
|
throw new Error('HTTP error! status: ' + r.status + ', body: ' + text);
|
|
});
|
|
}
|
|
return r.json();
|
|
})
|
|
.then(function (data) {
|
|
if (data && data.success && data.data && data.data.id && data.data.name) {
|
|
addTag(data.data.id, data.data.name);
|
|
tagInput.value = '';
|
|
hideSuggestions();
|
|
|
|
// Add to popular suggestions if not exists
|
|
var suggestions = qsa('#tag-suggestions .tag-suggestion');
|
|
var exists = false;
|
|
for (var i = 0; i < suggestions.length; i++) {
|
|
if (suggestions[i].getAttribute('data-tag-id') === String(data.data.id)) {
|
|
exists = true;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (!exists) {
|
|
var s = document.createElement('button');
|
|
s.type = 'button';
|
|
s.className = 'inline-flex items-center px-3 py-2 bg-white text-slate-700 text-sm font-medium rounded-full border border-slate-200 hover:bg-brand-500/10 hover:border-brand-400 hover:text-brand-700 cursor-pointer transition-all duration-200 tag-suggestion';
|
|
s.setAttribute('data-tag-id', data.data.id);
|
|
s.setAttribute('data-tag-name', data.data.name);
|
|
s.innerHTML = '<svg class="w-3 h-3 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>' + data.data.name;
|
|
s.addEventListener('click', function () {
|
|
var id = s.getAttribute('data-tag-id'),
|
|
n = s.getAttribute('data-tag-name');
|
|
if (selected.some(function (t) { return t.id == id; })) {
|
|
removeTag(id);
|
|
} else {
|
|
addTag(id, n);
|
|
}
|
|
});
|
|
var cont = qs('#tag-suggestions');
|
|
if (cont) {
|
|
cont.appendChild(s);
|
|
setSuggestionState(data.data.id, true);
|
|
}
|
|
} else {
|
|
setSuggestionState(data.data.id, true);
|
|
}
|
|
} else {
|
|
var errorMsg = data && data.data && data.data.message ? data.data.message : '<?php echo esc_js(__('خطا در ایجاد تگ', 'anspress-question-answer')); ?>';
|
|
alert(errorMsg);
|
|
}
|
|
}).catch(function (error) {
|
|
if (tagInput) {
|
|
tagInput.style.borderColor = '#ef4444';
|
|
setTimeout(function() {
|
|
if (tagInput) {
|
|
tagInput.style.borderColor = '';
|
|
}
|
|
}, 2000);
|
|
}
|
|
alert('<?php echo esc_js(__('خطا در ایجاد تگ. لطفاً دوباره تلاش کنید.', 'anspress-question-answer')); ?>');
|
|
}).finally(function () {
|
|
// Hide loading state
|
|
if (addBtn) {
|
|
addBtn.disabled = false;
|
|
addBtn.classList.remove('opacity-50', 'cursor-not-allowed');
|
|
}
|
|
if (addBtnIcon) {
|
|
addBtnIcon.classList.remove('hidden');
|
|
}
|
|
if (addBtnSpinner) {
|
|
addBtnSpinner.classList.add('hidden');
|
|
}
|
|
if (addBtnText) {
|
|
addBtnText.textContent = '<?php echo esc_js(__('افزودن تگ', 'anspress-question-answer')); ?>';
|
|
}
|
|
if (tagInput) {
|
|
tagInput.disabled = false;
|
|
}
|
|
});
|
|
}
|
|
|
|
// Add click event listener to button
|
|
var addBtn = qs('#add-tag-btn');
|
|
if (addBtn && tagInput) {
|
|
addBtn.addEventListener('click', function(e) {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
addTagFromInput();
|
|
});
|
|
}
|
|
|
|
// Add Enter key event listener to input
|
|
if (tagInput) {
|
|
tagInput.addEventListener('keydown', function(e) {
|
|
if (e.key === 'Enter' || e.keyCode === 13) {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
// Don't process if input is disabled (already processing)
|
|
if (!tagInput.disabled) {
|
|
addTagFromInput();
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
var showAll = qs('#show-all-tags'); if (showAll) { showAll.addEventListener('click', function () { qsa('#tag-suggestions .tag-suggestion').forEach(function (b) { b.style.display = 'inline-flex'; }); if (tagInput) { tagInput.value = ''; } }); }
|
|
updateTagCount(); renderSelected();
|
|
}
|
|
|
|
// File manager (client-side only) — keep input synced for submit
|
|
var fmInput = qs('#ap-file-input'); var filesDiv = qs('#selected-files'); var fileList = qs('#file-list');
|
|
// Use window.selectedFiles to make it accessible globally
|
|
if (typeof window.selectedFiles === 'undefined') {
|
|
window.selectedFiles = [];
|
|
}
|
|
var selectedFiles = window.selectedFiles; // Reference to global array
|
|
|
|
function fmt(bytes) { if (bytes === 0) return '0 Bytes'; var k = 1024, sizes = ['Bytes', 'KB', 'MB', 'GB'], i = Math.floor(Math.log(bytes) / Math.log(k)); return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]; }
|
|
function renderFiles() {
|
|
if (!filesDiv || !fileList) return; if (window.selectedFiles.length === 0) { filesDiv.classList.add('hidden'); return; } filesDiv.classList.remove('hidden'); fileList.innerHTML = ''; window.selectedFiles.forEach(function (f) {
|
|
var row = document.createElement('div'); row.className = 'flex items-center justify-between p-3 bg-white rounded-lg border border-slate-200'; row.innerHTML = '<div class="flex items-center space-x-3 space-x-reverse"><div class="flex-1 min-w-0"><p class="text-sm font-medium text-slate-800 truncate">' + f.name + '</p><p class="text-xs text-slate-500">' + fmt(f.size) + '</p></div></div><button type="button" class="flex-shrink-0 text-red-600 hover:text-red-800" data-id="' + f.__id + '"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></button>';
|
|
fileList.appendChild(row);
|
|
qs('button[data-id="' + f.__id + '"]', row).addEventListener('click', function () { window.selectedFiles = window.selectedFiles.filter(function (x) { return x.__id !== f.__id; }); selectedFiles = window.selectedFiles; renderFiles(); syncFilesToInput(); });
|
|
});
|
|
}
|
|
function syncFilesToInput() {
|
|
var mainFile = qs('input[type="file"][name*="attachments"], input[type="file"][name*="ap_attachments"]', form); if (!mainFile) { mainFile = document.createElement('input'); mainFile.type = 'file'; mainFile.name = 'ap_attachments[]'; mainFile.multiple = true; mainFile.style.display = 'none'; form.appendChild(mainFile); }
|
|
if (window.DataTransfer) { var dt = new DataTransfer(); window.selectedFiles.forEach(function (f) { dt.items.add(f); }); mainFile.files = dt.files; }
|
|
}
|
|
if (fmInput) { fmInput.addEventListener('change', function (e) { Array.prototype.slice.call(e.target.files || []).forEach(function (f) { if (window.selectedFiles.length >= 3) return; var okTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'text/plain']; if (okTypes.indexOf(f.type) === -1) return; if (f.size > 4 * 1024 * 1024) return; f.__id = Date.now() + Math.random(); window.selectedFiles.push(f); selectedFiles = window.selectedFiles; }); renderFiles(); syncFilesToInput(); }); }
|
|
|
|
// Form loading state management
|
|
function showFormLoading() {
|
|
var overlay = qs('#ap-form-loading-overlay');
|
|
if (overlay) { overlay.classList.remove('hidden'); }
|
|
// Disable all form fields (except hidden fields)
|
|
qsa('input, textarea, select, button', form).forEach(function (field) {
|
|
if (field.type !== 'hidden' && !field.disabled) {
|
|
field.disabled = true;
|
|
field.setAttribute('data-was-disabled', 'true');
|
|
}
|
|
});
|
|
// Disable custom submit button (even if outside form)
|
|
var customSubmit = qs('#ap-custom-submit');
|
|
if (customSubmit) {
|
|
customSubmit.disabled = true;
|
|
// customSubmit.style.opacity = '0.6';
|
|
// customSubmit.style.cursor = 'not-allowed';
|
|
customSubmit.setAttribute('data-was-disabled', 'true');
|
|
}
|
|
}
|
|
|
|
function hideFormLoading() {
|
|
var overlay = qs('#ap-form-loading-overlay');
|
|
if (overlay) { overlay.classList.add('hidden'); }
|
|
// Enable all form fields that were disabled
|
|
qsa('input, textarea, select, button', form).forEach(function (field) {
|
|
if (field.getAttribute('data-was-disabled') === 'true') {
|
|
field.disabled = false;
|
|
field.removeAttribute('data-was-disabled');
|
|
}
|
|
});
|
|
// Enable custom submit button (even if outside form)
|
|
var customSubmit = qs('#ap-custom-submit');
|
|
if (customSubmit && customSubmit.getAttribute('data-was-disabled') === 'true') {
|
|
customSubmit.disabled = false;
|
|
customSubmit.style.opacity = '1';
|
|
customSubmit.style.cursor = 'pointer';
|
|
customSubmit.removeAttribute('data-was-disabled');
|
|
}
|
|
}
|
|
|
|
// Handle AJAX form response errors - wait for AnsPress to be ready
|
|
function setupErrorHandler() {
|
|
if (typeof AnsPress !== 'undefined' && typeof AnsPress.on === 'function') {
|
|
AnsPress.on('formPosted', function (data) {
|
|
// Hide loading overlay after response (both success and error)
|
|
hideFormLoading();
|
|
|
|
if (!data.success) {
|
|
// Clear previous errors
|
|
qsa('#ap-title-errors, #ap-content-errors, #ap-private-errors, #ap-tags-errors').forEach(function (el) { el.innerHTML = ''; });
|
|
|
|
// AnsPress already adds form_errors (general errors) in common.js before triggering this event
|
|
// So we don't need to add them again, just let AnsPress handle them
|
|
// We only need to handle field-specific errors
|
|
|
|
// Display field errors
|
|
if (data.fields_errors) {
|
|
for (var fieldName in data.fields_errors) {
|
|
var errors = data.fields_errors[fieldName];
|
|
var errorContainer = null;
|
|
|
|
if (fieldName.indexOf('post_title') !== -1) {
|
|
errorContainer = qs('#ap-title-errors');
|
|
} else if (fieldName.indexOf('post_content') !== -1) {
|
|
errorContainer = qs('#ap-content-errors');
|
|
} else if (fieldName.indexOf('is_private') !== -1) {
|
|
errorContainer = qs('#ap-private-errors');
|
|
}
|
|
|
|
if (errorContainer && errors.error) {
|
|
errorContainer.innerHTML = '';
|
|
for (var code in errors.error) {
|
|
var errMsg = errors.error[code];
|
|
var errDiv = document.createElement('div');
|
|
errDiv.className = 'p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700 flex items-start';
|
|
errDiv.innerHTML = '<svg class="w-4 h-4 text-red-500 ml-2 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg><span>' + errMsg + '</span>';
|
|
errorContainer.appendChild(errDiv);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Scroll to first error
|
|
var firstError = qs('#ap-title-errors div, #ap-content-errors div, #ap-private-errors div, #ap-tags-errors div, .ap-form-errors');
|
|
if (firstError) {
|
|
firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
|
}
|
|
}
|
|
});
|
|
|
|
// Also handle AJAX errors (network errors, etc.)
|
|
if (typeof jQuery !== 'undefined') {
|
|
jQuery(form).on('ajaxSubmitError', function (e, xhr, status, error) {
|
|
hideFormLoading();
|
|
});
|
|
}
|
|
} else {
|
|
// Retry if AnsPress not loaded yet
|
|
setTimeout(setupErrorHandler, 100);
|
|
}
|
|
}
|
|
setupErrorHandler();
|
|
|
|
// Prevent default form submit - we handle it manually
|
|
form.addEventListener('submit', function (e) {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
e.stopImmediatePropagation(); // Prevent AnsPress handler from running
|
|
|
|
// Clear previous errors before new submit
|
|
qsa('.ap-form-errors', form).forEach(function (el) { el.remove(); });
|
|
qsa('#ap-title-errors, #ap-content-errors, #ap-private-errors, #ap-tags-errors').forEach(function (el) { el.innerHTML = ''; });
|
|
|
|
// Trigger click on custom submit button instead
|
|
if (customSubmit) {
|
|
customSubmit.click();
|
|
}
|
|
}, true);
|
|
|
|
// Also prevent AnsPress ajaxSubmit handler from running
|
|
if (typeof jQuery !== 'undefined') {
|
|
// Wait for AnsPress to load, then override
|
|
setTimeout(function() {
|
|
// Remove AnsPress handler
|
|
jQuery('body').off('submit', '[apform]');
|
|
|
|
// Add our own handler that prevents default
|
|
jQuery('body').on('submit', '[apform]', function(e) {
|
|
var formEl = this;
|
|
if (formEl === form || formEl.id === form.id) {
|
|
e.preventDefault();
|
|
e.stopImmediatePropagation();
|
|
|
|
var customSubmitBtn = qs('#ap-custom-submit');
|
|
if (customSubmitBtn) {
|
|
customSubmitBtn.click();
|
|
}
|
|
}
|
|
});
|
|
}, 100);
|
|
}
|
|
|
|
|
|
// Reveal form and hide preloader (late pass)
|
|
var pre = qs('#ap-form-preloader');
|
|
form.style.display = 'block';
|
|
if (pre) { pre.style.display = 'none'; }
|
|
|
|
// Fallback: if something blocks earlier, ensure form shows eventually
|
|
setTimeout(function () { if (form && form.style.display === 'none') { form.style.display = 'block'; if (pre) { pre.style.display = 'none'; } } }, 3000);
|
|
}
|
|
|
|
document.addEventListener('DOMContentLoaded', enhanceForm);
|
|
})();
|
|
</script>
|