tougao/assets/js/main.js
2025-05-26 15:23:18 +08:00

612 lines
18 KiB
JavaScript

/**
* 投稿系统前端交互脚本
* 提供表单切换、验证、提交等功能
*/
// 全局变量
let currentFormType = 'website';
let isSubmitting = false;
// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
initializeApp();
});
/**
* 初始化应用
*/
function initializeApp() {
initializeFormSwitching();
initializeFormValidation();
initializeWebsiteInfoFetching();
initializePlatformWarnings();
initializeFormSubmission();
}
/**
* 初始化表单切换功能
*/
function initializeFormSwitching() {
const tabButtons = document.querySelectorAll('.tab-btn');
const formContents = document.querySelectorAll('.form-content');
tabButtons.forEach(button => {
button.addEventListener('click', function() {
const targetForm = this.dataset.form;
switchForm(targetForm);
});
});
}
/**
* 切换表单
* @param {string} formType - 表单类型 ('website' 或 'app')
*/
function switchForm(formType) {
currentFormType = formType;
// 更新标签按钮状态
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.remove('active');
});
document.querySelector(`[data-form="${formType}"]`).classList.add('active');
// 切换表单内容
document.querySelectorAll('.form-content').forEach(content => {
content.classList.remove('active');
});
document.getElementById(`${formType}-form`).classList.add('active');
// 更新必填字段
updateRequiredFields(formType);
// 清除之前的错误信息
clearFormErrors();
}
/**
* 更新必填字段
* @param {string} formType - 表单类型
*/
function updateRequiredFields(formType) {
// 清除所有必填标记
document.querySelectorAll('input, textarea, select').forEach(field => {
field.removeAttribute('required');
});
if (formType === 'website') {
// 网址投稿必填字段
const requiredFields = ['url', 'platforms'];
requiredFields.forEach(fieldName => {
const field = document.querySelector(`[name="${fieldName}"]`);
if (field) {
if (fieldName === 'platforms') {
// 平台选择至少选一个
const checkboxes = document.querySelectorAll('input[name="platforms[]"]');
checkboxes.forEach(cb => cb.setAttribute('required', 'required'));
} else {
field.setAttribute('required', 'required');
}
}
});
} else if (formType === 'app') {
// APP投稿必填字段
const requiredFields = ['app_name', 'platform', 'version', 'download_url'];
requiredFields.forEach(fieldName => {
const field = document.querySelector(`[name="${fieldName}"]`);
if (field) {
field.setAttribute('required', 'required');
}
});
}
}
/**
* 初始化表单验证
*/
function initializeFormValidation() {
// URL格式验证
const urlInput = document.querySelector('input[name="url"]');
if (urlInput) {
urlInput.addEventListener('blur', validateURL);
urlInput.addEventListener('input', debounce(validateURL, 500));
}
// 平台选择验证
const platformCheckboxes = document.querySelectorAll('input[name="platforms[]"]');
platformCheckboxes.forEach(checkbox => {
checkbox.addEventListener('change', validatePlatformSelection);
});
// APP表单验证
const appNameInput = document.querySelector('input[name="app_name"]');
if (appNameInput) {
appNameInput.addEventListener('blur', validateAppName);
}
const downloadUrlInput = document.querySelector('input[name="download_url"]');
if (downloadUrlInput) {
downloadUrlInput.addEventListener('blur', validateDownloadURL);
}
}
/**
* 验证URL格式
*/
function validateURL() {
const urlInput = document.querySelector('input[name="url"]');
const url = urlInput.value.trim();
if (!url) return;
// 自动添加协议
if (url && !url.match(/^https?:\/\//)) {
urlInput.value = 'https://' + url;
}
// 验证URL格式
const urlPattern = /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/;
if (!urlPattern.test(urlInput.value)) {
showFieldError(urlInput, '请输入有效的网址格式');
return false;
} else {
clearFieldError(urlInput);
return true;
}
}
/**
* 验证平台选择
*/
function validatePlatformSelection() {
const checkboxes = document.querySelectorAll('input[name="platforms[]"]');
const checked = Array.from(checkboxes).some(cb => cb.checked);
if (!checked) {
showFieldError(checkboxes[0].closest('.checkbox-group'), '请至少选择一个收录平台');
return false;
} else {
clearFieldError(checkboxes[0].closest('.checkbox-group'));
return true;
}
}
/**
* 验证APP名称
*/
function validateAppName() {
const appNameInput = document.querySelector('input[name="app_name"]');
const appName = appNameInput.value.trim();
if (appName.length < 2) {
showFieldError(appNameInput, 'APP名称至少需要2个字符');
return false;
} else {
clearFieldError(appNameInput);
return true;
}
}
/**
* 验证下载链接
*/
function validateDownloadURL() {
const downloadUrlInput = document.querySelector('input[name="download_url"]');
const url = downloadUrlInput.value.trim();
if (!url) return;
const urlPattern = /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/;
if (!urlPattern.test(url)) {
showFieldError(downloadUrlInput, '请输入有效的下载链接');
return false;
} else {
clearFieldError(downloadUrlInput);
return true;
}
}
/**
* 显示字段错误
* @param {Element} field - 字段元素
* @param {string} message - 错误信息
*/
function showFieldError(field, message) {
clearFieldError(field);
const errorDiv = document.createElement('div');
errorDiv.className = 'field-error';
errorDiv.style.cssText = `
color: var(--error-color);
font-size: 0.75rem;
margin-top: 0.25rem;
display: flex;
align-items: center;
gap: 0.25rem;
`;
errorDiv.innerHTML = `
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
</svg>
${message}
`;
field.style.borderColor = 'var(--error-color)';
field.parentNode.appendChild(errorDiv);
}
/**
* 清除字段错误
* @param {Element} field - 字段元素
*/
function clearFieldError(field) {
const existingError = field.parentNode.querySelector('.field-error');
if (existingError) {
existingError.remove();
}
field.style.borderColor = '';
}
/**
* 清除所有表单错误
*/
function clearFormErrors() {
document.querySelectorAll('.field-error').forEach(error => error.remove());
document.querySelectorAll('.form-control').forEach(field => {
field.style.borderColor = '';
});
}
/**
* 初始化网站信息获取功能
*/
function initializeWebsiteInfoFetching() {
const urlInput = document.querySelector('input[name="url"]');
const fetchBtn = document.querySelector('#fetch-info-btn');
if (fetchBtn) {
fetchBtn.addEventListener('click', fetchWebsiteInfo);
}
if (urlInput) {
urlInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
e.preventDefault();
fetchWebsiteInfo();
}
});
}
}
/**
* 获取网站信息
*/
async function fetchWebsiteInfo() {
const urlInput = document.querySelector('input[name="url"]');
const fetchBtn = document.querySelector('#fetch-info-btn');
const url = urlInput.value.trim();
if (!url) {
showAlert('请先输入网址', 'warning');
return;
}
if (!validateURL()) {
return;
}
// 显示加载状态
const originalText = fetchBtn.innerHTML;
fetchBtn.innerHTML = '<span class="spinner"></span> 获取中...';
fetchBtn.disabled = true;
try {
const response = await fetch('api/fetch_website_info.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ url: url })
});
const data = await response.json();
if (data.success) {
// 填充表单字段
fillWebsiteInfo(data.data);
showAlert('网站信息获取成功!', 'success');
} else {
showAlert(data.message || '获取网站信息失败', 'error');
}
} catch (error) {
console.error('获取网站信息失败:', error);
showAlert('网络错误,请稍后重试', 'error');
} finally {
// 恢复按钮状态
fetchBtn.innerHTML = originalText;
fetchBtn.disabled = false;
}
}
/**
* 填充网站信息到表单
* @param {Object} info - 网站信息
*/
function fillWebsiteInfo(info) {
const fields = {
'site_name': info.title || '',
'site_description': info.description || '',
'site_keywords': info.keywords || ''
};
Object.entries(fields).forEach(([fieldName, value]) => {
const field = document.querySelector(`[name="${fieldName}"]`);
if (field && value) {
field.value = value;
// 触发输入事件以更新UI
field.dispatchEvent(new Event('input', { bubbles: true }));
}
});
}
/**
* 初始化平台警告提示
*/
function initializePlatformWarnings() {
const platformCheckboxes = document.querySelectorAll('input[name="platforms[]"]');
platformCheckboxes.forEach(checkbox => {
checkbox.addEventListener('change', updatePlatformWarnings);
});
}
/**
* 更新平台警告提示
*/
function updatePlatformWarnings() {
const warnings = {
'zmtwiki': '该平台需要合法合规的内容',
'ztab': '该平台需要合法合规的内容',
'soso': '该平台内容审查相当宽松'
};
// 清除现有警告
document.querySelectorAll('.platform-warning').forEach(warning => {
warning.classList.remove('show');
});
// 显示相关警告
Object.entries(warnings).forEach(([platform, message]) => {
const checkbox = document.querySelector(`input[value="${platform}"]`);
if (checkbox && checkbox.checked) {
showPlatformWarning(platform, message);
}
});
}
/**
* 显示平台警告
* @param {string} platform - 平台名称
* @param {string} message - 警告信息
*/
function showPlatformWarning(platform, message) {
let warningDiv = document.querySelector(`#warning-${platform}`);
if (!warningDiv) {
warningDiv = document.createElement('div');
warningDiv.id = `warning-${platform}`;
warningDiv.className = 'platform-warning';
const checkbox = document.querySelector(`input[value="${platform}"]`);
checkbox.closest('.checkbox-item').appendChild(warningDiv);
}
warningDiv.innerHTML = `
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="flex-shrink: 0;">
<path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>
</svg>
<span>${message}</span>
`;
warningDiv.classList.add('show');
}
/**
* 初始化表单提交
*/
function initializeFormSubmission() {
const form = document.querySelector('#submission-form');
if (form) {
form.addEventListener('submit', handleFormSubmission);
}
}
/**
* 处理表单提交
* @param {Event} e - 提交事件
*/
async function handleFormSubmission(e) {
e.preventDefault();
if (isSubmitting) return;
// 验证表单
if (!validateForm()) {
return;
}
isSubmitting = true;
const submitBtn = document.querySelector('button[type="submit"]');
const originalText = submitBtn.innerHTML;
// 显示提交状态
submitBtn.innerHTML = '<span class="spinner"></span> 提交中...';
submitBtn.disabled = true;
try {
const formData = new FormData(e.target);
formData.append('form_type', currentFormType);
const response = await fetch('', {
method: 'POST',
body: formData
});
const result = await response.text();
// 检查响应中是否包含成功信息
if (result.includes('提交成功') || result.includes('success')) {
showAlert('投稿提交成功!我们会尽快审核您的内容。', 'success');
resetForm();
} else if (result.includes('已存在') || result.includes('重复')) {
showAlert('该内容已存在,请勿重复提交。', 'warning');
} else if (result.includes('超出限制') || result.includes('限制')) {
showAlert('今日提交次数已达上限,请明天再试。', 'warning');
} else {
showAlert('提交失败,请稍后重试。', 'error');
}
} catch (error) {
console.error('提交失败:', error);
showAlert('网络错误,请稍后重试。', 'error');
} finally {
// 恢复按钮状态
isSubmitting = false;
submitBtn.innerHTML = originalText;
submitBtn.disabled = false;
}
}
/**
* 验证整个表单
* @returns {boolean} 验证结果
*/
function validateForm() {
let isValid = true;
if (currentFormType === 'website') {
if (!validateURL()) isValid = false;
if (!validatePlatformSelection()) isValid = false;
} else if (currentFormType === 'app') {
if (!validateAppName()) isValid = false;
if (!validateDownloadURL()) isValid = false;
}
return isValid;
}
/**
* 重置表单
*/
function resetForm() {
const form = document.querySelector('#submission-form');
if (form) {
form.reset();
clearFormErrors();
// 清除平台警告
document.querySelectorAll('.platform-warning').forEach(warning => {
warning.classList.remove('show');
});
}
}
/**
* 显示提示信息
* @param {string} message - 提示信息
* @param {string} type - 提示类型 (success, error, warning, info)
*/
function showAlert(message, type = 'info') {
// 移除现有提示
const existingAlert = document.querySelector('.alert');
if (existingAlert) {
existingAlert.remove();
}
const alertDiv = document.createElement('div');
alertDiv.className = `alert alert-${type}`;
alertDiv.innerHTML = `
<div style="display: flex; align-items: center; gap: 0.5rem;">
${getAlertIcon(type)}
<span>${message}</span>
</div>
`;
// 插入到表单顶部
const form = document.querySelector('#submission-form');
if (form) {
form.insertBefore(alertDiv, form.firstChild);
}
// 自动隐藏
setTimeout(() => {
if (alertDiv.parentNode) {
alertDiv.style.opacity = '0';
alertDiv.style.transform = 'translateY(-10px)';
setTimeout(() => alertDiv.remove(), 300);
}
}, 5000);
}
/**
* 获取提示图标
* @param {string} type - 提示类型
* @returns {string} SVG图标
*/
function getAlertIcon(type) {
const icons = {
success: '<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>',
error: '<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/></svg>',
warning: '<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/></svg>',
info: '<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/></svg>'
};
return icons[type] || icons.info;
}
/**
* 防抖函数
* @param {Function} func - 要防抖的函数
* @param {number} wait - 等待时间
* @returns {Function} 防抖后的函数
*/
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
/**
* 节流函数
* @param {Function} func - 要节流的函数
* @param {number} limit - 限制时间
* @returns {Function} 节流后的函数
*/
function throttle(func, limit) {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// 导出函数供其他脚本使用
window.SubmissionSystem = {
switchForm,
validateForm,
fetchWebsiteInfo,
showAlert,
resetForm
};