Merge remote-tracking branch 'origin/main' into nextjs-migration

This commit is contained in:
lezi-fun committed 2026-08-09 17:15:57 +08:00
commit 3e9d004fb6
10 files changed
+1311

No files matched your search

+261
View File
@@ -0,0 +1,261 @@
// ============================================================
// 🛡️ 管理后台
// ============================================================
function renderAdminReports() {
const container = document.getElementById('adminContent');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
API.getReports().then(reports => {
if (!reports || reports.length === 0) {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">✅ 暂无举报</div>';
return;
}
let html = '';
const statusMap = { pending: '⏳ 待处理', approved: '✅ 已删除', rejected: '❌ 已驳回' };
reports.forEach(r => {
const postTitle = r.post_title || '无标题';
html += `
<div class="report-item">
<div><strong>${r.reporter_name || '匿名'}</strong> 举报了帖子</div>
<div style="font-size:13px;color:#64748b;margin:4px 0;">原因:${r.reason}</div>
<div style="font-size:13px;color:#64748b;margin:4px 0;">帖子:${postTitle} — ${(r.post_content || '').substring(0, 30)}${(r.post_content || '').length > 30 ? '...' : ''}</div>
<div style="font-size:13px;font-weight:600;">状态:${statusMap[r.status] || r.status}</div>
${r.handler_name ? `<div style="font-size:12px;color:#94a3b8;">处理人:${r.handler_name}${r.handler_note ? ' (' + r.handler_note + ')' : ''}</div>` : ''}
${r.status === 'pending' ? `
<div class="report-actions">
<button class="btn-sm btn-danger" data-reportid="${r.id}" data-action="approve">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
删除帖子
</button>
<button class="btn-sm btn-secondary" data-reportid="${r.id}" data-action="reject">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
驳回举报
</button>
</div>
` : ''}
</div>
`;
});
container.innerHTML = html;
container.querySelectorAll('[data-action]').forEach(btn => {
btn.addEventListener('click', function() {
const id = this.dataset.reportid;
const action = this.dataset.action;
const status = action === 'approve' ? 'approved' : 'rejected';
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return;
API.updateReport(id, status, note).then(() => {
if (action === 'approve') {
const report = reports.find(r => r.id === id);
if (report && report.post_id) {
API.deletePost(report.post_id).catch(() => {});
}
}
renderAdminReports();
}).catch(err => alert('操作失败:' + err.message));
});
});
}).catch(() => {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>';
});
}
function renderAdminUsers() {
const container = document.getElementById('adminContent');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
API.getUsers().then(users => {
let html = `
<div style="margin-bottom:12px;font-size:13px;color:#94a3b8;">
共 <strong>${users.length}</strong> 位用户
</div>
<div style="overflow-x:auto;">
<table style="width:100%;border-collapse:collapse;font-size:14px;">
<thead>
<tr style="text-align:left;border-bottom:2px solid #e2e8f0;">
<th style="padding:10px 12px;">用户</th>
<th style="padding:10px 12px;">角色</th>
<th style="padding:10px 12px;">注册时间</th>
<th style="padding:10px 12px;text-align:center;">操作</th>
</tr>
</thead>
<tbody>
`;
users.forEach(u => {
const isAdmin = u.role === 'admin';
const isCurrentUser = currentUser && currentUser.id === u.id;
html += `
<tr style="border-bottom:1px solid #f1f5f9;${isCurrentUser ? 'background:var(--primary-bg);' : ''}">
<td style="padding:10px 12px;">
<div style="display:flex;align-items:center;gap:8px;">
<img src="${u.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64'}"
style="width:28px;height:28px;border-radius:50%;object-fit:cover;" />
<span style="font-weight:500;">${u.username}</span>
${isCurrentUser ? '<span style="font-size:11px;color:#94a3b8;background:#eef2ff;padding:1px 8px;border-radius:4px;">你</span>' : ''}
</div>
</td>
<td style="padding:10px 12px;">
<span style="display:inline-block;padding:2px 10px;border-radius:4px;font-size:12px;font-weight:500;${isAdmin ? 'background:#6366f1;color:#fff;' : 'background:#e2e8f0;color:#64748b;'}">
${isAdmin ? '管理员' : '普通用户'}
</span>
</td>
<td style="padding:10px 12px;color:#94a3b8;font-size:13px;">${u.created_at ? new Date(u.created_at).toLocaleDateString('zh-CN') : '—'}</td>
<td style="padding:10px 12px;text-align:center;">
${isCurrentUser ?
'<span style="font-size:12px;color:#94a3b8;">不可操作自己</span>' :
(isAdmin ?
`<button class="btn-sm btn-secondary" data-userid="${u.id}" data-role="user" style="padding:4px 12px;">设为普通用户</button>` :
`<button class="btn-sm btn-primary" data-userid="${u.id}" data-role="admin" style="padding:4px 12px;background:#6366f1;color:#fff;border:none;border-radius:4px;cursor:pointer;">设为管理员</button>`
)
}
</td>
</tr>
`;
});
html += '</tbody></table></div>';
container.innerHTML = html;
container.querySelectorAll('[data-role]').forEach(btn => {
btn.addEventListener('click', function() {
const userId = this.dataset.userid;
const role = this.dataset.role;
const roleName = role === 'admin' ? '管理员' : '普通用户';
if (!confirm(`确定要将该用户设为「${roleName}」吗?`)) return;
API.updateUserRole(userId, role).then(() => {
renderAdminUsers();
}).catch(err => alert('操作失败:' + err.message));
});
});
}).catch(() => {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载失败</div>';
});
}
function renderAdminLogs() {
const container = document.getElementById('adminContent');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
API.getEventLogs().then(logs => {
if (!logs || logs.length === 0) {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">暂无日志</div>';
return;
}
let html =
'<table style="width:100%;border-collapse:collapse;font-size:13px;"><thead><tr style="text-align:left;border-bottom:1px solid #e2e8f0;"><th>时间</th><th>用户</th><th>操作</th></tr></thead><tbody>';
logs.forEach(l => {
html += `
<tr style="border-bottom:1px solid #f1f5f9;">
<td style="padding:6px 0;">${new Date(l.created_at).toLocaleString('zh-CN')}</td>
<td style="padding:6px 0;">${l.username || '系统'}</td>
<td style="padding:6px 0;">${l.action}</td>
</tr>
`;
});
html += '</tbody></table>';
container.innerHTML = html;
}).catch(() => {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载失败</div>';
});
}
function renderAdminLinks() {
const container = document.getElementById('adminContent');
container.innerHTML = `
<div style="margin-bottom:16px;display:flex;gap:8px;flex-wrap:wrap;">
<input type="text" id="newLinkTitle" placeholder="链接名称" style="flex:1;min-width:120px;padding:8px 12px;border:1px solid #e2e8f0;border-radius:4px;" />
<input type="url" id="newLinkUrl" placeholder="链接地址" style="flex:2;min-width:160px;padding:8px 12px;border:1px solid #e2e8f0;border-radius:4px;" />
<button id="addLinkBtn" class="btn-primary" style="padding:8px 16px;">添加</button>
</div>
<div id="linkList"></div>
`;
function loadLinks() {
API.getLinks().then(links => {
const ul = document.getElementById('linkList');
if (!links || links.length === 0) {
ul.innerHTML = '<div style="color:#94a3b8;font-size:13px;">暂无友情链接</div>';
return;
}
let html = '';
links.forEach(l => {
html += `
<div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f1f5f9;">
<span><a href="${l.url}" target="_blank" style="color:#6366f1;text-decoration:none;">${l.title}</a></span>
<button class="btn-sm btn-danger" data-linkid="${l.id}">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
删除
</button>
</div>
`;
});
ul.innerHTML = html;
ul.querySelectorAll('[data-linkid]').forEach(btn => {
btn.addEventListener('click', function() {
if (!confirm('确定删除该链接吗?')) return;
API.deleteLink(this.dataset.linkid).then(() => {
loadLinks();
}).catch(err => alert('删除失败:' + err.message));
});
});
}).catch(() => {});
}
loadLinks();
document.getElementById('addLinkBtn').addEventListener('click', function() {
const title = document.getElementById('newLinkTitle').value.trim();
const url = document.getElementById('newLinkUrl').value.trim();
if (!title || !url) { alert('请填写完整信息'); return; }
API.addLink(title, url).then(() => {
document.getElementById('newLinkTitle').value = '';
document.getElementById('newLinkUrl').value = '';
loadLinks();
}).catch(err => alert('添加失败:' + err.message));
});
}
function renderAdminSettings() {
const container = document.getElementById('adminContent');
container.innerHTML = `
<h3 style="margin-bottom:16px;">⚙️ 论坛设置</h3>
<div style="max-width:400px;margin:0 auto;width:100%;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:6px;">论坛名称</label>
<input type="text" id="settingsForumName" style="width:100%;padding:10px 14px;border:1.5px solid #e2e8f0;border-radius:6px;font-size:15px;margin-bottom:12px;font-family:inherit;background:var(--bg);color:var(--text);" />
<button id="settingsForumSave" class="btn-primary" style="padding:10px 24px;">保存</button>
<span id="settingsResult" style="margin-left:12px;font-size:14px;"></span>
</div>
`;
API.getSettings().then(data => {
document.getElementById('settingsForumName').value = data.forum_name || 'Forumlify';
}).catch(() => {});
document.getElementById('settingsForumSave').addEventListener('click', async () => {
const name = document.getElementById('settingsForumName').value.trim();
if (!name) { alert('请输入论坛名称'); return; }
try {
await API.updateSettings(name);
document.getElementById('settingsResult').textContent = '✅ 保存成功!';
document.getElementById('settingsResult').style.color = '#22c55e';
document.getElementById('forumName').textContent = name;
document.title = name;
const titleEl = document.getElementById('pageTitle');
if (titleEl) titleEl.textContent = name;
} catch (err) {
document.getElementById('settingsResult').textContent = '❌ 保存失败';
document.getElementById('settingsResult').style.color = '#ef4444';
}
});
}
// 管理后台Tab切换
document.querySelectorAll('.admin-tab').forEach(tab => {
tab.addEventListener('click', function() {
document.querySelectorAll('.admin-tab').forEach(t => t.classList.remove('active'));
this.classList.add('active');
const tabMap = {
reports: renderAdminReports,
users: renderAdminUsers,
logs: renderAdminLogs,
links: renderAdminLinks,
settings: renderAdminSettings
};
if (tabMap[this.dataset.tab]) tabMap[this.dataset.tab]();
});
});
+208
View File
@@ -0,0 +1,208 @@
// ============================================================
// API 请求封装
// ============================================================
let token = localStorage.getItem('forumlify-token') || null;
function apiFetch(path, options = {}) {
const url = CONFIG.API_BASE_URL + path;
const headers = {
'Content-Type': 'application/json',
...(options.headers || {})
};
if (token) {
headers['Authorization'] = 'Bearer ' + token;
}
return fetch(url, {
...options,
headers
}).then(res => res.json());
}
const API = {
// 认证
async login(email, password) {
const data = await apiFetch('/auth/login', {
method: 'POST',
body: JSON.stringify({ email, password })
});
if (data.error) throw new Error(data.error);
if (data.token) {
token = data.token;
localStorage.setItem('forumlify-token', token);
}
return data;
},
async register(email, password, username) {
const data = await apiFetch('/auth/register', {
method: 'POST',
body: JSON.stringify({ email, password, username })
});
if (data.error) throw new Error(data.error);
return data;
},
async logout() {
token = null;
localStorage.removeItem('forumlify-token');
currentUser = null;
},
async getMe() {
const data = await apiFetch('/auth/me');
if (data.error) throw new Error(data.error);
return data;
},
// 帖子
async getPosts(sort) {
const data = await apiFetch('/posts?sort=' + (sort || 'latest'));
if (data.error) throw new Error(data.error);
return data || [];
},
async getPost(postId) {
const data = await apiFetch('/posts/' + postId);
if (data.error) throw new Error(data.error);
return data;
},
async createPost(title, content, images) {
const data = await apiFetch('/posts', {
method: 'POST',
body: JSON.stringify({ title, content, images: images || [] })
});
if (data.error) throw new Error(data.error);
return data;
},
async deletePost(postId) {
const data = await apiFetch('/posts/' + postId, { method: 'DELETE' });
if (data.error) throw new Error(data.error);
return data;
},
// 回复
async getReplies(postId) {
const data = await apiFetch('/posts/' + postId + '/replies');
if (data.error) throw new Error(data.error);
return data || [];
},
async createReply(postId, content) {
const data = await apiFetch('/posts/' + postId + '/replies', {
method: 'POST',
body: JSON.stringify({ content })
});
if (data.error) throw new Error(data.error);
return data;
},
async deleteReply(replyId) {
const data = await apiFetch('/replies/' + replyId, { method: 'DELETE' });
if (data.error) throw new Error(data.error);
return data;
},
// 用户管理
async getUsers() {
const data = await apiFetch('/users');
if (data.error) throw new Error(data.error);
return data || [];
},
async updateUserRole(userId, role) {
const data = await apiFetch('/users/' + userId + '/role', {
method: 'PUT',
body: JSON.stringify({ role })
});
if (data.error) throw new Error(data.error);
return data;
},
// 举报
async getReports() {
const data = await apiFetch('/reports');
if (data.error) throw new Error(data.error);
return data || [];
},
async createReport(postId, reason) {
const data = await apiFetch('/reports', {
method: 'POST',
body: JSON.stringify({ post_id: postId, reason })
});
if (data.error) throw new Error(data.error);
return data;
},
async updateReport(reportId, status, note) {
const data = await apiFetch('/reports/' + reportId, {
method: 'PUT',
body: JSON.stringify({ status, note })
});
if (data.error) throw new Error(data.error);
return data;
},
// 统计
async getStats() {
const data = await apiFetch('/stats');
if (data.error) throw new Error(data.error);
return data;
},
// 友情链接
async getLinks() {
const data = await apiFetch('/links');
if (data.error) throw new Error(data.error);
return data || [];
},
async addLink(title, url) {
const data = await apiFetch('/links', {
method: 'POST',
body: JSON.stringify({ title, url })
});
if (data.error) throw new Error(data.error);
return data;
},
async deleteLink(id) {
const data = await apiFetch('/links/' + id, { method: 'DELETE' });
if (data.error) throw new Error(data.error);
return data;
},
// 事件日志
async getEventLogs() {
const data = await apiFetch('/event-logs');
if (data.error) throw new Error(data.error);
return data || [];
},
async logEvent(action) {
try {
await apiFetch('/event-logs', {
method: 'POST',
body: JSON.stringify({ action })
});
} catch (e) { /* 静默失败 */ }
},
// 论坛设置
async getSettings() {
const data = await apiFetch('/settings');
if (data.error) throw new Error(data.error);
return data;
},
async updateSettings(forum_name) {
const data = await apiFetch('/settings', {
method: 'PUT',
body: JSON.stringify({ forum_name })
});
if (data.error) throw new Error(data.error);
return data;
}
};
+303
View File
@@ -0,0 +1,303 @@
// ============================================================
// 🚀 主入口
// ============================================================
let currentUser = null;
let currentPage = 'feed';
function renderNav() {
const authBtns = document.getElementById('authButtons');
const userDropdown = document.getElementById('userDropdown');
if (currentUser) {
authBtns.style.display = 'none';
userDropdown.style.display = 'block';
document.getElementById('avatarImg').src = currentUser.avatar_url ||
'https://ui-avatars.com/api/?name=U&background=6366f1&color=fff';
document.getElementById('adminEntry').style.display = currentUser.role === 'admin' ? 'block' : 'none';
} else {
authBtns.style.display = 'flex';
userDropdown.style.display = 'none';
}
}
async function loadForumName() {
try {
const data = await API.getSettings();
const name = data.forum_name || CONFIG.FORUM_NAME || 'Forumlify';
document.getElementById('forumName').textContent = name;
document.title = name;
const titleEl = document.getElementById('pageTitle');
if (titleEl) titleEl.textContent = name;
} catch (e) {
const name = CONFIG.FORUM_NAME || 'Forumlify';
document.getElementById('forumName').textContent = name;
document.title = name;
const titleEl = document.getElementById('pageTitle');
if (titleEl) titleEl.textContent = name;
}
}
function switchPage(page, param) {
const url = new URL(window.location);
if (page === 'user' && param) {
url.searchParams.set('user', param);
url.searchParams.delete('page');
url.searchParams.delete('post');
window.history.pushState({ page: 'user', username: param }, '', url);
showUserPage(param);
return;
}
if (page === 'feed') {
url.searchParams.delete('page');
url.searchParams.delete('post');
url.searchParams.delete('user');
} else {
url.searchParams.set('page', page);
url.searchParams.delete('post');
url.searchParams.delete('user');
}
window.history.pushState({ page: page }, '', url);
document.getElementById('app').style.display = 'none';
document.querySelectorAll('.page-slide').forEach(el => {
el.classList.remove('active', 'slide-out');
});
if (page === 'feed') {
document.getElementById('app').style.display = 'flex';
currentPage = 'feed';
renderFeed();
renderStats();
renderLinks();
return;
}
const pageMap = {
messages: 'pageMessages',
settings: 'pageSettings',
admin: 'pageAdmin',
new: 'pageNew'
};
const el = document.getElementById(pageMap[page]);
if (el) {
el.classList.add('active');
el.style.animation = 'none';
void el.offsetHeight;
el.style.animation = '';
currentPage = page;
if (page === 'admin') {
document.querySelectorAll('.admin-tab').forEach((t, i) => {
t.classList.toggle('active', i === 0);
});
renderAdminReports();
}
if (page === 'settings' && currentUser) {
document.getElementById('settingsUsername').value = currentUser.username || '';
document.getElementById('settingsBio').value = currentUser.bio || '';
}
if (page === 'new') {
document.getElementById('postTitle').value = '';
document.getElementById('postContent').value = '';
document.getElementById('imagePreview').innerHTML = '';
document.getElementById('imageUpload').value = '';
document.getElementById('postCaptchaInput').value = '';
refreshCaptcha('post');
}
}
}
// ============================================================
// 🚀 初始化
// ============================================================
async function init() {
applyTheme();
document.getElementById('forumName').textContent = CONFIG.FORUM_NAME || 'Forumlify';
refreshCaptcha('reg');
refreshCaptcha('post');
refreshCaptcha('reply');
if (token) {
try {
const user = await API.getMe();
currentUser = user;
API.logEvent('login').catch(() => {});
} catch (e) {
token = null;
localStorage.removeItem('forumlify-token');
}
}
renderNav();
await loadForumName();
renderStats();
renderLinks();
const urlParams = new URLSearchParams(window.location.search);
const postParam = urlParams.get('post');
const pageParam = urlParams.get('page');
const userParam = urlParams.get('user');
if (userParam) {
showUserPage(userParam);
} else if (postParam) {
showPostPage(postParam);
} else if (pageParam && ['messages', 'settings', 'admin', 'new'].includes(pageParam)) {
if (pageParam === 'admin' && currentUser?.role !== 'admin') {
switchPage('feed');
} else {
switchPage(pageParam);
}
} else {
switchPage('feed');
}
// 绑定事件(在 app.js 中绑)
document.getElementById('avatarImg').addEventListener('click', function(e) {
e.stopPropagation();
document.getElementById('dropdownMenu').classList.toggle('show');
});
document.addEventListener('click', function() {
document.getElementById('dropdownMenu').classList.remove('show');
});
document.querySelectorAll('[data-page]').forEach(el => {
el.addEventListener('click', function(e) {
e.preventDefault();
const page = this.dataset.page;
if (page === 'admin' && currentUser?.role !== 'admin') {
alert('无权限访问');
return;
}
document.getElementById('dropdownMenu').classList.remove('show');
switchPage(page);
});
});
document.querySelectorAll('.back-btn').forEach(btn => {
btn.addEventListener('click', function() {
switchPage('feed');
});
});
document.getElementById('settingsSave').addEventListener('click', async () => {
if (!currentUser) { alert('请先登录'); return; }
const username = document.getElementById('settingsUsername').value.trim();
const bio = document.getElementById('settingsBio').value.trim();
if (!username) { alert('用户名不能为空'); return; }
try {
const data = await apiFetch('/users/' + currentUser.id, {
method: 'PUT',
body: JSON.stringify({ username, bio })
});
if (data.error) throw new Error(data.error);
currentUser.username = username;
currentUser.bio = bio;
alert('保存成功!');
renderNav();
if (currentPage === 'feed') {
renderFeed();
}
} catch (err) {
alert('保存失败:' + err.message);
}
});
document.getElementById('forumName').addEventListener('click', function() {
switchPage('feed');
});
// 发帖按钮
document.getElementById('fab').addEventListener('click', () => {
if (!currentUser) { alert('请先登录'); return; }
switchPage('new');
});
document.getElementById('postSubmit').addEventListener('click', async () => {
if (!currentUser || !currentUser.id) {
alert('请先登录');
switchPage('feed');
return;
}
const title = document.getElementById('postTitle').value.trim() || '无标题';
const content = document.getElementById('postContent').value.trim();
const captchaInput = document.getElementById('postCaptchaInput').value.trim();
const captchaAnswer = parseInt(document.getElementById('postCaptchaInput').dataset.answer);
if (!content) { alert('请填写内容'); return; }
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('post'); return; }
const images = [];
document.querySelectorAll('#imagePreview img').forEach(img => {
images.push(img.src);
});
try {
await API.createPost(title, content, images);
API.logEvent('create_post').catch(() => {});
alert('发布成功!');
switchPage('feed');
renderFeed();
renderStats();
} catch (err) {
alert('发布失败:' + err.message);
}
});
document.getElementById('postCaptchaQuestion').addEventListener('click', function() {
refreshCaptcha('post');
});
document.getElementById('imageUpload').addEventListener('change', function() {
const preview = document.getElementById('imagePreview');
preview.innerHTML = '';
for (let file of this.files) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.createElement('img');
img.src = e.target.result;
img.style.cssText = 'width:80px;height:80px;object-fit:cover;border-radius:4px;border:1px solid #e2e8f0;';
preview.appendChild(img);
};
reader.readAsDataURL(file);
}
});
document.getElementById('reportSubmit').addEventListener('click', async () => {
if (!reportTargetPostId) return;
const reason = document.getElementById('reportReason').value;
try {
await API.createReport(reportTargetPostId, reason);
document.getElementById('reportModal').classList.remove('active');
alert('举报已提交,管理员将尽快处理');
reportTargetPostId = null;
} catch (err) {
alert('举报失败:' + err.message);
}
});
document.querySelectorAll('.modal .close').forEach(btn => {
btn.addEventListener('click', function() {
document.getElementById(this.dataset.modal).classList.remove('active');
});
});
document.querySelectorAll('.modal').forEach(m => {
m.addEventListener('click', function(e) {
if (e.target === this) this.classList.remove('active');
});
});
window.addEventListener('popstate', function(e) {
const state = e.state || {};
const page = state.page || 'feed';
const postId = state.postId || null;
const username = state.username || null;
if (postId) {
showPostPage(postId);
} else if (username) {
showUserPage(username);
} else {
switchPage(page);
}
});
}
document.addEventListener('DOMContentLoaded', init);
+88
View File
@@ -0,0 +1,88 @@
// ============================================================
// 🔐 认证
// ============================================================
// 登录事件绑定
document.getElementById('loginBtn').addEventListener('click', () => {
document.getElementById('loginModal').classList.add('active');
});
document.getElementById('loginSubmit').addEventListener('click', async () => {
const email = document.getElementById('loginEmail').value.trim();
const password = document.getElementById('loginPassword').value;
if (!email || !password) { alert('请填写完整信息'); return; }
try {
const result = await API.login(email, password);
document.getElementById('loginModal').classList.remove('active');
document.getElementById('loginEmail').value = '';
document.getElementById('loginPassword').value = '';
if (result.user) {
currentUser = result.user;
API.logEvent('login').catch(() => {});
renderNav();
if (currentPage === 'admin' && currentUser.role !== 'admin') {
switchPage('feed');
} else if (currentPage === 'feed') {
renderFeed();
renderStats();
}
}
} catch (err) {
alert('登录失败:' + err.message);
}
});
// 注册事件绑定
document.getElementById('registerBtn').addEventListener('click', () => {
refreshCaptcha('reg');
document.getElementById('registerModal').classList.add('active');
});
document.getElementById('registerSubmit').addEventListener('click', async () => {
const username = document.getElementById('regUsername').value.trim();
const email = document.getElementById('regEmail').value.trim();
const password = document.getElementById('regPassword').value;
const captchaInput = document.getElementById('regCaptchaInput').value.trim();
const captchaAnswer = parseInt(document.getElementById('regCaptchaInput').dataset.answer);
if (!username || !email || !password) { alert('请填写完整信息'); return; }
if (password.length < 6) { alert('密码至少6位'); return; }
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reg'); return; }
try {
await API.register(email, password, username);
document.getElementById('registerModal').classList.remove('active');
document.getElementById('regUsername').value = '';
document.getElementById('regEmail').value = '';
document.getElementById('regPassword').value = '';
document.getElementById('regCaptchaInput').value = '';
alert('注册成功!请登录');
const result = await API.login(email, password);
if (result.user) {
currentUser = result.user;
API.logEvent('register').catch(() => {});
renderNav();
if (currentPage === 'admin' && currentUser.role !== 'admin') {
switchPage('feed');
} else if (currentPage === 'feed') {
renderFeed();
renderStats();
}
}
} catch (err) {
alert('注册失败:' + err.message);
}
});
document.getElementById('regCaptchaQuestion').addEventListener('click', function() {
refreshCaptcha('reg');
});
// 退出
document.getElementById('logoutBtn').addEventListener('click', async () => {
if (!confirm('确定要退出吗?')) return;
await API.logout();
currentUser = null;
renderNav();
document.querySelectorAll('.page-slide').forEach(el => el.classList.remove('active'));
switchPage('feed');
});
+28
View File
@@ -0,0 +1,28 @@
// ============================================================
// 🧠 验证码
// ============================================================
function generateCaptcha() {
let a = Math.floor(Math.random() * 9) + 1;
let b = Math.floor(Math.random() * 9) + 1;
let op = ['+', '-'][Math.floor(Math.random() * 2)];
if (op === '-' && a < b) { let t = a;
a = b;
b = t; }
let answer = op === '+' ? a + b : a - b;
return { question: a + ' ' + op + ' ' + b + ' = ?', answer: answer };
}
function refreshCaptcha(type) {
let q = generateCaptcha();
if (type === 'reg') {
document.getElementById('regCaptchaQuestion').textContent = q.question;
document.getElementById('regCaptchaInput').dataset.answer = q.answer;
} else if (type === 'post') {
document.getElementById('postCaptchaQuestion').textContent = q.question;
document.getElementById('postCaptchaInput').dataset.answer = q.answer;
} else if (type === 'reply') {
document.getElementById('replyCaptchaQuestion').textContent = q.question;
document.getElementById('replyCaptchaInput').dataset.answer = q.answer;
}
}
+128
View File
@@ -0,0 +1,128 @@
// ============================================================
// 📋 帖子列表
// ============================================================
let currentSort = 'latest';
function renderFeed() {
const container = document.getElementById('postList');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
API.getPosts(currentSort).then(posts => {
if (!posts || posts.length === 0) {
container.innerHTML =
'<div style="text-align:center;color:#94a3b8;padding:60px 0;">✨ 还没有帖子,快来发布第一条吧!</div>';
return;
}
let html = '';
posts.forEach(p => {
const username = p.username || '匿名用户';
const avatar = p.avatar_url ||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) +
'&background=6366f1&color=fff&size=64';
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
let imagesHtml = '';
if (p.images && p.images.length > 0) {
imagesHtml = '<div class="post-images">';
p.images.forEach(img => {
imagesHtml += '<img src="' + img + '" class="post-image" />';
});
imagesHtml += '</div>';
}
const replyCount = p.reply_count || 0;
html += `
<div class="post-card" data-postid="${p.id}" style="cursor:pointer;">
<div class="post-header">
<img src="${avatar}" class="post-avatar" />
<span class="post-username" style="cursor:pointer;color:var(--primary);" onclick="event.stopPropagation();switchPage('user','${username}')">${username}</span>
<span class="post-time">${time}</span>
</div>
<div class="post-title">${p.title || '无标题'}</div>
<div class="post-content">${(p.content || '').replace(/\n/g, '<br>')}</div>
${imagesHtml}
<div class="post-actions">
<span>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
${replyCount}
</span>
<button class="action-report" data-postid="${p.id}">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
举报
</button>
${currentUser && currentUser.id === p.user_id ? `<button class="action-delete" data-postid="${p.id}">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
删除
</button>` : ''}
</div>
</div>
`;
});
container.innerHTML = html;
container.querySelectorAll('.post-card').forEach(card => {
card.addEventListener('click', function(e) {
if (e.target.closest('button')) return;
const postId = this.dataset.postid;
switchToPost(postId);
});
});
container.querySelectorAll('.action-report').forEach(btn => {
btn.addEventListener('click', function(e) {
e.stopPropagation();
if (!currentUser) { alert('请先登录'); return; }
reportTargetPostId = this.dataset.postid;
document.getElementById('reportModal').classList.add('active');
});
});
container.querySelectorAll('.action-delete').forEach(btn => {
btn.addEventListener('click', function(e) {
e.stopPropagation();
if (confirm('确定要删除这条帖子吗?')) {
API.deletePost(this.dataset.postid).then(() => {
renderFeed();
renderStats();
}).catch(err => alert('删除失败:' + err.message));
}
});
});
}).catch(err => {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message +
'</div>';
});
}
function renderStats() {
API.getStats().then(stats => {
document.getElementById('statTopics').textContent = stats.topics || 0;
document.getElementById('statPosts').textContent = stats.posts || 0;
document.getElementById('statUsers').textContent = stats.users || 0;
document.getElementById('statOnline').textContent = stats.online || 0;
}).catch(() => {});
}
function renderLinks() {
API.getLinks().then(links => {
const ul = document.getElementById('friendlyLinks');
if (!links || links.length === 0) {
ul.innerHTML = '<li style="color:#94a3b8;font-size:13px;">暂无链接</li>';
return;
}
let html = '';
links.forEach(l => {
html += '<li><a href="' + l.url + '" target="_blank">' + l.title + '</a></li>';
});
ul.innerHTML = html;
}).catch(() => {});
}
// 排序切换
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', function() {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
this.classList.add('active');
currentSort = this.dataset.sort;
if (currentPage === 'feed') {
renderFeed();
}
});
});
+1
View File
@@ -0,0 +1 @@
+181
View File
@@ -0,0 +1,181 @@
// ============================================================
// 📄 帖子详情 + 回复
// ============================================================
let currentPostId = null;
let reportTargetPostId = null;
function switchToPost(postId) {
const url = new URL(window.location);
url.searchParams.set('post', postId);
url.searchParams.delete('page');
window.history.pushState({ page: 'post', postId: postId }, '', url);
showPostPage(postId);
}
function showPostPage(postId) {
document.getElementById('app').style.display = 'none';
document.querySelectorAll('.page-slide').forEach(el => {
el.classList.remove('active', 'slide-out');
});
const el = document.getElementById('pagePost');
el.classList.add('active');
el.style.animation = 'none';
void el.offsetHeight;
el.style.animation = '';
currentPage = 'post';
renderPostDetail(postId);
}
async function renderPostDetail(postId) {
const container = document.getElementById('postDetailContent');
const replyArea = document.getElementById('replyArea');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
replyArea.style.display = 'none';
try {
const post = await API.getPost(postId);
const replies = await API.getReplies(postId);
document.getElementById('postDetailTitle').textContent = post.title || '帖子详情';
const username = post.username || '匿名用户';
const avatar = post.avatar_url ||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) +
'&background=6366f1&color=fff&size=64';
const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : '';
let imagesHtml = '';
if (post.images && post.images.length > 0) {
imagesHtml = '<div class="post-images">';
post.images.forEach(img => {
imagesHtml += '<img src="' + img + '" class="post-image" />';
});
imagesHtml += '</div>';
}
let html = `
<div class="post-detail-card">
<div class="post-header">
<img src="${avatar}" class="post-avatar" />
<span class="post-username" style="cursor:pointer;color:var(--primary);" onclick="switchPage('user','${username}')">${username}</span>
<span class="post-time">${time}</span>
${currentUser && currentUser.id === post.user_id ? `<button class="btn-sm btn-danger" id="detailDeleteBtn" data-postid="${post.id}">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
删除
</button>` : ''}
</div>
<div class="post-title" style="font-size:20px;font-weight:700;margin:8px 0 12px;">${post.title || '无标题'}</div>
<div class="post-content" style="font-size:16px;line-height:1.8;">${(post.content || '').replace(/\n/g, '<br>')}</div>
${imagesHtml}
</div>
<div style="margin-top:20px;font-size:14px;color:#64748b;">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
${replies.length} 条回复
</div>
<div style="margin-top:12px;" id="repliesList">
`;
if (replies.length === 0) {
html += '<div style="color:#94a3b8;padding:20px 0;text-align:center;">还没有回复,快来抢沙发吧 🛋️</div>';
} else {
replies.forEach(r => {
const rUsername = r.username || '匿名用户';
const rAvatar = r.avatar_url ||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(rUsername) +
'&background=6366f1&color=fff&size=64';
const rTime = r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : '';
html += `
<div class="reply-item" data-replyid="${r.id}">
<div class="reply-header">
<img src="${rAvatar}" class="reply-avatar" />
<span class="reply-username" style="cursor:pointer;color:var(--primary);" onclick="switchPage('user','${rUsername}')">${rUsername}</span>
<span class="reply-time">${rTime}</span>
${currentUser && currentUser.id === r.user_id ? `<button class="btn-sm btn-danger reply-delete-btn" data-replyid="${r.id}">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
删除
</button>` : ''}
</div>
<div class="reply-content">${(r.content || '').replace(/\n/g, '<br>')}</div>
</div>
`;
});
}
html += '</div>';
container.innerHTML = html;
replyArea.style.display = 'block';
document.getElementById('replyContent').value = '';
document.getElementById('replyCaptchaInput').value = '';
refreshCaptcha('reply');
const deleteBtn = document.getElementById('detailDeleteBtn');
if (deleteBtn) {
deleteBtn.addEventListener('click', function() {
if (confirm('确定要删除这条帖子吗?')) {
API.deletePost(postId).then(() => {
alert('删除成功');
switchPage('feed');
renderFeed();
renderStats();
}).catch(err => alert('删除失败:' + err.message));
}
});
}
document.querySelectorAll('.reply-delete-btn').forEach(btn => {
btn.addEventListener('click', function(e) {
e.stopPropagation();
const replyId = this.dataset.replyid;
if (confirm('确定要删除这条回复吗?')) {
API.deleteReply(replyId).then(() => {
renderPostDetail(postId);
}).catch(err => alert('删除失败:' + err.message));
}
});
});
const replySubmit = document.getElementById('replySubmit');
const newReplySubmit = replySubmit.cloneNode(true);
replySubmit.parentNode.replaceChild(newReplySubmit, replySubmit);
newReplySubmit.addEventListener('click', async function() {
await handleReplySubmit(postId);
});
const replyInput = document.getElementById('replyContent');
replyInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
handleReplySubmit(postId);
}
});
currentPostId = postId;
} catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message +
'</div>';
replyArea.style.display = 'none';
}
}
async function handleReplySubmit(postId) {
if (!currentUser) { alert('请先登录'); return; }
const content = document.getElementById('replyContent').value.trim();
const captchaInput = document.getElementById('replyCaptchaInput').value.trim();
const captchaAnswer = parseInt(document.getElementById('replyCaptchaInput').dataset.answer);
if (!content) { alert('请填写回复内容'); return; }
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reply'); return; }
try {
await API.createReply(postId, content);
API.logEvent('create_reply').catch(() => {});
renderPostDetail(postId);
if (currentPage === 'feed') {
renderFeed();
}
renderStats();
} catch (err) {
alert('回复失败:' + err.message);
}
}
+41
View File
@@ -0,0 +1,41 @@
// ============================================================
// 🌓 主题切换
// ============================================================
function getTheme() {
return localStorage.getItem('forumlify-theme') || 'light';
}
function setTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('forumlify-theme', theme);
updateThemeUI(theme);
}
function toggleTheme(e) {
if (e) { e.preventDefault();
e.stopPropagation(); }
const current = getTheme();
const next = current === 'light' ? 'dark' : 'light';
setTheme(next);
}
function updateThemeUI(theme) {
const icon = document.getElementById('themeIcon');
const label = document.getElementById('themeLabel');
if (!icon) return;
if (theme === 'dark') {
icon.innerHTML =
`<circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>`;
if (label) label.textContent = '☀️ 亮色模式';
} else {
icon.innerHTML = `<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>`;
if (label) label.textContent = '🌙 暗色模式';
}
}
function applyTheme() {
const theme = getTheme();
document.documentElement.setAttribute('data-theme', theme);
updateThemeUI(theme);
}
+72
View File
@@ -0,0 +1,72 @@
// ============================================================
// 👤 用户主页
// ============================================================
async function renderUserProfile(username) {
const container = document.getElementById('userProfileContent');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
try {
const users = await apiFetch('/users?username=' + encodeURIComponent(username));
const user = users && users.length > 0 ? users[0] : null;
if (!user) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">用户不存在</div>';
return;
}
document.getElementById('userPageTitle').textContent = '👤 ' + user.username;
const posts = await apiFetch('/posts?user_id=' + user.id);
const avatar = user.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(user.username) + '&background=6366f1&color=fff&size=128';
let html = `
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:32px;text-align:center;">
<img src="${avatar}" style="width:96px;height:96px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" />
<h2 style="margin:16px 0 4px;font-size:24px;">${user.username}</h2>
<p style="color:var(--text-secondary);font-size:14px;">${user.bio || '这个人很懒,什么都没写'}</p>
<div style="display:flex;justify-content:center;gap:32px;margin-top:16px;font-size:14px;color:var(--text-secondary);flex-wrap:wrap;">
<span>📅 加入于 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span>📝 发了 ${posts.length} 个帖子</span>
${user.role === 'admin' ? '<span style="color:var(--primary);font-weight:600;">🛡️ 管理员</span>' : ''}
</div>
</div>
<h3 style="margin:24px 0 16px;font-size:18px;">📝 发布的帖子</h3>
`;
if (posts.length === 0) {
html += '<div style="color:#94a3b8;padding:20px 0;text-align:center;">还没有发帖</div>';
} else {
posts.forEach(p => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
html += `
<div class="post-card" style="cursor:pointer;" onclick="switchToPost('${p.id}')">
<div class="post-title" style="font-size:16px;font-weight:600;">${p.title || '无标题'}</div>
<div class="post-content" style="font-size:14px;color:var(--text-secondary);">${(p.content || '').substring(0, 100)}${(p.content || '').length > 100 ? '...' : ''}</div>
<div style="font-size:12px;color:var(--text-light);margin-top:8px;">${time}</div>
</div>
`;
});
}
container.innerHTML = html;
} catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message + '</div>';
}
}
function showUserPage(username) {
document.getElementById('app').style.display = 'none';
document.querySelectorAll('.page-slide').forEach(el => {
el.classList.remove('active', 'slide-out');
});
const el = document.getElementById('pageUser');
el.classList.add('active');
el.style.animation = 'none';
void el.offsetHeight;
el.style.animation = '';
currentPage = 'user';
renderUserProfile(username);
}