diff --git a/js/admin.js b/js/admin.js deleted file mode 100644 index cfd7089..0000000 --- a/js/admin.js +++ /dev/null @@ -1,834 +0,0 @@ -// ============================================================ -// 🛡️ 管理后台 -// ============================================================ - -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 = '
加载失败
'; - }); -} - -// ============================================================ -// 👥 用户列表(支持分页 + 搜索) -// ============================================================ - -let currentUsersPage = 1; -let usersTotalPages = 1; -let usersSearchKeyword = ''; - -function renderAdminUsers(page = 1, search = '') { - const container = document.getElementById('adminContent'); - container.innerHTML = '
加载中...
'; - - currentUsersPage = page; - usersSearchKeyword = search; - - API.getUsers(page, 20, search).then(result => { - const users = result.data || []; - const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 }; - usersTotalPages = pagination.totalPages || 1; - - let html = ` -
- 共 ${pagination.total} 位用户 -
- - - -
-
-
- - - - - - - - - - - `; - - if (users.length === 0) { - html += ``; - } else { - users.forEach(u => { - const isAdmin = u.role === 'admin'; - const isCurrentUser = currentUser && currentUser.id === u.id; - html += ` - - - - - - - `; - }); - } - - html += '
用户角色注册时间操作
暂无用户
-
- - ${u.username} - ${isCurrentUser ? '你' : ''} -
-
- - ${isAdmin ? '管理员' : '普通用户'} - - ${u.created_at ? new Date(u.created_at).toLocaleDateString('zh-CN') : '—'} - ${isCurrentUser ? - '不可操作自己' : - (isAdmin ? - `` : - `` - ) - } -
'; - - // 分页控件 - if (usersTotalPages > 1) { - html += ` -
- - `; - - let startPage = Math.max(1, page - 4); - let endPage = Math.min(usersTotalPages, page + 4); - - if (page <= 4) endPage = Math.min(usersTotalPages, 9); - if (page > usersTotalPages - 4) startPage = Math.max(1, usersTotalPages - 8); - - if (startPage > 1) { - html += ``; - if (startPage > 2) html += `…`; - } - - for (let i = startPage; i <= endPage; i++) { - const isActive = i === page; - html += ` - - `; - } - - if (endPage < usersTotalPages) { - if (endPage < usersTotalPages - 1) html += `…`; - html += ``; - } - - html += ` - - - ${pagination.total} 位用户 - -
- `; - } - - container.innerHTML = html; - - // 绑定分页按钮事件 - container.querySelectorAll('.users-page-btn:not([disabled])').forEach(btn => { - btn.addEventListener('click', function() { - const newPage = parseInt(this.dataset.page); - if (newPage >= 1 && newPage <= usersTotalPages) { - renderAdminUsers(newPage, usersSearchKeyword); - } - }); - }); - - // 绑定角色切换事件 - 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(currentUsersPage, usersSearchKeyword); - }).catch(err => alert('操作失败:' + err.message)); - }); - }); - - // 搜索按钮 - const searchBtn = document.getElementById('userSearchBtn'); - if (searchBtn) { - searchBtn.addEventListener('click', function() { - const input = document.getElementById('userSearchInput'); - renderAdminUsers(1, input.value.trim()); - }); - } - - // 清空搜索 - const clearBtn = document.getElementById('userClearSearchBtn'); - if (clearBtn) { - clearBtn.addEventListener('click', function() { - const input = document.getElementById('userSearchInput'); - input.value = ''; - renderAdminUsers(1, ''); - }); - } - - // 回车搜索 - const searchInput = document.getElementById('userSearchInput'); - if (searchInput) { - searchInput.addEventListener('keydown', function(e) { - if (e.key === 'Enter') { - renderAdminUsers(1, this.value.trim()); - } - }); - } - - }).catch(() => { - container.innerHTML = '
加载失败
'; - }); -} - -// ============================================================ -// 📜 操作日志(支持分页) -// ============================================================ - -function renderAdminLogs(page = 1) { - const container = document.getElementById('adminContent'); - container.innerHTML = '
加载中...
'; - - API.getEventLogs(page, 20).then(result => { - const logs = result.data || []; - const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 }; - const totalPages = pagination.totalPages || 1; - - if (!logs || logs.length === 0) { - container.innerHTML = '
暂无日志
'; - return; - } - - let html = ` - - - - - - - - - - `; - logs.forEach(l => { - html += ` - - - - - - `; - }); - html += '
时间用户操作
${new Date(l.created_at).toLocaleString('zh-CN')}${l.username || '系统'}${l.action}
'; - - // 分页控件 - if (totalPages > 1) { - html += ` -
- - `; - - let startPage = Math.max(1, page - 4); - let endPage = Math.min(totalPages, page + 4); - - if (page <= 4) endPage = Math.min(totalPages, 9); - if (page > totalPages - 4) startPage = Math.max(1, totalPages - 8); - - if (startPage > 1) { - html += ``; - if (startPage > 2) html += `…`; - } - - for (let i = startPage; i <= endPage; i++) { - const isActive = i === page; - html += ` - - `; - } - - if (endPage < totalPages) { - if (endPage < totalPages - 1) html += `…`; - html += ``; - } - - html += ` - - - ${pagination.total} 条日志 - -
- `; - } - - container.innerHTML = html; - - // 绑定分页按钮事件 - container.querySelectorAll('.logs-page-btn:not([disabled])').forEach(btn => { - btn.addEventListener('click', function() { - const newPage = parseInt(this.dataset.page); - if (newPage >= 1 && newPage <= totalPages) { - renderAdminLogs(newPage); - } - }); - }); - - }).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 += ` -
- ${l.title} - -
- `; - }); - 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'; - } - }); -} - -// ============================================================ -// 🎨 自定义 CSS(独立标签页) -// ============================================================ - -function renderAdminCustomCSS() { - const container = document.getElementById('adminContent'); - container.innerHTML = ` -

🎨 自定义 CSS

-

上传 style.css 覆盖默认样式,自定义论坛外观。

- -
-
- -

- 点击或拖拽上传 style.css -

-

只能上传 style.css 文件

- -
-
- -
- - -
-
- `; - - // 自定义 CSS 上传逻辑 - const dropZone = document.getElementById('customCssDropZone'); - const fileInput = document.getElementById('customCssInput'); - const dropText = document.getElementById('customCssDropText'); - const statusEl = document.getElementById('customCssStatus'); - - let selectedFile = null; - - if (dropZone && fileInput) { - dropZone.addEventListener('click', function() { - fileInput.click(); - }); - - fileInput.addEventListener('change', function() { - if (this.files.length > 0) { - handleCssFile(this.files[0]); - } - }); - - dropZone.addEventListener('dragover', function(e) { - e.preventDefault(); - this.style.borderColor = 'var(--primary)'; - this.style.background = 'var(--primary-bg)'; - dropText.textContent = '松开上传'; - }); - - dropZone.addEventListener('dragleave', function(e) { - e.preventDefault(); - this.style.borderColor = 'var(--border)'; - this.style.background = 'var(--bg)'; - dropText.textContent = '点击或拖拽上传 style.css'; - }); - - dropZone.addEventListener('drop', function(e) { - e.preventDefault(); - this.style.borderColor = 'var(--border)'; - this.style.background = 'var(--bg)'; - dropText.textContent = '点击或拖拽上传 style.css'; - if (e.dataTransfer.files.length > 0) { - handleCssFile(e.dataTransfer.files[0]); - } - }); - } - - function handleCssFile(file) { - if (file.name !== 'style.css') { - statusEl.textContent = '❌ 文件名必须是 style.css'; - statusEl.style.color = '#ef4444'; - selectedFile = null; - fileInput.value = ''; - return; - } - if (!file.type.includes('text/css') && !file.name.endsWith('.css')) { - statusEl.textContent = '❌ 请上传 CSS 文件'; - statusEl.style.color = '#ef4444'; - selectedFile = null; - fileInput.value = ''; - return; - } - selectedFile = file; - statusEl.textContent = '✅ 已选择: ' + file.name + ' (' + (file.size / 1024).toFixed(1) + ' KB)'; - statusEl.style.color = '#22c55e'; - } - - document.getElementById('customCssSaveBtn').addEventListener('click', function() { - if (!selectedFile) { - statusEl.textContent = '⚠️ 请先选择 style.css 文件'; - statusEl.style.color = '#f59e0b'; - return; - } - - showCustomCssWarningModal(async function() { - try { - await API.uploadCustomCSS(selectedFile); - statusEl.textContent = '✅ CSS 上传成功!刷新页面查看效果'; - statusEl.style.color = '#22c55e'; - selectedFile = null; - fileInput.value = ''; - dropText.textContent = '点击或拖拽上传 style.css'; - loadCustomCSS(); - } catch (err) { - statusEl.textContent = '❌ 上传失败:' + err.message; - statusEl.style.color = '#ef4444'; - } - }); - }); - - document.getElementById('customCssDeleteBtn').addEventListener('click', async function() { - if (!confirm('确定要删除自定义 CSS 吗?将恢复默认样式。')) return; - try { - await API.deleteCustomCSS(); - statusEl.textContent = '✅ 已删除自定义 CSS'; - statusEl.style.color = '#22c55e'; - const link = document.getElementById('customCssLink'); - if (link) link.remove(); - } catch (err) { - statusEl.textContent = '❌ 删除失败:' + err.message; - statusEl.style.color = '#ef4444'; - } - }); -} - -// ============================================================ -// 📄 自定义页面管理 -// ============================================================ - -let editingPageId = null; - -function renderAdminCustomPages() { - const container = document.getElementById('adminContent'); - container.innerHTML = ` -
-

📄 自定义页面

- -
-
- `; - - loadCustomPageList(); - - document.getElementById('addCustomPageBtn').addEventListener('click', function() { - editingPageId = null; - openCustomPageEditor(); - }); -} - -function loadCustomPageList() { - const container = document.getElementById('customPageList'); - container.innerHTML = '
加载中...
'; - API.getAdminCustomPages().then(pages => { - if (pages.length === 0) { - container.innerHTML = '
暂无自定义页面
'; - return; - } - let html = `
- - - - - - - - - - - - `; - pages.forEach(p => { - html += ` - - - - - - - - `; - }); - html += '
名称标题URL状态操作
${p.name}${p.title}?custom=${p.name}${p.enabled ? '✅ 启用' : '❌ 禁用'} - - -
'; - container.innerHTML = html; - - container.querySelectorAll('[data-action="edit"]').forEach(btn => { - btn.addEventListener('click', function() { - const page = pages.find(p => p.id === this.dataset.id); - if (page) { - editingPageId = page.id; - openCustomPageEditor(page); - } - }); - }); - - container.querySelectorAll('[data-action="delete"]').forEach(btn => { - btn.addEventListener('click', function() { - if (!confirm('确定要删除这个页面吗?')) return; - API.deleteCustomPage(this.dataset.id).then(() => { - loadCustomPageList(); - loadCustomPagesNav(); - }).catch(err => alert('删除失败:' + err.message)); - }); - }); - }).catch(err => { - container.innerHTML = '
加载失败
'; - }); -} - -function openCustomPageEditor(page) { - const isEdit = !!page; - const modal = document.createElement('div'); - modal.className = 'modal active'; - modal.style.display = 'flex'; - modal.innerHTML = ` - - `; - - document.body.appendChild(modal); - - modal.querySelector('.close').addEventListener('click', function() { - modal.remove(); - }); - modal.addEventListener('click', function(e) { - if (e.target === this) modal.remove(); - }); - - modal.querySelector('#editorSaveBtn').addEventListener('click', async function() { - const name = document.getElementById('editorPageName').value.trim(); - const title = document.getElementById('editorPageTitle').value.trim(); - const content = document.getElementById('editorContent').value.trim(); - const enabled = document.getElementById('editorEnabled').value === 'true'; - - if (!name) { alert('请输入页面名称'); return; } - if (!title) { alert('请输入导航栏显示名称'); return; } - if (!content) { alert('请输入页面内容'); return; } - if (!/^[a-zA-Z0-9\-_]+$/.test(name)) { - alert('页面名称只允许字母、数字、短横线和下划线'); - return; - } - - try { - if (isEdit) { - await API.updateCustomPage(page.id, title, content, enabled); - } else { - await API.createCustomPage(name, title, content); - } - modal.remove(); - loadCustomPageList(); - loadCustomPagesNav(); - } catch (err) { - alert('保存失败:' + err.message); - } - }); -} - -// ============================================================ -// 自定义 CSS 警告模态框 -// ============================================================ - -function showCustomCssWarningModal(onConfirm) { - const modal = document.createElement('div'); - modal.className = 'modal active'; - modal.style.display = 'flex'; - modal.innerHTML = ` - - `; - - document.body.appendChild(modal); - - modal.querySelector('#cssWarningConfirm').addEventListener('click', function() { - modal.remove(); - if (onConfirm) onConfirm(); - }); - - modal.querySelector('#cssWarningCancel').addEventListener('click', function() { - modal.remove(); - }); - - modal.addEventListener('click', function(e) { - if (e.target === this) modal.remove(); - }); -} - -// ============================================================ -// 加载自定义 CSS -// ============================================================ - -function loadCustomCSS() { - const existing = document.getElementById('customCssLink'); - if (existing) existing.remove(); - - const link = document.createElement('link'); - link.id = 'customCssLink'; - link.rel = 'stylesheet'; - link.href = CONFIG.API_BASE_URL + '/custom-css?v=' + Date.now(); - link.onerror = function() { - // 如果自定义 CSS 不存在,静默失败 - }; - document.head.appendChild(link); -} - -// ============================================================ -// 管理后台Tab切换(侧边栏适配) -// ============================================================ - -// 使用事件委托监听 .admin-nav 下的点击 -document.querySelector('.admin-nav')?.addEventListener('click', function(e) { - const tabLink = e.target.closest('.admin-nav-item'); - if (!tabLink) return; - - e.preventDefault(); - const tab = tabLink.dataset.tab; - if (!tab) return; - - // 切换高亮 - document.querySelectorAll('.admin-nav-item').forEach(el => el.classList.remove('active')); - tabLink.classList.add('active'); - - // 渲染对应内容 - const tabMap = { - reports: renderAdminReports, - users: renderAdminUsers, - logs: renderAdminLogs, - links: renderAdminLinks, - 'custom-css': renderAdminCustomCSS, - settings: renderAdminSettings, - custom: renderAdminCustomPages - }; - if (tabMap[tab]) tabMap[tab](); -}); - -// 页面加载时尝试加载自定义 CSS -document.addEventListener('DOMContentLoaded', function() { - setTimeout(loadCustomCSS, 500); -}); diff --git a/js/api.js b/js/api.js deleted file mode 100644 index f0d0812..0000000 --- a/js/api.js +++ /dev/null @@ -1,441 +0,0 @@ -// ============================================================ -// 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, page = 1, limit = 20) { - const data = await apiFetch('/posts?sort=' + (sort || 'latest') + '&page=' + page + '&limit=' + limit); - 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 updatePost(postId, title, content) { - const data = await apiFetch('/posts/' + postId, { - method: 'PUT', - body: JSON.stringify({ title, content }) - }); - 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 togglePinPost(postId) { - const data = await apiFetch('/posts/' + postId + '/pin', { - method: 'PUT' - }); - 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(page = 1, limit = 20, search = '') { - const data = await apiFetch('/users?page=' + page + '&limit=' + limit + '&search=' + encodeURIComponent(search)); - 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(page = 1, limit = 20) { - const data = await apiFetch('/event-logs?page=' + page + '&limit=' + limit); - 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; - }, - - // ============================================================ - // 私信 - // ============================================================ - async getConversations() { - const data = await apiFetch('/conversations'); - if (data.error) throw new Error(data.error); - return data || []; - }, - - async getOrCreateConversation(other_user_id) { - const data = await apiFetch('/conversations', { - method: 'POST', - body: JSON.stringify({ other_user_id }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - async getMessages(conversationId) { - const data = await apiFetch('/conversations/' + conversationId + '/messages'); - if (data.error) throw new Error(data.error); - return data || []; - }, - - async sendMessage(conversationId, content) { - const data = await apiFetch('/conversations/' + conversationId + '/messages', { - method: 'POST', - body: JSON.stringify({ content }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - async markMessageRead(messageId) { - const data = await apiFetch('/messages/' + messageId + '/read', { - method: 'PUT' - }); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 自定义页面 - // ============================================================ - async getCustomPages() { - const data = await apiFetch('/custom-pages'); - if (data.error) throw new Error(data.error); - return data || []; - }, - - async getCustomPage(name) { - const data = await apiFetch('/custom-pages/' + encodeURIComponent(name)); - if (data.error) throw new Error(data.error); - return data; - }, - - async getAdminCustomPages() { - const data = await apiFetch('/admin/custom-pages'); - if (data.error) throw new Error(data.error); - return data || []; - }, - - async createCustomPage(name, title, content) { - const data = await apiFetch('/admin/custom-pages', { - method: 'POST', - body: JSON.stringify({ name, title, content }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - async updateCustomPage(id, title, content, enabled) { - const data = await apiFetch('/admin/custom-pages/' + id, { - method: 'PUT', - body: JSON.stringify({ title, content, enabled }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - async deleteCustomPage(id) { - const data = await apiFetch('/admin/custom-pages/' + id, { method: 'DELETE' }); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 头像 - // ============================================================ - async updateAvatar(userId, avatar_url) { - const data = await apiFetch('/users/' + userId + '/avatar', { - method: 'PUT', - body: JSON.stringify({ avatar_url }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 恢复码 - // ============================================================ - async generateRecoveryCodes() { - const data = await apiFetch('/auth/recovery-codes/generate', { - method: 'POST' - }); - if (data.error) throw new Error(data.error); - return data; - }, - - async getRecoveryCodesCount() { - const data = await apiFetch('/auth/recovery-codes/count'); - if (data.error) throw new Error(data.error); - return data; - }, - - async resetPassword(email, recoveryCode, newPassword) { - const data = await apiFetch('/auth/reset-password', { - method: 'POST', - body: JSON.stringify({ email, recoveryCode, newPassword }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 修改密码和邮箱 - // ============================================================ - async changePassword(oldPassword, newPassword) { - const data = await apiFetch('/users/' + currentUser.id + '/password', { - method: 'PUT', - body: JSON.stringify({ oldPassword, newPassword }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - async changeEmail(password, newEmail) { - const data = await apiFetch('/users/' + currentUser.id + '/email', { - method: 'PUT', - body: JSON.stringify({ password, newEmail }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 置顶 - // ============================================================ - - async togglePinPost(postId) { - const data = await apiFetch('/posts/' + postId + '/pin', { - method: 'PUT' - }); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 更新用户资料(含签名) - // ============================================================ - async updateProfile(userId, username, bio, signature) { - const data = await apiFetch('/users/' + userId, { - method: 'PUT', - body: JSON.stringify({ username, bio, signature }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 自定义 CSS - // ============================================================ - - async uploadCustomCSS(file) { - const formData = new FormData(); - formData.append('file', file); - - const url = CONFIG.API_BASE_URL + '/admin/custom-css'; - const response = await fetch(url, { - method: 'POST', - headers: { - 'Authorization': 'Bearer ' + localStorage.getItem('forumlify-token') - }, - body: formData - }); - const data = await response.json(); - if (data.error) throw new Error(data.error); - return data; - }, - - async deleteCustomCSS() { - const data = await apiFetch('/admin/custom-css', { - method: 'DELETE' - }); - if (data.error) throw new Error(data.error); - return data; - } -}; diff --git a/js/app.js b/js/app.js deleted file mode 100644 index efbd78f..0000000 --- a/js/app.js +++ /dev/null @@ -1,1299 +0,0 @@ -// ============================================================ -// 🚀 主入口 -// =========================================================== - -let currentUser = null; -let currentPage = 'feed'; -let currentPageNum = 1; - -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'; - updateUnreadBadge(); - } 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 === 'post' && param) { - url.searchParams.set('post', param); - url.searchParams.delete('page'); - url.searchParams.delete('user'); - window.history.pushState({ page: 'post', postId: param }, '', url); - showPostPage(param); - return; - } - - if (page === 'custom' && param) { - url.searchParams.set('custom', param); - url.searchParams.delete('page'); - url.searchParams.delete('post'); - url.searchParams.delete('user'); - window.history.pushState({ page: 'custom', custom: param }, '', url); - showCustomPage(param); - return; - } - - if (page === 'feed') { - url.searchParams.delete('page'); - url.searchParams.delete('post'); - url.searchParams.delete('user'); - url.searchParams.delete('custom'); - } else { - url.searchParams.set('page', page); - url.searchParams.delete('post'); - url.searchParams.delete('user'); - url.searchParams.delete('custom'); - } - window.history.pushState({ page: page }, '', url); - - document.getElementById('app').style.display = 'none'; - document.querySelectorAll('.page-slide').forEach(el => { - el.classList.remove('active', 'slide-out'); - }); - - const customContainer = document.getElementById('customPageContainer'); - if (customContainer) { - customContainer.classList.remove('active'); - customContainer.style.display = 'none'; - } - - 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') { - renderSettingsPage('profile'); - } - if (page === 'messages') { - renderMessagesPage(); - } - if (page === 'new') { - document.getElementById('postTitle').value = ''; - document.getElementById('postContent').value = ''; - document.getElementById('imagePreview').innerHTML = ''; - document.getElementById('fileInput').value = ''; - document.getElementById('postCaptchaInput').value = ''; - refreshCaptcha('post'); - const dropText = document.getElementById('dropZoneText'); - if (dropText) dropText.textContent = '点击或拖拽上传图片'; - } - } -} - -// ============================================================ -// ✉️ 私信系统 -// ============================================================ - -let currentChatUserId = null; -let currentChatUsername = null; -let currentConversationId = null; -let messagePollInterval = null; - -async function updateUnreadBadge() { - const badge = document.getElementById('messageBadge'); - if (!badge || !currentUser) return; - try { - const conversations = await API.getConversations(); - const totalUnread = conversations.reduce((sum, c) => sum + (c.unread_count || 0), 0); - if (totalUnread > 0) { - badge.style.display = 'inline-block'; - badge.textContent = totalUnread > 99 ? '99+' : totalUnread; - } else { - badge.style.display = 'none'; - } - } catch (e) {} -} - -function openMessageList() { - document.getElementById('messageListModal').classList.add('active'); - renderMessageList(); -} - -function closeMessageList() { - document.getElementById('messageListModal').classList.remove('active'); - if (messagePollInterval) { - clearInterval(messagePollInterval); - messagePollInterval = null; - } -} - -async function renderMessageList() { - const container = document.getElementById('messageListContent'); - container.innerHTML = '
加载中...
'; - - try { - const conversations = await API.getConversations(); - if (conversations.length === 0) { - container.innerHTML = '
暂无私信
'; - return; - } - let html = ''; - conversations.forEach(c => { - const unread = c.unread_count || 0; - const lastMsg = c.last_message || '暂无消息'; - const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString('zh-CN') : ''; - html += ` -
- -
-
- ${c.other_username} - ${time} -
-
- ${lastMsg} - ${unread > 0 ? `${unread}` : ''} -
-
-
- `; - }); - container.innerHTML = html; - } catch (err) { - container.innerHTML = '
加载失败
'; - } -} - -function openChat(conversationId, otherUserId, otherUsername) { - currentConversationId = conversationId; - currentChatUserId = otherUserId; - currentChatUsername = otherUsername; - - document.getElementById('chatModal').classList.add('active'); - document.getElementById('chatTitle').textContent = otherUsername; - - renderMessages(conversationId); - - if (messagePollInterval) clearInterval(messagePollInterval); - messagePollInterval = setInterval(() => { - if (currentConversationId) { - renderMessages(currentConversationId, true); - } - }, 3000); -} - -function closeChat() { - document.getElementById('chatModal').classList.remove('active'); - if (messagePollInterval) { - clearInterval(messagePollInterval); - messagePollInterval = null; - } - currentConversationId = null; - currentChatUserId = null; - currentChatUsername = null; - updateUnreadBadge(); -} - -async function renderMessages(conversationId, silent = false) { - const container = document.getElementById('chatMessages'); - if (!silent) { - container.innerHTML = '
加载中...
'; - } - - try { - const messages = await API.getMessages(conversationId); - if (messages.length === 0) { - container.innerHTML = '
还没有消息,打个招呼吧 👋
'; - return; - } - let html = ''; - messages.forEach(m => { - const isMine = m.sender_id === currentUser.id; - const time = m.created_at ? new Date(m.created_at).toLocaleString('zh-CN') : ''; - html += ` -
- ${!isMine ? `` : ''} -
-
- ${m.content} -
-
- ${time} ${isMine ? (m.is_read ? '✓✓' : '✓') : ''} -
-
-
- `; - }); - container.innerHTML = html; - container.scrollTop = container.scrollHeight; - } catch (err) { - if (!silent) { - container.innerHTML = '
加载失败
'; - } - } -} - -async function sendMessage() { - const input = document.getElementById('chatInput'); - const content = input.value.trim(); - if (!content || !currentConversationId) return; - - try { - await API.sendMessage(currentConversationId, content); - input.value = ''; - renderMessages(currentConversationId); - updateUnreadBadge(); - if (document.getElementById('messageListModal').classList.contains('active')) { - renderMessageList(); - } - } catch (err) { - alert('发送失败:' + err.message); - } -} - -async function openPrivateChat(otherUserId, otherUsername) { - try { - const result = await API.getOrCreateConversation(otherUserId); - currentConversationId = result.id; - currentChatUserId = otherUserId; - currentChatUsername = otherUsername; - - document.getElementById('chatModal').classList.add('active'); - document.getElementById('chatTitle').textContent = otherUsername; - - renderMessages(currentConversationId); - - if (messagePollInterval) clearInterval(messagePollInterval); - messagePollInterval = setInterval(() => { - if (currentConversationId) { - renderMessages(currentConversationId, true); - } - }, 3000); - } catch (err) { - alert('打开私信失败:' + err.message); - } -} - -// ============================================================ -// 📸 图片上传(拖拽上传) -// ============================================================ - -function handleImageFiles(files) { - const preview = document.getElementById('imagePreview'); - if (!preview) return; - for (let file of files) { - if (!file.type.startsWith('image/')) continue; - if (file.size > 5 * 1024 * 1024) { - alert('图片 ' + file.name + ' 超过 5MB,请压缩后上传'); - continue; - } - 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 var(--border);'; - preview.appendChild(img); - }; - reader.readAsDataURL(file); - } - const fileInput = document.getElementById('fileInput'); - if (fileInput) fileInput.value = ''; -} - -// ============================================================ -// 📄 自定义页面导航 -// ============================================================ - -let customPagesNav = []; - -async function loadCustomPagesNav() { - try { - const pages = await API.getCustomPages(); - customPagesNav = pages; - renderCustomPagesNav(); - } catch (e) { - customPagesNav = []; - } -} - -function renderCustomPagesNav() { - const container = document.getElementById('customNavLinks'); - if (!container) return; - container.innerHTML = ''; - - customPagesNav.forEach(page => { - const link = document.createElement('a'); - link.href = '#'; - link.dataset.custom = page.name; - link.textContent = page.title; - link.style.cssText = 'color:var(--text-secondary);text-decoration:none;font-size:14px;padding:4px 10px;border-radius:4px;transition:color 0.15s;'; - link.addEventListener('mouseenter', function() { - this.style.color = 'var(--text)'; - }); - link.addEventListener('mouseleave', function() { - this.style.color = 'var(--text-secondary)'; - }); - link.addEventListener('click', function(e) { - e.preventDefault(); - switchPage('custom', page.name); - }); - container.appendChild(link); - }); -} - -// ============================================================ -// 📄 自定义页面渲染 -// ============================================================ - -function showCustomPage(pageName) { - document.getElementById('app').style.display = 'none'; - document.querySelectorAll('.page-slide').forEach(el => { - el.classList.remove('active', 'slide-out'); - }); - - let container = document.getElementById('customPageContainer'); - if (!container) { - container = document.createElement('div'); - container.id = 'customPageContainer'; - container.className = 'page-slide'; - container.style.cssText = 'display:none;position:fixed;inset:0;background:var(--bg);z-index:50;padding:84px 32px 40px;overflow-y:auto;transition:background 0.2s;'; - document.body.appendChild(container); - } - - container.innerHTML = '
加载中...
'; - container.classList.add('active'); - container.style.display = 'block'; - currentPage = 'custom'; - - API.getCustomPage(pageName).then(page => { - const iframe = document.createElement('iframe'); - iframe.style.cssText = 'width:100%;min-height:70vh;border:none;border-radius:8px;background:var(--surface);'; - iframe.sandbox = 'allow-scripts allow-modals allow-same-origin'; - iframe.srcdoc = ` - - - - - - - ${page.content} - - - - `; - container.innerHTML = ''; - container.appendChild(iframe); - - document.querySelectorAll('.custom-page-nav-link').forEach(el => { - el.style.color = el.dataset.custom === pageName ? 'var(--primary)' : 'var(--text-secondary)'; - }); - }).catch(err => { - container.innerHTML = '
页面加载失败:' + err.message + '
'; - }); -} - -// ============================================================ -// 📩 消息页面 -// ============================================================ - -async function renderMessagesPage() { - const container = document.getElementById('messagesContent'); - if (!container) return; - container.innerHTML = '
加载中...
'; - - try { - const notifications = await apiFetch('/notifications'); - if (notifications.error) throw new Error(notifications.error); - - if (notifications.length === 0) { - container.innerHTML = ` -
- -

暂无消息

-

当有人回复你的帖子或处理你的举报时,会在这里通知你

-
- `; - return; - } - - await apiFetch('/notifications/read-all', { method: 'PUT' }); - - let html = ''; - const typeMap = { - reply: '💬', - post_deleted: '🗑️', - report_handled: '🛡️', - system: '📢' - }; - notifications.forEach(n => { - const icon = typeMap[n.type] || '📌'; - const time = n.created_at ? new Date(n.created_at).toLocaleString('zh-CN') : ''; - html += ` -
- ${icon} -
-
${n.title}
-
${n.content}
- ${n.link ? `查看详情 →` : ''} -
${time}
-
-
- `; - }); - container.innerHTML = html; - } catch (err) { - container.innerHTML = '
加载失败
'; - } -} - -// ============================================================ -// ⚙️ 设置页面(含侧边栏) -// ============================================================ - -let currentSettingsTab = 'profile'; - -async function renderSettingsPage(tab = 'profile') { - const container = document.getElementById('settingsContent'); - if (!container) return; - - // 更新侧边栏高亮 - document.querySelectorAll('.settings-nav-item').forEach(el => el.classList.remove('active')); - document.querySelector(`.settings-nav-item[data-settings-tab="${tab}"]`)?.classList.add('active'); - currentSettingsTab = tab; - - if (!currentUser) { - container.innerHTML = '
请先登录
'; - return; - } - - const user = currentUser; - - try { - const userPosts = await apiFetch('/posts?user_id=' + user.id); - const postCount = userPosts.data ? userPosts.data.length : 0; - - let recoveryCount = 0; - try { - const countData = await API.getRecoveryCodesCount(); - recoveryCount = countData.count || 0; - } catch (e) {} - - if (tab === 'profile') { - container.innerHTML = ` -

👤 个人资料

- - -
-
- - -
- -

${user.username}

-

${user.bio || '这个人很懒,什么都没写'}

-
- 📅 加入 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'} - 📝 ${postCount} 帖 - ${user.role === 'admin' ? '🛡️ 管理员' : ''} -
-
-
- - -
-
- - -
-
- - -
-
- - -
用 --- 分隔,支持 Markdown
-
- -
- `; - - // ===== 头像上传 ===== - const avatarBtn = document.getElementById('avatarUploadBtn'); - const avatarInput = document.getElementById('avatarFileInput'); - const avatarPreview = document.getElementById('avatarPreview'); - const statusEl = document.getElementById('avatarUploadStatus'); - - if (avatarBtn && avatarInput) { - avatarBtn.addEventListener('click', function() { - avatarInput.click(); - }); - - avatarInput.addEventListener('change', async function() { - const file = this.files[0]; - if (!file) return; - if (!file.type.startsWith('image/')) { - statusEl.textContent = '❌ 请选择图片文件'; - statusEl.style.color = '#ef4444'; - return; - } - if (file.size > 5 * 1024 * 1024) { - statusEl.textContent = '❌ 图片不能超过 5MB'; - statusEl.style.color = '#ef4444'; - return; - } - - statusEl.textContent = '⏳ 上传中...'; - statusEl.style.color = 'var(--text-secondary)'; - - try { - const formData = new FormData(); - formData.append('file', file); - - const uploadRes = await fetch(CONFIG.API_BASE_URL + '/upload', { - method: 'POST', - headers: { - 'Authorization': 'Bearer ' + localStorage.getItem('forumlify-token') - }, - body: formData - }); - const uploadData = await uploadRes.json(); - if (uploadData.error) throw new Error(uploadData.error); - - const avatarUrl = uploadData.url; - - const updateRes = await API.updateAvatar(user.id, avatarUrl); - if (updateRes.error) throw new Error(updateRes.error); - - currentUser.avatar_url = avatarUrl; - avatarPreview.src = avatarUrl; - statusEl.textContent = '✅ 头像更新成功!'; - statusEl.style.color = '#22c55e'; - renderNav(); - - } catch (err) { - statusEl.textContent = '❌ ' + err.message; - statusEl.style.color = '#ef4444'; - } - }); - } - - // ===== 保存设置(含签名) ===== - document.getElementById('settingsSaveBtn').addEventListener('click', async function() { - const username = document.getElementById('settingsUsername').value.trim(); - const bio = document.getElementById('settingsBio').value.trim(); - const signature = document.getElementById('settingsSignature').value.trim(); - if (!username) { alert('用户名不能为空'); return; } - try { - await API.updateProfile(user.id, username, bio, signature); - currentUser.username = username; - currentUser.bio = bio; - currentUser.signature = signature; - alert('保存成功!'); - renderNav(); - renderSettingsPage('profile'); - } catch (err) { - alert('保存失败:' + err.message); - } - }); - } - - else if (tab === 'security') { - container.innerHTML = ` -

🔒 安全设置

- -
-

修改密码

-
- - -
-
- - -
- -
- -
- -

修改邮箱

-
- - -
-
- - -
- -
-
- `; - - // ===== 修改密码 ===== - document.getElementById('changePasswordBtn').addEventListener('click', async function() { - const oldPassword = document.getElementById('changeOldPassword').value; - const newPassword = document.getElementById('changeNewPassword').value; - const statusEl = document.getElementById('passwordChangeStatus'); - - if (!oldPassword || !newPassword) { - statusEl.textContent = '请填写完整信息'; - statusEl.style.color = '#ef4444'; - return; - } - if (newPassword.length < 6) { - statusEl.textContent = '新密码至少6位'; - statusEl.style.color = '#ef4444'; - return; - } - - try { - await API.changePassword(oldPassword, newPassword); - document.getElementById('changeOldPassword').value = ''; - document.getElementById('changeNewPassword').value = ''; - statusEl.textContent = '✅ 密码修改成功!'; - statusEl.style.color = '#22c55e'; - } catch (err) { - statusEl.textContent = '❌ ' + err.message; - statusEl.style.color = '#ef4444'; - } - }); - - // ===== 修改邮箱 ===== - document.getElementById('changeEmailBtn').addEventListener('click', async function() { - const password = document.getElementById('changeEmailPassword').value; - const newEmail = document.getElementById('changeNewEmail').value; - const statusEl = document.getElementById('emailChangeStatus'); - - if (!password || !newEmail) { - statusEl.textContent = '请填写完整信息'; - statusEl.style.color = '#ef4444'; - return; - } - - try { - await API.changeEmail(password, newEmail); - document.getElementById('changeEmailPassword').value = ''; - document.getElementById('changeNewEmail').value = ''; - currentUser.email = newEmail; - statusEl.textContent = '✅ 邮箱修改成功!'; - statusEl.style.color = '#22c55e'; - } catch (err) { - statusEl.textContent = '❌ ' + err.message; - statusEl.style.color = '#ef4444'; - } - }); - } - - else if (tab === 'recovery') { - container.innerHTML = ` -

🔑 恢复码

- -
-

用于忘记密码时重置账户。每个恢复码只能使用一次。

-
- - -
-
剩余 ${recoveryCount} 个可用恢复码
-
- `; - - // ===== 恢复码管理 ===== - const viewBtn = document.getElementById('viewRecoveryCodesBtn'); - const regenBtn = document.getElementById('regenerateRecoveryCodesBtn'); - const recoveryStatus = document.getElementById('recoveryCodesStatus'); - - if (viewBtn) { - viewBtn.addEventListener('click', async function() { - try { - const data = await API.generateRecoveryCodes(); - showRecoveryCodesModal(data.codes); - const countData = await API.getRecoveryCodesCount(); - if (recoveryStatus) recoveryStatus.textContent = '剩余 ' + (countData.count || 0) + ' 个可用恢复码'; - } catch (err) { - alert('获取恢复码失败:' + err.message); - } - }); - } - - if (regenBtn) { - regenBtn.addEventListener('click', async function() { - if (!confirm('重新生成将替换所有旧的恢复码,确定继续吗?')) return; - try { - const data = await API.generateRecoveryCodes(); - showRecoveryCodesModal(data.codes); - const countData = await API.getRecoveryCodesCount(); - if (recoveryStatus) recoveryStatus.textContent = '剩余 ' + (countData.count || 0) + ' 个可用恢复码'; - } catch (err) { - alert('重新生成失败:' + err.message); - } - }); - } - } - - } catch (err) { - container.innerHTML = '
加载失败
'; - } -} - -// ============================================================ -// 设置页面侧边栏切换 -// ============================================================ - -document.querySelector('.settings-nav')?.addEventListener('click', function(e) { - const tabLink = e.target.closest('.settings-nav-item'); - if (!tabLink) return; - e.preventDefault(); - const tab = tabLink.dataset.settingsTab; - if (!tab) return; - renderSettingsPage(tab); -}); - -// ============================================================ -// ✏️ 编辑帖子模态框 -// ============================================================ - -function openEditModal(postId, currentTitle, currentContent) { - const modal = document.createElement('div'); - modal.className = 'modal active'; - modal.style.display = 'flex'; - modal.innerHTML = ` - - `; - - document.body.appendChild(modal); - - modal.querySelector('.close').addEventListener('click', function() { - modal.remove(); - }); - modal.addEventListener('click', function(e) { - if (e.target === this) modal.remove(); - }); - - modal.querySelector('#editPostSaveBtn').addEventListener('click', async function() { - const title = document.getElementById('editPostTitle').value.trim() || '无标题'; - const content = document.getElementById('editPostContent').value.trim(); - if (!content) { alert('请填写内容'); return; } - - try { - await API.updatePost(postId, title, content); - modal.remove(); - if (currentPage === 'post') { - renderPostDetail(currentPostId); - } else { - renderFeed(); - } - alert('编辑成功!'); - } catch (err) { - alert('编辑失败:' + err.message); - } - }); -} - -// ============================================================ -// 🔑 恢复码显示模态框 -// ============================================================ - -function showRecoveryCodesModal(codes) { - let modal = document.getElementById('recoveryCodesModal'); - if (!modal) { - modal = document.createElement('div'); - modal.id = 'recoveryCodesModal'; - modal.className = 'modal active'; - modal.style.display = 'flex'; - document.body.appendChild(modal); - } - - let codesHtml = ''; - codes.forEach((code, i) => { - codesHtml += ` -
- ${String(i + 1).padStart(2, '0')}. - ${code} -
- `; - }); - - modal.innerHTML = ` - - `; - - modal.style.display = 'flex'; - modal.classList.add('active'); - - document.getElementById('closeRecoveryCodesBtn').addEventListener('click', function() { - modal.remove(); - }); - - document.getElementById('copyRecoveryCodesBtn').addEventListener('click', function() { - const text = codes.join('\n'); - navigator.clipboard.writeText(text).then(() => { - document.getElementById('copyStatus').textContent = '✅ 已复制到剪贴板'; - }).catch(() => { - const textarea = document.createElement('textarea'); - textarea.value = text; - document.body.appendChild(textarea); - textarea.select(); - document.execCommand('copy'); - textarea.remove(); - document.getElementById('copyStatus').textContent = '✅ 已复制到剪贴板'; - }); - }); - - modal.addEventListener('click', function(e) { - if (e.target === this) modal.remove(); - }); -} - -// ============================================================ -// 🖼️ 图片查看器 -// ============================================================ - -function openImageViewer(imageUrl) { - const existing = document.getElementById('imageViewerModal'); - if (existing) existing.remove(); - - const modal = document.createElement('div'); - modal.id = 'imageViewerModal'; - modal.style.cssText = ` - position:fixed;inset:0;background:rgba(0,0,0,0.85);z-index:9999; - display:flex;align-items:center;justify-content:center; - cursor:pointer;animation:fadeIn 0.2s ease-out; - `; - - const img = document.createElement('img'); - img.src = imageUrl; - img.style.cssText = ` - max-width:90vw;max-height:90vh;object-fit:contain; - border-radius:8px;box-shadow:0 8px 32px rgba(0,0,0,0.5); - cursor:default;user-select:none; - `; - - modal.addEventListener('click', function(e) { - if (e.target === this) { - this.remove(); - } - }); - - modal.addEventListener('keydown', function(e) { - if (e.key === 'Escape') this.remove(); - }); - - modal.appendChild(img); - document.body.appendChild(modal); - modal.focus(); -} - -// 添加淡入动画 -(function() { - const style = document.createElement('style'); - style.textContent = ` - @keyframes fadeIn { - from { opacity: 0; transform: scale(0.95); } - to { opacity: 1; transform: scale(1); } - } - `; - document.head.appendChild(style); -})(); - -// ============================================================ -// 🚀 初始化 -// ============================================================ -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(); - await loadCustomPagesNav(); - renderStats(); - renderLinks(); - - const urlParams = new URLSearchParams(window.location.search); - const postParam = urlParams.get('post'); - const pageParam = urlParams.get('page'); - const userParam = urlParams.get('user'); - const postPageParam = urlParams.get('postpage'); - const customParam = urlParams.get('custom'); - - if (postPageParam) { - currentPageNum = parseInt(postPageParam) || 1; - } - - if (customParam) { - showCustomPage(customParam); - } else 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'); - } - - // ============================================================ - // 绑定所有事件 - // ============================================================ - - const themeToggle = document.getElementById('themeToggle'); - if (themeToggle) { - themeToggle.addEventListener('click', function(e) { - e.preventDefault(); - e.stopPropagation(); - toggleTheme(e); - document.getElementById('dropdownMenu').classList.remove('show'); - }); - } - - 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('forumName').addEventListener('click', function() { - switchPage('feed'); - }); - - // ===== 忘记密码 ===== - const forgotLink = document.getElementById('forgotPasswordLink'); - if (forgotLink) { - forgotLink.addEventListener('click', function(e) { - e.preventDefault(); - document.getElementById('forgotPasswordModal').classList.add('active'); - document.getElementById('resetStatus').textContent = ''; - }); - } - - document.getElementById('resetPasswordSubmit').addEventListener('click', async function() { - const email = document.getElementById('resetEmail').value.trim(); - const code = document.getElementById('resetRecoveryCode').value.trim().toUpperCase(); - const newPassword = document.getElementById('resetNewPassword').value; - const statusEl = document.getElementById('resetStatus'); - - if (!email || !code || !newPassword) { - statusEl.textContent = '请填写完整信息'; - statusEl.style.color = '#ef4444'; - return; - } - if (newPassword.length < 6) { - statusEl.textContent = '密码至少6位'; - statusEl.style.color = '#ef4444'; - return; - } - - try { - await API.resetPassword(email, code, newPassword); - statusEl.textContent = '✅ 重置成功!请登录'; - statusEl.style.color = '#22c55e'; - setTimeout(() => { - document.getElementById('forgotPasswordModal').classList.remove('active'); - document.getElementById('resetEmail').value = ''; - document.getElementById('resetRecoveryCode').value = ''; - document.getElementById('resetNewPassword').value = ''; - }, 1500); - } catch (err) { - statusEl.textContent = '❌ ' + err.message; - statusEl.style.color = '#ef4444'; - } - }); - - // ===== 发帖 ===== - 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('regCaptchaQuestion').addEventListener('click', function() { - refreshCaptcha('reg'); - }); - - // ===== 拖拽上传 ===== - const dropZone = document.getElementById('dropZone'); - const fileInput = document.getElementById('fileInput'); - const dropZoneText = document.getElementById('dropZoneText'); - - if (dropZone && fileInput) { - dropZone.addEventListener('click', function() { - fileInput.click(); - }); - - fileInput.addEventListener('change', function() { - handleImageFiles(this.files); - }); - - dropZone.addEventListener('dragover', function(e) { - e.preventDefault(); - this.style.borderColor = 'var(--primary)'; - this.style.background = 'var(--primary-bg)'; - if (dropZoneText) dropZoneText.textContent = '松开上传'; - }); - - dropZone.addEventListener('dragleave', function(e) { - e.preventDefault(); - this.style.borderColor = 'var(--border)'; - this.style.background = 'var(--bg)'; - if (dropZoneText) dropZoneText.textContent = '点击或拖拽上传图片'; - }); - - dropZone.addEventListener('drop', function(e) { - e.preventDefault(); - this.style.borderColor = 'var(--border)'; - this.style.background = 'var(--bg)'; - if (dropZoneText) dropZoneText.textContent = '点击或拖拽上传图片'; - handleImageFiles(e.dataTransfer.files); - }); - } - - // ===== 举报 ===== - 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; - const custom = state.custom || null; - if (postId) { - showPostPage(postId); - } else if (username) { - showUserPage(username); - } else if (custom) { - showCustomPage(custom); - } else { - switchPage(page); - } - }); - - // ===== 私信按钮 ===== - const messageBtn = document.getElementById('messageBtn'); - if (messageBtn) { - const newBtn = messageBtn.cloneNode(true); - messageBtn.parentNode.replaceChild(newBtn, messageBtn); - newBtn.addEventListener('click', function(e) { - e.stopPropagation(); - if (!currentUser) { alert('请先登录'); return; } - openMessageList(); - }); - } - - const closeMessageListBtn = document.querySelector('#messageListModal .close'); - if (closeMessageListBtn) { - closeMessageListBtn.addEventListener('click', closeMessageList); - } - - const closeChatBtn = document.querySelector('#chatModal .close'); - if (closeChatBtn) { - closeChatBtn.addEventListener('click', closeChat); - } - - const chatInput = document.getElementById('chatInput'); - if (chatInput) { - chatInput.addEventListener('keydown', function(e) { - if (e.key === 'Enter') { - e.preventDefault(); - sendMessage(); - } - }); - } - - document.querySelectorAll('.modal').forEach(m => { - m.addEventListener('click', function(e) { - if (e.target === this) { - this.classList.remove('active'); - if (this.id === 'messageListModal') { - closeMessageList(); - } - if (this.id === 'chatModal') { - closeChat(); - } - } - }); - }); -} - -document.addEventListener('DOMContentLoaded', init); diff --git a/js/auth.js b/js/auth.js deleted file mode 100644 index 9ba5245..0000000 --- a/js/auth.js +++ /dev/null @@ -1,111 +0,0 @@ -// ============================================================ -// AUTH 对象(供其他模块使用) -// ============================================================ - -const AUTH = { - async getUserProfile(userId) { - const data = await apiFetch('/users/' + userId); - if (data.error) throw new Error(data.error); - return data; - } -}; - -// ============================================================ -// 🔐 认证 -// ============================================================ - -// 登录事件绑定 -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 { - const result = 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('注册成功!请登录'); - - // 生成恢复码 - try { - const recoveryData = await API.generateRecoveryCodes(); - if (recoveryData.codes) { - showRecoveryCodesModal(recoveryData.codes); - } - } catch (e) { - console.warn('恢复码生成失败:', e); - } - - const loginResult = await API.login(email, password); - if (loginResult.user) { - const profile = await AUTH.getUserProfile(loginResult.user.id); - currentUser = { ...loginResult.user, ...profile }; - 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'); -}); diff --git a/js/captcha.js b/js/captcha.js deleted file mode 100644 index ad89972..0000000 --- a/js/captcha.js +++ /dev/null @@ -1,28 +0,0 @@ -// ============================================================ -// 🧠 验证码 -// ============================================================ - -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; - } -} diff --git a/js/feed.js b/js/feed.js deleted file mode 100644 index 662c169..0000000 --- a/js/feed.js +++ /dev/null @@ -1,231 +0,0 @@ -// ============================================================ -// 📋 帖子列表 -// ============================================================ - -let currentSort = 'latest'; -let totalPages = 1; -const PAGE_SIZE = 20; - -function renderFeed() { - const container = document.getElementById('postList'); - container.innerHTML = '
加载中...
'; - API.getPosts(currentSort, currentPageNum, PAGE_SIZE).then(result => { - const posts = result.data || []; - const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 }; - totalPages = pagination.totalPages || 1; - currentPageNum = pagination.page || 1; - - if (posts.length === 0 && currentPageNum === 1) { - container.innerHTML = - '
✨ 还没有帖子,快来发布第一条吧!
'; - return; - } - - if (posts.length === 0 && currentPageNum > 1) { - currentPageNum = 1; - renderFeed(); - 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; - - const renderedContent = marked ? marked.parse(p.content || '') : (p.content || '').replace(/\n/g, '
'); - - // 签名渲染 - let signatureHtml = ''; - if (p.signature) { - const sigContent = marked ? marked.parse(p.signature) : p.signature; - signatureHtml = ` -
- ${sigContent} -
- `; - } - - html += ` -
- ${p.is_pinned ? '
📌 置顶
' : ''} -
- - ${username} - ${time} - ${p.edited_at ? '(已编辑)' : ''} -
-
${p.title || '无标题'}
-
${renderedContent}
- ${imagesHtml} -
- - - ${replyCount} - - - ${currentUser && currentUser.id === p.user_id ? `` : ''} -
- ${signatureHtml} -
- `; - }); - container.innerHTML = html; - - // 分页控件 - if (totalPages > 1) { - let paginationHtml = ` -
- - `; - - let startPage = Math.max(1, currentPageNum - 4); - let endPage = Math.min(totalPages, currentPageNum + 4); - - if (currentPageNum <= 4) { - endPage = Math.min(totalPages, 9); - } - if (currentPageNum > totalPages - 4) { - startPage = Math.max(1, totalPages - 8); - } - - if (startPage > 1) { - paginationHtml += ``; - if (startPage > 2) { - paginationHtml += `…`; - } - } - - for (let i = startPage; i <= endPage; i++) { - const isActive = i === currentPageNum; - paginationHtml += ` - - `; - } - - if (endPage < totalPages) { - if (endPage < totalPages - 1) { - paginationHtml += `…`; - } - paginationHtml += ``; - } - - paginationHtml += ` - - - ${pagination.total} 帖 - -
- `; - container.innerHTML += paginationHtml; - - container.querySelectorAll('.page-btn:not([disabled])').forEach(btn => { - btn.addEventListener('click', function() { - const page = parseInt(this.dataset.page); - if (page >= 1 && page <= totalPages) { - currentPageNum = page; - const url = new URL(window.location); - url.searchParams.set('postpage', page); - window.history.pushState({}, '', url); - renderFeed(); - } - }); - }); - } - - 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; - // 在线人数已移除 - }).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; - currentPageNum = 1; - const url = new URL(window.location); - url.searchParams.delete('postpage'); - window.history.pushState({}, '', url); - renderFeed(); - }); -}); diff --git a/js/nothing b/js/nothing deleted file mode 100644 index 8b13789..0000000 --- a/js/nothing +++ /dev/null @@ -1 +0,0 @@ - diff --git a/js/post.js b/js/post.js deleted file mode 100644 index 87d5919..0000000 --- a/js/post.js +++ /dev/null @@ -1,237 +0,0 @@ -// ============================================================ -// 📄 帖子详情 + 回复 -// ============================================================ - -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 renderedContent = post.content || ''; - try { - if (typeof marked !== 'undefined' && marked.parse) { - renderedContent = marked.parse(renderedContent); - } else { - renderedContent = renderedContent.replace(/\n/g, '
    '); - } - } catch (e) { - renderedContent = renderedContent.replace(/\n/g, '
    '); - } - - // 签名渲染 - let signatureHtml = ''; - if (post.signature) { - const sigContent = marked ? marked.parse(post.signature) : post.signature; - signatureHtml = ` -
    - ${sigContent} -
    - `; - } - - let html = ` -
    -
    - - ${username} - ${time} - ${post.edited_at ? `(已编辑 ${new Date(post.edited_at).toLocaleString('zh-CN')})` : ''} - ${post.is_pinned ? '📌 置顶' : ''} -
    - ${currentUser && currentUser.role === 'admin' ? ` - - ` : ''} - ${currentUser && currentUser.id === post.user_id ? `` : ''} - ${currentUser && currentUser.id === post.user_id ? `` : ''} -
    -
    -
    ${renderedContent}
    - ${imagesHtml} - ${signatureHtml} -
    -
    - - ${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 += ` -
    -
    - - ${rUsername} - ${rTime} - ${currentUser && currentUser.id === r.user_id ? `` : ''} -
    -
    ${(r.content || '').replace(/\n/g, '
    ')}
    -
    - `; - }); - } - - html += '
    '; - container.innerHTML = html; - - replyArea.style.display = 'block'; - document.getElementById('replyContent').value = ''; - document.getElementById('replyCaptchaInput').value = ''; - refreshCaptcha('reply'); - - // 置顶按钮 - const pinBtn = document.getElementById('pinPostBtn'); - if (pinBtn) { - pinBtn.addEventListener('click', function() { - const postId = this.dataset.postid; - if (!confirm('确定要' + (this.textContent.includes('取消') ? '取消' : '') + '置顶吗?')) return; - API.togglePinPost(postId).then(() => { - renderPostDetail(postId); - renderFeed(); - }).catch(err => alert('操作失败:' + err.message)); - }); - } - - // 编辑按钮 - const editBtn = document.getElementById('editPostBtn'); - if (editBtn) { - editBtn.addEventListener('click', function() { - const postId = this.dataset.postid; - const currentTitle = post.title || ''; - const currentContent = post.content || ''; - openEditModal(postId, currentTitle, currentContent); - }); - } - - 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); - } -} diff --git a/js/theme.js b/js/theme.js deleted file mode 100644 index 48c9209..0000000 --- a/js/theme.js +++ /dev/null @@ -1,46 +0,0 @@ -// ============================================================ -// 🌓 主题切换 -// ============================================================ - -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); -} - -// 确保 DOM 加载完成后执行 -document.addEventListener('DOMContentLoaded', function() { - applyTheme(); -}); diff --git a/js/user.js b/js/user.js deleted file mode 100644 index 1e71011..0000000 --- a/js/user.js +++ /dev/null @@ -1,86 +0,0 @@ -// ============================================================ -// 👤 用户主页 -// ============================================================ - -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 result = await apiFetch('/posts?user_id=' + user.id + '&page=1&limit=100'); - const posts = result.data || []; - - 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' ? '🛡️ 管理员' : ''} -
    - ${currentUser && currentUser.id !== user.id ? ` - - ` : ''} -
    -

    📝 发布的帖子

    - `; - - 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; - - const dmBtn = document.getElementById('dmBtn'); - if (dmBtn) { - dmBtn.addEventListener('click', function() { - openPrivateChat(user.id, user.username); - }); - } - - } 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); -}