diff --git a/js/admin.js b/js/admin.js
new file mode 100644
index 0000000..ef751bf
--- /dev/null
+++ b/js/admin.js
@@ -0,0 +1,261 @@
+// ============================================================
+// 🛡️ 管理后台
+// ============================================================
+
+function renderAdminReports() {
+ const container = document.getElementById('adminContent');
+ container.innerHTML = '
加载中...
';
+ API.getReports().then(reports => {
+ if (!reports || reports.length === 0) {
+ container.innerHTML = '✅ 暂无举报
';
+ return;
+ }
+ let html = '';
+ const statusMap = { pending: '⏳ 待处理', approved: '✅ 已删除', rejected: '❌ 已驳回' };
+ reports.forEach(r => {
+ const postTitle = r.post_title || '无标题';
+ html += `
+
+
${r.reporter_name || '匿名'} 举报了帖子
+
原因:${r.reason}
+
帖子:${postTitle} — ${(r.post_content || '').substring(0, 30)}${(r.post_content || '').length > 30 ? '...' : ''}
+
状态:${statusMap[r.status] || r.status}
+ ${r.handler_name ? `
处理人:${r.handler_name}${r.handler_note ? ' (' + r.handler_note + ')' : ''}
` : ''}
+ ${r.status === 'pending' ? `
+
+
+
+
+ ` : ''}
+
+ `;
+ });
+ 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 = '加载失败
';
+ });
+}
+
+function renderAdminUsers() {
+ const container = document.getElementById('adminContent');
+ container.innerHTML = '加载中...
';
+ API.getUsers().then(users => {
+ let html = `
+
+ 共 ${users.length} 位用户
+
+
+
+
+
+ | 用户 |
+ 角色 |
+ 注册时间 |
+ 操作 |
+
+
+
+ `;
+ users.forEach(u => {
+ const isAdmin = u.role === 'admin';
+ const isCurrentUser = currentUser && currentUser.id === u.id;
+ html += `
+
+
+
+  + '&background=6366f1&color=fff&size=64'})
+ ${u.username}
+ ${isCurrentUser ? ' 你' : ''}
+
+ |
+
+
+ ${isAdmin ? '管理员' : '普通用户'}
+
+ |
+ ${u.created_at ? new Date(u.created_at).toLocaleDateString('zh-CN') : '—'} |
+
+ ${isCurrentUser ?
+ '不可操作自己' :
+ (isAdmin ?
+ `` :
+ ``
+ )
+ }
+ |
+
+ `;
+ });
+ html += '
';
+ 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 = '加载失败
';
+ });
+}
+
+function renderAdminLogs() {
+ const container = document.getElementById('adminContent');
+ container.innerHTML = '加载中...
';
+ API.getEventLogs().then(logs => {
+ if (!logs || logs.length === 0) {
+ container.innerHTML = '暂无日志
';
+ return;
+ }
+ let html =
+ '| 时间 | 用户 | 操作 |
';
+ logs.forEach(l => {
+ html += `
+
+ | ${new Date(l.created_at).toLocaleString('zh-CN')} |
+ ${l.username || '系统'} |
+ ${l.action} |
+
+ `;
+ });
+ html += '
';
+ container.innerHTML = html;
+ }).catch(() => {
+ container.innerHTML = '加载失败
';
+ });
+}
+
+function renderAdminLinks() {
+ const container = document.getElementById('adminContent');
+ container.innerHTML = `
+
+
+
+
+
+
+ `;
+
+ function loadLinks() {
+ API.getLinks().then(links => {
+ const ul = document.getElementById('linkList');
+ if (!links || links.length === 0) {
+ ul.innerHTML = '暂无友情链接
';
+ return;
+ }
+ let html = '';
+ links.forEach(l => {
+ html += `
+
+ `;
+ });
+ 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 = `
+ ⚙️ 论坛设置
+
+
+
+
+
+
+ `;
+
+ 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]();
+ });
+});
\ No newline at end of file
diff --git a/js/api.js b/js/api.js
new file mode 100644
index 0000000..3285446
--- /dev/null
+++ b/js/api.js
@@ -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;
+ }
+};
\ No newline at end of file
diff --git a/js/app.js b/js/app.js
new file mode 100644
index 0000000..93bf4b3
--- /dev/null
+++ b/js/app.js
@@ -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);
\ No newline at end of file
diff --git a/js/auth.js b/js/auth.js
new file mode 100644
index 0000000..04b1646
--- /dev/null
+++ b/js/auth.js
@@ -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');
+});
\ No newline at end of file
diff --git a/js/captcha.js b/js/captcha.js
new file mode 100644
index 0000000..97f9aca
--- /dev/null
+++ b/js/captcha.js
@@ -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;
+ }
+}
\ No newline at end of file
diff --git a/js/feed.js b/js/feed.js
new file mode 100644
index 0000000..abef2cb
--- /dev/null
+++ b/js/feed.js
@@ -0,0 +1,128 @@
+// ============================================================
+// 📋 帖子列表
+// ============================================================
+
+let currentSort = 'latest';
+
+function renderFeed() {
+ const container = document.getElementById('postList');
+ container.innerHTML = '加载中...
';
+ API.getPosts(currentSort).then(posts => {
+ if (!posts || posts.length === 0) {
+ container.innerHTML =
+ '✨ 还没有帖子,快来发布第一条吧!
';
+ 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 = '';
+ p.images.forEach(img => {
+ imagesHtml += '

';
+ });
+ imagesHtml += '
';
+ }
+ const replyCount = p.reply_count || 0;
+ html += `
+
+
+
${p.title || '无标题'}
+
${(p.content || '').replace(/\n/g, '
')}
+ ${imagesHtml}
+
+
+
+ ${replyCount}
+
+
+ ${currentUser && currentUser.id === p.user_id ? `
` : ''}
+
+
+ `;
+ });
+ 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 = '加载失败:' + err.message +
+ '
';
+ });
+}
+
+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 = '暂无链接';
+ return;
+ }
+ let html = '';
+ links.forEach(l => {
+ html += '' + l.title + '';
+ });
+ 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();
+ }
+ });
+});
\ No newline at end of file
diff --git a/js/post.js b/js/post.js
new file mode 100644
index 0000000..630a766
--- /dev/null
+++ b/js/post.js
@@ -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 = '加载中...
';
+ 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 = '';
+ post.images.forEach(img => {
+ imagesHtml += '

';
+ });
+ imagesHtml += '
';
+ }
+
+ let html = `
+
+
+
${post.title || '无标题'}
+
${(post.content || '').replace(/\n/g, '
')}
+ ${imagesHtml}
+
+
+
+ ${replies.length} 条回复
+
+
+ `;
+
+ if (replies.length === 0) {
+ html += '
还没有回复,快来抢沙发吧 🛋️
';
+ } 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 += `
+
+
+
${(r.content || '').replace(/\n/g, '
')}
+
+ `;
+ });
+ }
+
+ html += '
';
+ 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 = '加载失败:' + err.message +
+ '
';
+ 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);
+ }
+}
\ No newline at end of file
diff --git a/js/theme.js b/js/theme.js
new file mode 100644
index 0000000..b205a3c
--- /dev/null
+++ b/js/theme.js
@@ -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 =
+ ``;
+ if (label) label.textContent = '☀️ 亮色模式';
+ } else {
+ icon.innerHTML = ``;
+ if (label) label.textContent = '🌙 暗色模式';
+ }
+}
+
+function applyTheme() {
+ const theme = getTheme();
+ document.documentElement.setAttribute('data-theme', theme);
+ updateThemeUI(theme);
+}
\ No newline at end of file
diff --git a/js/user.js b/js/user.js
new file mode 100644
index 0000000..1b7ea5e
--- /dev/null
+++ b/js/user.js
@@ -0,0 +1,72 @@
+// ============================================================
+// 👤 用户主页
+// ============================================================
+
+async function renderUserProfile(username) {
+ const container = document.getElementById('userProfileContent');
+ container.innerHTML = '加载中...
';
+
+ try {
+ const users = await apiFetch('/users?username=' + encodeURIComponent(username));
+ const user = users && users.length > 0 ? users[0] : null;
+
+ if (!user) {
+ container.innerHTML = '用户不存在
';
+ 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 = `
+
+

+
${user.username}
+
${user.bio || '这个人很懒,什么都没写'}
+
+ 📅 加入于 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}
+ 📝 发了 ${posts.length} 个帖子
+ ${user.role === 'admin' ? '🛡️ 管理员' : ''}
+
+
+ 📝 发布的帖子
+ `;
+
+ if (posts.length === 0) {
+ html += '还没有发帖
';
+ } else {
+ posts.forEach(p => {
+ const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
+ html += `
+
+
${p.title || '无标题'}
+
${(p.content || '').substring(0, 100)}${(p.content || '').length > 100 ? '...' : ''}
+
${time}
+
+ `;
+ });
+ }
+
+ container.innerHTML = html;
+
+ } catch (err) {
+ container.innerHTML = '加载失败:' + err.message + '
';
+ }
+}
+
+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);
+}
\ No newline at end of file