This commit is contained in:
Furrium Network authored and GitHub committed 2026-08-11 08:48:53 +08:00
1 parent 6eb60df5ee
commit 12b3513f29
9 files changed
+3313

No files matched your search

+834
View File
@@ -0,0 +1,834 @@
// ============================================================
// 🛡️ 管理后台
// ============================================================
function renderAdminReports() {
const container = document.getElementById('adminContent');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
API.getReports().then(reports => {
if (!reports || reports.length === 0) {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">✅ 暂无举报</div>';
return;
}
let html = '';
const statusMap = { pending: '⏳ 待处理', approved: '✅ 已删除', rejected: '❌ 已驳回' };
reports.forEach(r => {
const postTitle = r.post_title || '无标题';
html += `
<div class="report-item">
<div><strong>${r.reporter_name || '匿名'}</strong> 举报了帖子</div>
<div style="font-size:13px;color:#64748b;margin:4px 0;">原因:${r.reason}</div>
<div style="font-size:13px;color:#64748b;margin:4px 0;">帖子:${postTitle} — ${(r.post_content || '').substring(0, 30)}${(r.post_content || '').length > 30 ? '...' : ''}</div>
<div style="font-size:13px;font-weight:600;">状态:${statusMap[r.status] || r.status}</div>
${r.handler_name ? `<div style="font-size:12px;color:#94a3b8;">处理人:${r.handler_name}${r.handler_note ? ' (' + r.handler_note + ')' : ''}</div>` : ''}
${r.status === 'pending' ? `
<div class="report-actions">
<button class="btn-sm btn-danger" data-reportid="${r.id}" data-action="approve">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
删除帖子
</button>
<button class="btn-sm btn-secondary" data-reportid="${r.id}" data-action="reject">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
驳回举报
</button>
</div>
` : ''}
</div>
`;
});
container.innerHTML = html;
container.querySelectorAll('[data-action]').forEach(btn => {
btn.addEventListener('click', function() {
const id = this.dataset.reportid;
const action = this.dataset.action;
const status = action === 'approve' ? 'approved' : 'rejected';
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return;
API.updateReport(id, status, note).then(() => {
if (action === 'approve') {
const report = reports.find(r => r.id === id);
if (report && report.post_id) {
API.deletePost(report.post_id).catch(() => {});
}
}
renderAdminReports();
}).catch(err => alert('操作失败:' + err.message));
});
});
}).catch(() => {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>';
});
}
// ============================================================
// 👥 用户列表(支持分页 + 搜索)
// ============================================================
let currentUsersPage = 1;
let usersTotalPages = 1;
let usersSearchKeyword = '';
function renderAdminUsers(page = 1, search = '') {
const container = document.getElementById('adminContent');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
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 = `
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;flex-wrap:wrap;gap:8px;">
<span style="font-size:13px;color:#94a3b8;">共 <strong>${pagination.total}</strong> 位用户</span>
<div style="display:flex;gap:6px;">
<input type="text" id="userSearchInput" placeholder="搜索用户名..." value="${search}"
style="padding:6px 12px;border:1px solid var(--border);border-radius:4px;font-size:13px;background:var(--bg);color:var(--text);" />
<button id="userSearchBtn" class="btn-sm btn-primary" style="padding:6px 14px;">搜索</button>
<button id="userClearSearchBtn" class="btn-sm btn-secondary" style="padding:6px 14px;">清空</button>
</div>
</div>
<div style="overflow-x:auto;">
<table style="width:100%;border-collapse:collapse;font-size:14px;">
<thead>
<tr style="text-align:left;border-bottom:2px solid #e2e8f0;">
<th style="padding:10px 12px;">用户</th>
<th style="padding:10px 12px;">角色</th>
<th style="padding:10px 12px;">注册时间</th>
<th style="padding:10px 12px;text-align:center;">操作</th>
</tr>
</thead>
<tbody>
`;
if (users.length === 0) {
html += `<tr><td colspan="4" style="text-align:center;padding:40px 0;color:#94a3b8;">暂无用户</td></tr>`;
} else {
users.forEach(u => {
const isAdmin = u.role === 'admin';
const isCurrentUser = currentUser && currentUser.id === u.id;
html += `
<tr style="border-bottom:1px solid #f1f5f9;${isCurrentUser ? 'background:var(--primary-bg);' : ''}">
<td style="padding:10px 12px;">
<div style="display:flex;align-items:center;gap:8px;">
<img src="${u.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64'}"
style="width:28px;height:28px;border-radius:50%;object-fit:cover;" />
<span style="font-weight:500;">${u.username}</span>
${isCurrentUser ? '<span style="font-size:11px;color:#94a3b8;background:#eef2ff;padding:1px 8px;border-radius:4px;">你</span>' : ''}
</div>
</td>
<td style="padding:10px 12px;">
<span style="display:inline-block;padding:2px 10px;border-radius:4px;font-size:12px;font-weight:500;${isAdmin ? 'background:#6366f1;color:#fff;' : 'background:#e2e8f0;color:#64748b;'}">
${isAdmin ? '管理员' : '普通用户'}
</span>
</td>
<td style="padding:10px 12px;color:#94a3b8;font-size:13px;">${u.created_at ? new Date(u.created_at).toLocaleDateString('zh-CN') : '—'}</td>
<td style="padding:10px 12px;text-align:center;">
${isCurrentUser ?
'<span style="font-size:12px;color:#94a3b8;">不可操作自己</span>' :
(isAdmin ?
`<button class="btn-sm btn-secondary" data-userid="${u.id}" data-role="user" style="padding:4px 12px;">设为普通用户</button>` :
`<button class="btn-sm btn-primary" data-userid="${u.id}" data-role="admin" style="padding:4px 12px;background:#6366f1;color:#fff;border:none;border-radius:4px;cursor:pointer;">设为管理员</button>`
)
}
</td>
</tr>
`;
});
}
html += '</tbody></table></div>';
// 分页控件
if (usersTotalPages > 1) {
html += `
<div style="display:flex;justify-content:center;align-items:center;gap:6px;padding:16px 0;margin-top:8px;border-top:1px solid var(--border);flex-wrap:wrap;">
<button class="users-page-btn" data-page="${page - 1}" ${page <= 1 ? 'disabled style="opacity:0.4;cursor:not-allowed;"' : ''}
style="padding:6px 12px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">
&laquo;
</button>
`;
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 += `<button class="users-page-btn" data-page="1" style="padding:6px 10px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">1</button>`;
if (startPage > 2) html += `<span style="color:var(--text-light);padding:0 4px;">…</span>`;
}
for (let i = startPage; i <= endPage; i++) {
const isActive = i === page;
html += `
<button class="users-page-btn" data-page="${i}" ${isActive ? 'disabled style="background:var(--primary);color:#fff;cursor:default;border-color:var(--primary);"' : ''}
style="padding:6px 10px;border:1px solid var(--border);border-radius:4px;background:${isActive ? 'var(--primary)' : 'var(--surface)'};color:${isActive ? '#fff' : 'var(--text)'};cursor:${isActive ? 'default' : 'pointer'};font-size:13px;min-width:32px;text-align:center;">
${i}
</button>
`;
}
if (endPage < usersTotalPages) {
if (endPage < usersTotalPages - 1) html += `<span style="color:var(--text-light);padding:0 4px;">…</span>`;
html += `<button class="users-page-btn" data-page="${usersTotalPages}" style="padding:6px 10px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">${usersTotalPages}</button>`;
}
html += `
<button class="users-page-btn" data-page="${page + 1}" ${page >= usersTotalPages ? 'disabled style="opacity:0.4;cursor:not-allowed;"' : ''}
style="padding:6px 12px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">
&raquo;
</button>
<span style="font-size:13px;color:var(--text-light);margin-left:8px;">
${pagination.total} 位用户
</span>
</div>
`;
}
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 = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载失败</div>';
});
}
// ============================================================
// 📜 操作日志(支持分页)
// ============================================================
function renderAdminLogs(page = 1) {
const container = document.getElementById('adminContent');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
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 = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">暂无日志</div>';
return;
}
let html = `
<table style="width:100%;border-collapse:collapse;font-size:13px;">
<thead>
<tr style="text-align:left;border-bottom:1px solid #e2e8f0;">
<th>时间</th>
<th>用户</th>
<th>操作</th>
</tr>
</thead>
<tbody>
`;
logs.forEach(l => {
html += `
<tr style="border-bottom:1px solid #f1f5f9;">
<td style="padding:6px 0;">${new Date(l.created_at).toLocaleString('zh-CN')}</td>
<td style="padding:6px 0;">${l.username || '系统'}</td>
<td style="padding:6px 0;">${l.action}</td>
</tr>
`;
});
html += '</tbody></table>';
// 分页控件
if (totalPages > 1) {
html += `
<div style="display:flex;justify-content:center;align-items:center;gap:6px;padding:16px 0;margin-top:8px;border-top:1px solid var(--border);flex-wrap:wrap;">
<button class="logs-page-btn" data-page="${page - 1}" ${page <= 1 ? 'disabled style="opacity:0.4;cursor:not-allowed;"' : ''}
style="padding:6px 12px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">
&laquo;
</button>
`;
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 += `<button class="logs-page-btn" data-page="1" style="padding:6px 10px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">1</button>`;
if (startPage > 2) html += `<span style="color:var(--text-light);padding:0 4px;">…</span>`;
}
for (let i = startPage; i <= endPage; i++) {
const isActive = i === page;
html += `
<button class="logs-page-btn" data-page="${i}" ${isActive ? 'disabled style="background:var(--primary);color:#fff;cursor:default;border-color:var(--primary);"' : ''}
style="padding:6px 10px;border:1px solid var(--border);border-radius:4px;background:${isActive ? 'var(--primary)' : 'var(--surface)'};color:${isActive ? '#fff' : 'var(--text)'};cursor:${isActive ? 'default' : 'pointer'};font-size:13px;min-width:32px;text-align:center;">
${i}
</button>
`;
}
if (endPage < totalPages) {
if (endPage < totalPages - 1) html += `<span style="color:var(--text-light);padding:0 4px;">…</span>`;
html += `<button class="logs-page-btn" data-page="${totalPages}" style="padding:6px 10px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">${totalPages}</button>`;
}
html += `
<button class="logs-page-btn" data-page="${page + 1}" ${page >= totalPages ? 'disabled style="opacity:0.4;cursor:not-allowed;"' : ''}
style="padding:6px 12px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">
&raquo;
</button>
<span style="font-size:13px;color:var(--text-light);margin-left:8px;">
${pagination.total} 条日志
</span>
</div>
`;
}
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 = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载失败</div>';
});
}
// ============================================================
// 🔗 友情链接管理
// ============================================================
function renderAdminLinks() {
const container = document.getElementById('adminContent');
container.innerHTML = `
<div style="margin-bottom:16px;display:flex;gap:8px;flex-wrap:wrap;">
<input type="text" id="newLinkTitle" placeholder="链接名称" style="flex:1;min-width:120px;padding:8px 12px;border:1px solid #e2e8f0;border-radius:4px;" />
<input type="url" id="newLinkUrl" placeholder="链接地址" style="flex:2;min-width:160px;padding:8px 12px;border:1px solid #e2e8f0;border-radius:4px;" />
<button id="addLinkBtn" class="btn-primary" style="padding:8px 16px;">添加</button>
</div>
<div id="linkList"></div>
`;
function loadLinks() {
API.getLinks().then(links => {
const ul = document.getElementById('linkList');
if (!links || links.length === 0) {
ul.innerHTML = '<div style="color:#94a3b8;font-size:13px;">暂无友情链接</div>';
return;
}
let html = '';
links.forEach(l => {
html += `
<div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f1f5f9;">
<span><a href="${l.url}" target="_blank" style="color:#6366f1;text-decoration:none;">${l.title}</a></span>
<button class="btn-sm btn-danger" data-linkid="${l.id}" style="background:rgba(239,68,68,0.08);border:1.5px solid #ef4444;color:#1a1a2e;padding:2px 10px;border-radius:6px;transition:all 0.2s;cursor:pointer;font-size:12px;font-weight:500;">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
删除
</button>
</div>
`;
});
ul.innerHTML = html;
ul.querySelectorAll('[data-linkid]').forEach(btn => {
btn.addEventListener('click', function() {
if (!confirm('确定删除该链接吗?')) return;
API.deleteLink(this.dataset.linkid).then(() => {
loadLinks();
}).catch(err => alert('删除失败:' + err.message));
});
});
}).catch(() => {});
}
loadLinks();
document.getElementById('addLinkBtn').addEventListener('click', function() {
const title = document.getElementById('newLinkTitle').value.trim();
const url = document.getElementById('newLinkUrl').value.trim();
if (!title || !url) { alert('请填写完整信息'); return; }
API.addLink(title, url).then(() => {
document.getElementById('newLinkTitle').value = '';
document.getElementById('newLinkUrl').value = '';
loadLinks();
}).catch(err => alert('添加失败:' + err.message));
});
}
// ============================================================
// ⚙️ 论坛设置(只改名称)
// ============================================================
function renderAdminSettings() {
const container = document.getElementById('adminContent');
container.innerHTML = `
<h3 style="margin-bottom:16px;text-align:center;">⚙️ 论坛名称</h3>
<div style="max-width:400px;margin:0 auto;width:100%;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:6px;">论坛名称</label>
<input type="text" id="settingsForumName" style="width:100%;padding:10px 14px;border:1.5px solid #e2e8f0;border-radius:6px;font-size:15px;margin-bottom:12px;font-family:inherit;background:var(--bg);color:var(--text);" />
<button id="settingsForumSave" class="btn-primary" style="padding:10px 24px;">保存</button>
<span id="settingsResult" style="margin-left:12px;font-size:14px;"></span>
</div>
`;
API.getSettings().then(data => {
document.getElementById('settingsForumName').value = data.forum_name || 'Forumlify';
}).catch(() => {});
document.getElementById('settingsForumSave').addEventListener('click', async () => {
const name = document.getElementById('settingsForumName').value.trim();
if (!name) { alert('请输入论坛名称'); return; }
try {
await API.updateSettings(name);
document.getElementById('settingsResult').textContent = '✅ 保存成功!';
document.getElementById('settingsResult').style.color = '#22c55e';
document.getElementById('forumName').textContent = name;
document.title = name;
const titleEl = document.getElementById('pageTitle');
if (titleEl) titleEl.textContent = name;
} catch (err) {
document.getElementById('settingsResult').textContent = '❌ 保存失败';
document.getElementById('settingsResult').style.color = '#ef4444';
}
});
}
// ============================================================
// 🎨 自定义 CSS(独立标签页)
// ============================================================
function renderAdminCustomCSS() {
const container = document.getElementById('adminContent');
container.innerHTML = `
<h3 style="margin-bottom:8px;text-align:center;">🎨 自定义 CSS</h3>
<p style="font-size:13px;color:var(--text-secondary);margin-bottom:12px;text-align:center;">上传 style.css 覆盖默认样式,自定义论坛外观。</p>
<div style="max-width:500px;margin:0 auto;">
<div id="customCssDropZone" style="border:2px dashed var(--border);border-radius:8px;padding:32px;text-align:center;cursor:pointer;transition:all 0.3s;background:var(--bg);">
<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block;margin:0 auto 8px;color:var(--text-secondary);"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
<p style="color:var(--text-secondary);font-size:14px;margin:0;">
<span id="customCssDropText">点击或拖拽上传 style.css</span>
</p>
<p style="color:var(--text-light);font-size:12px;margin:4px 0 0;">只能上传 style.css 文件</p>
<input type="file" id="customCssInput" accept=".css" style="display:none;" />
</div>
<div id="customCssStatus" style="font-size:13px;margin-top:8px;color:var(--text-light);"></div>
<div style="display:flex;gap:8px;margin-top:12px;flex-wrap:wrap;justify-content:center;">
<button id="customCssSaveBtn" class="btn-primary" style="padding:8px 20px;">💾 保存 CSS</button>
<button id="customCssDeleteBtn" class="btn-secondary" style="padding:8px 20px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">🗑️ 删除自定义 CSS</button>
</div>
</div>
`;
// 自定义 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 = `
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
<h3 style="margin:0;">📄 自定义页面</h3>
<button id="addCustomPageBtn" class="btn-primary" style="padding:8px 16px;">➕ 添加页面</button>
</div>
<div id="customPageList"></div>
`;
loadCustomPageList();
document.getElementById('addCustomPageBtn').addEventListener('click', function() {
editingPageId = null;
openCustomPageEditor();
});
}
function loadCustomPageList() {
const container = document.getElementById('customPageList');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
API.getAdminCustomPages().then(pages => {
if (pages.length === 0) {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">暂无自定义页面</div>';
return;
}
let html = `<div style="overflow-x:auto;">
<table style="width:100%;border-collapse:collapse;font-size:14px;">
<thead>
<tr style="text-align:left;border-bottom:2px solid var(--border);">
<th style="padding:8px 12px;">名称</th>
<th style="padding:8px 12px;">标题</th>
<th style="padding:8px 12px;">URL</th>
<th style="padding:8px 12px;">状态</th>
<th style="padding:8px 12px;text-align:center;">操作</th>
</tr>
</thead>
<tbody>
`;
pages.forEach(p => {
html += `
<tr style="border-bottom:1px solid var(--border-light);">
<td style="padding:8px 12px;"><code style="background:var(--bg);padding:2px 6px;border-radius:4px;font-size:12px;">${p.name}</code></td>
<td style="padding:8px 12px;">${p.title}</td>
<td style="padding:8px 12px;"><code style="background:var(--bg);padding:2px 6px;border-radius:4px;font-size:12px;">?custom=${p.name}</code></td>
<td style="padding:8px 12px;"><span style="color:${p.enabled ? '#22c55e' : '#ef4444'};">${p.enabled ? '✅ 启用' : '❌ 禁用'}</span></td>
<td style="padding:8px 12px;text-align:center;display:flex;gap:6px;justify-content:center;">
<button class="btn-sm btn-secondary" data-id="${p.id}" data-action="edit">✏️</button>
<button class="btn-sm btn-danger" data-id="${p.id}" data-action="delete">🗑️</button>
</td>
</tr>
`;
});
html += '</tbody></table></div>';
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 = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>';
});
}
function openCustomPageEditor(page) {
const isEdit = !!page;
const modal = document.createElement('div');
modal.className = 'modal active';
modal.style.display = 'flex';
modal.innerHTML = `
<div class="modal-content" style="max-width:600px;max-height:90vh;overflow-y:auto;">
<span class="close" style="position:absolute;top:12px;right:16px;font-size:24px;cursor:pointer;color:var(--text-light);">&times;</span>
<h2 style="margin-bottom:16px;">${isEdit ? '✏️ 编辑页面' : '📄 添加页面'}</h2>
<div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">页面名称</label>
<input type="text" id="editorPageName" value="${isEdit ? page.name : ''}" ${isEdit ? 'readonly style="background:var(--border-light);color:var(--text-light);"' : ''}
placeholder="about (用于 URL: ?custom=about)" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" />
${isEdit ? '<div style="font-size:12px;color:var(--text-light);margin-top:2px;">⚠️ 名称不可修改</div>' : '<div style="font-size:12px;color:var(--text-light);margin-top:2px;">只允许字母、数字、短横线和下划线</div>'}
</div>
<div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">导航栏显示名称</label>
<input type="text" id="editorPageTitle" value="${isEdit ? page.title : ''}"
placeholder="关于我们" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" />
</div>
<div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">状态</label>
<select id="editorEnabled" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);">
<option value="true" ${isEdit && page.enabled ? 'selected' : ''}>启用</option>
<option value="false" ${isEdit && !page.enabled ? 'selected' : ''}>禁用</option>
</select>
</div>
<div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">页面内容(HTML + CSS + JS)</label>
<textarea id="editorContent" rows="12" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:13px;font-family:monospace;background:var(--bg);color:var(--text);resize:vertical;">${isEdit ? page.content : ''}</textarea>
<div style="font-size:12px;color:var(--text-light);margin-top:2px;">支持 HTML、CSS(&lt;style&gt;)、JS(&lt;script&gt;),内容会在独立的沙盒中渲染</div>
</div>
<button id="editorSaveBtn" class="btn-primary" style="padding:10px 24px;width:100%;">保存</button>
</div>
`;
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 = `
<div class="modal-content" style="max-width:420px;">
<h2 style="margin-bottom:12px;">⚠️ 警告</h2>
<p style="font-size:14px;color:var(--text-secondary);margin-bottom:16px;">
若上传的 <strong>style.css</strong> 存在问题,将导致整个论坛界面样式错乱,甚至无法正常使用。
</p>
<p style="font-size:13px;color:var(--text-light);margin-bottom:20px;">
请确保 CSS 文件是完整的、经过测试的版本。如出现问题,可点击「删除自定义 CSS」恢复默认样式。
</p>
<div style="display:flex;gap:8px;">
<button id="cssWarningConfirm" class="btn-primary" style="padding:8px 24px;">我了解,继续上传</button>
<button id="cssWarningCancel" class="btn-secondary" style="padding:8px 24px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">取消</button>
</div>
</div>
`;
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);
});
+441
View File
@@ -0,0 +1,441 @@
// ============================================================
// 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;
}
};
+1299
View File
File diff suppressed because it is too large. Load diff
+111
View File
@@ -0,0 +1,111 @@
// ============================================================
// 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');
});
+28
View File
@@ -0,0 +1,28 @@
// ============================================================
// 🧠 验证码
// ============================================================
function generateCaptcha() {
let a = Math.floor(Math.random() * 9) + 1;
let b = Math.floor(Math.random() * 9) + 1;
let op = ['+', '-'][Math.floor(Math.random() * 2)];
if (op === '-' && a < b) { let t = a;
a = b;
b = t; }
let answer = op === '+' ? a + b : a - b;
return { question: a + ' ' + op + ' ' + b + ' = ?', answer: answer };
}
function refreshCaptcha(type) {
let q = generateCaptcha();
if (type === 'reg') {
document.getElementById('regCaptchaQuestion').textContent = q.question;
document.getElementById('regCaptchaInput').dataset.answer = q.answer;
} else if (type === 'post') {
document.getElementById('postCaptchaQuestion').textContent = q.question;
document.getElementById('postCaptchaInput').dataset.answer = q.answer;
} else if (type === 'reply') {
document.getElementById('replyCaptchaQuestion').textContent = q.question;
document.getElementById('replyCaptchaInput').dataset.answer = q.answer;
}
}
+231
View File
@@ -0,0 +1,231 @@
// ============================================================
// 📋 帖子列表
// ============================================================
let currentSort = 'latest';
let totalPages = 1;
const PAGE_SIZE = 20;
function renderFeed() {
const container = document.getElementById('postList');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
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 =
'<div style="text-align:center;color:#94a3b8;padding:60px 0;">✨ 还没有帖子,快来发布第一条吧!</div>';
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 = '<div class="post-images">';
p.images.forEach(img => {
imagesHtml += '<img src="' + img + '" class="post-image" onclick="openImageViewer(this.src)" style="cursor:pointer;" />';
});
imagesHtml += '</div>';
}
const replyCount = p.reply_count || 0;
const renderedContent = marked ? marked.parse(p.content || '') : (p.content || '').replace(/\n/g, '<br>');
// 签名渲染
let signatureHtml = '';
if (p.signature) {
const sigContent = marked ? marked.parse(p.signature) : p.signature;
signatureHtml = `
<div style="margin-top:10px;padding-top:8px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
${sigContent}
</div>
`;
}
html += `
<div class="post-card" data-postid="${p.id}" style="cursor:pointer;">
${p.is_pinned ? '<div style="font-size:12px;color:var(--primary);font-weight:600;margin-bottom:4px;">📌 置顶</div>' : ''}
<div class="post-header">
<img src="${avatar}" class="post-avatar" />
<span class="post-username" style="cursor:pointer;color:var(--primary);" onclick="event.stopPropagation();switchPage('user','${username}')">${username}</span>
<span class="post-time">${time}</span>
${p.edited_at ? '<span style="font-size:11px;color:var(--text-light);margin-left:6px;">(已编辑)</span>' : ''}
</div>
<div class="post-title">${p.title || '无标题'}</div>
<div class="post-content">${renderedContent}</div>
${imagesHtml}
<div class="post-actions">
<span>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
${replyCount}
</span>
<button class="action-report" data-postid="${p.id}">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
举报
</button>
${currentUser && currentUser.id === p.user_id ? `<button class="action-delete" data-postid="${p.id}">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
删除
</button>` : ''}
</div>
${signatureHtml}
</div>
`;
});
container.innerHTML = html;
// 分页控件
if (totalPages > 1) {
let paginationHtml = `
<div style="display:flex;justify-content:center;align-items:center;gap:6px;padding:16px 0;margin-top:8px;border-top:1px solid var(--border);flex-wrap:wrap;">
<button class="page-btn" data-page="${currentPageNum - 1}" ${currentPageNum <= 1 ? 'disabled style="opacity:0.4;cursor:not-allowed;"' : ''}
style="padding:6px 12px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">
&laquo;
</button>
`;
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 += `<button class="page-btn" data-page="1" style="padding:6px 10px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">1</button>`;
if (startPage > 2) {
paginationHtml += `<span style="color:var(--text-light);padding:0 4px;">…</span>`;
}
}
for (let i = startPage; i <= endPage; i++) {
const isActive = i === currentPageNum;
paginationHtml += `
<button class="page-btn" data-page="${i}" ${isActive ? 'disabled style="background:var(--primary);color:#fff;cursor:default;border-color:var(--primary);"' : ''}
style="padding:6px 10px;border:1px solid var(--border);border-radius:4px;background:${isActive ? 'var(--primary)' : 'var(--surface)'};color:${isActive ? '#fff' : 'var(--text)'};cursor:${isActive ? 'default' : 'pointer'};font-size:13px;min-width:32px;text-align:center;">
${i}
</button>
`;
}
if (endPage < totalPages) {
if (endPage < totalPages - 1) {
paginationHtml += `<span style="color:var(--text-light);padding:0 4px;">…</span>`;
}
paginationHtml += `<button class="page-btn" data-page="${totalPages}" style="padding:6px 10px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">${totalPages}</button>`;
}
paginationHtml += `
<button class="page-btn" data-page="${currentPageNum + 1}" ${currentPageNum >= totalPages ? 'disabled style="opacity:0.4;cursor:not-allowed;"' : ''}
style="padding:6px 12px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">
&raquo;
</button>
<span style="font-size:13px;color:var(--text-light);margin-left:8px;">
${pagination.total} 帖
</span>
</div>
`;
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 = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message +
'</div>';
});
}
function renderStats() {
API.getStats().then(stats => {
document.getElementById('statTopics').textContent = stats.topics || 0;
document.getElementById('statPosts').textContent = stats.posts || 0;
document.getElementById('statUsers').textContent = stats.users || 0;
// 在线人数已移除
}).catch(() => {});
}
function renderLinks() {
API.getLinks().then(links => {
const ul = document.getElementById('friendlyLinks');
if (!links || links.length === 0) {
ul.innerHTML = '<li style="color:#94a3b8;font-size:13px;">暂无链接</li>';
return;
}
let html = '';
links.forEach(l => {
html += '<li><a href="' + l.url + '" target="_blank">' + l.title + '</a></li>';
});
ul.innerHTML = html;
}).catch(() => {});
}
// 排序切换
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', function() {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
this.classList.add('active');
currentSort = this.dataset.sort;
currentPageNum = 1;
const url = new URL(window.location);
url.searchParams.delete('postpage');
window.history.pushState({}, '', url);
renderFeed();
});
});
+237
View File
@@ -0,0 +1,237 @@
// ============================================================
// 📄 帖子详情 + 回复
// ============================================================
let currentPostId = null;
let reportTargetPostId = null;
function switchToPost(postId) {
const url = new URL(window.location);
url.searchParams.set('post', postId);
url.searchParams.delete('page');
window.history.pushState({ page: 'post', postId: postId }, '', url);
showPostPage(postId);
}
function showPostPage(postId) {
document.getElementById('app').style.display = 'none';
document.querySelectorAll('.page-slide').forEach(el => {
el.classList.remove('active', 'slide-out');
});
const el = document.getElementById('pagePost');
el.classList.add('active');
el.style.animation = 'none';
void el.offsetHeight;
el.style.animation = '';
currentPage = 'post';
renderPostDetail(postId);
}
async function renderPostDetail(postId) {
const container = document.getElementById('postDetailContent');
const replyArea = document.getElementById('replyArea');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
replyArea.style.display = 'none';
try {
const post = await API.getPost(postId);
const replies = await API.getReplies(postId);
document.getElementById('postDetailTitle').textContent = post.title || '帖子详情';
const username = post.username || '匿名用户';
const avatar = post.avatar_url ||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) +
'&background=6366f1&color=fff&size=64';
const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : '';
let imagesHtml = '';
if (post.images && post.images.length > 0) {
imagesHtml = '<div class="post-images">';
post.images.forEach(img => {
imagesHtml += '<img src="' + img + '" class="post-image" onclick="openImageViewer(this.src)" style="cursor:pointer;" />';
});
imagesHtml += '</div>';
}
let renderedContent = post.content || '';
try {
if (typeof marked !== 'undefined' && marked.parse) {
renderedContent = marked.parse(renderedContent);
} else {
renderedContent = renderedContent.replace(/\n/g, '<br>');
}
} catch (e) {
renderedContent = renderedContent.replace(/\n/g, '<br>');
}
// 签名渲染
let signatureHtml = '';
if (post.signature) {
const sigContent = marked ? marked.parse(post.signature) : post.signature;
signatureHtml = `
<div style="margin-top:16px;padding-top:12px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
${sigContent}
</div>
`;
}
let html = `
<div class="post-detail-card">
<div class="post-header">
<img src="${avatar}" class="post-avatar" />
<span class="post-username" style="cursor:pointer;color:var(--primary);" onclick="switchPage('user','${username}')">${username}</span>
<span class="post-time">${time}</span>
${post.edited_at ? `<span style="font-size:12px;color:var(--text-light);margin-left:8px;">(已编辑 ${new Date(post.edited_at).toLocaleString('zh-CN')})</span>` : ''}
${post.is_pinned ? '<span style="font-size:12px;color:var(--primary);margin-left:8px;">📌 置顶</span>' : ''}
<div style="display:flex;gap:4px;margin-left:auto;">
${currentUser && currentUser.role === 'admin' ? `
<button class="btn-sm btn-secondary" id="pinPostBtn" data-postid="${post.id}" style="padding:4px 10px;">
${post.is_pinned ? '📌 取消置顶' : '📌 置顶'}
</button>
` : ''}
${currentUser && currentUser.id === post.user_id ? `<button class="btn-sm btn-secondary" id="editPostBtn" data-postid="${post.id}" style="padding:4px 10px;">✏️ 编辑</button>` : ''}
${currentUser && currentUser.id === post.user_id ? `<button class="btn-sm btn-danger" id="detailDeleteBtn" data-postid="${post.id}" style="padding:4px 10px;">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
删除
</button>` : ''}
</div>
</div>
<div class="post-content" style="font-size:16px;line-height:1.8;">${renderedContent}</div>
${imagesHtml}
${signatureHtml}
</div>
<div style="margin-top:20px;font-size:14px;color:#64748b;">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
${replies.length} 条回复
</div>
<div style="margin-top:12px;" id="repliesList">
`;
if (replies.length === 0) {
html += '<div style="color:#94a3b8;padding:20px 0;text-align:center;">还没有回复,快来抢沙发吧 🛋️</div>';
} else {
replies.forEach(r => {
const rUsername = r.username || '匿名用户';
const rAvatar = r.avatar_url ||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(rUsername) +
'&background=6366f1&color=fff&size=64';
const rTime = r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : '';
html += `
<div class="reply-item" data-replyid="${r.id}">
<div class="reply-header">
<img src="${rAvatar}" class="reply-avatar" />
<span class="reply-username" style="cursor:pointer;color:var(--primary);" onclick="switchPage('user','${rUsername}')">${rUsername}</span>
<span class="reply-time">${rTime}</span>
${currentUser && currentUser.id === r.user_id ? `<button class="btn-sm btn-danger reply-delete-btn" data-replyid="${r.id}">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
删除
</button>` : ''}
</div>
<div class="reply-content">${(r.content || '').replace(/\n/g, '<br>')}</div>
</div>
`;
});
}
html += '</div>';
container.innerHTML = html;
replyArea.style.display = 'block';
document.getElementById('replyContent').value = '';
document.getElementById('replyCaptchaInput').value = '';
refreshCaptcha('reply');
// 置顶按钮
const 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 = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message +
'</div>';
replyArea.style.display = 'none';
}
}
async function handleReplySubmit(postId) {
if (!currentUser) { alert('请先登录'); return; }
const content = document.getElementById('replyContent').value.trim();
const captchaInput = document.getElementById('replyCaptchaInput').value.trim();
const captchaAnswer = parseInt(document.getElementById('replyCaptchaInput').dataset.answer);
if (!content) { alert('请填写回复内容'); return; }
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reply'); return; }
try {
await API.createReply(postId, content);
API.logEvent('create_reply').catch(() => {});
renderPostDetail(postId);
if (currentPage === 'feed') {
renderFeed();
}
renderStats();
} catch (err) {
alert('回复失败:' + err.message);
}
}
+46
View File
@@ -0,0 +1,46 @@
// ============================================================
// 🌓 主题切换
// ============================================================
function getTheme() {
return localStorage.getItem('forumlify-theme') || 'light';
}
function setTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('forumlify-theme', theme);
updateThemeUI(theme);
}
function toggleTheme(e) {
if (e) { e.preventDefault();
e.stopPropagation(); }
const current = getTheme();
const next = current === 'light' ? 'dark' : 'light';
setTheme(next);
}
function updateThemeUI(theme) {
const icon = document.getElementById('themeIcon');
const label = document.getElementById('themeLabel');
if (!icon) return;
if (theme === 'dark') {
icon.innerHTML =
`<circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>`;
if (label) label.textContent = '☀️ 亮色模式';
} else {
icon.innerHTML = `<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>`;
if (label) label.textContent = '🌙 暗色模式';
}
}
function applyTheme() {
const theme = getTheme();
document.documentElement.setAttribute('data-theme', theme);
updateThemeUI(theme);
}
// 确保 DOM 加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
applyTheme();
});
+86
View File
@@ -0,0 +1,86 @@
// ============================================================
// 👤 用户主页
// ============================================================
async function renderUserProfile(username) {
const container = document.getElementById('userProfileContent');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
try {
const users = await apiFetch('/users?username=' + encodeURIComponent(username));
const user = users && users.length > 0 ? users[0] : null;
if (!user) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">用户不存在</div>';
return;
}
document.getElementById('userPageTitle').textContent = '👤 ' + user.username;
const 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 = `
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:32px;text-align:center;">
<img src="${avatar}" style="width:96px;height:96px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" />
<h2 style="margin:16px 0 4px;font-size:24px;">${user.username}</h2>
<p style="color:var(--text-secondary);font-size:14px;">${user.bio || '这个人很懒,什么都没写'}</p>
<div style="display:flex;justify-content:center;gap:32px;margin-top:16px;font-size:14px;color:var(--text-secondary);flex-wrap:wrap;">
<span>📅 加入于 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span>📝 发了 ${posts.length} 个帖子</span>
${user.role === 'admin' ? '<span style="color:var(--primary);font-weight:600;">🛡️ 管理员</span>' : ''}
</div>
${currentUser && currentUser.id !== user.id ? `
<button id="dmBtn" class="btn-primary" style="margin-top:16px;padding:8px 24px;">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;margin-right:6px;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
发私信
</button>
` : ''}
</div>
<h3 style="margin:24px 0 16px;font-size:18px;">📝 发布的帖子</h3>
`;
if (posts.length === 0) {
html += '<div style="color:#94a3b8;padding:20px 0;text-align:center;">还没有发帖</div>';
} else {
posts.forEach(p => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
html += `
<div class="post-card" style="cursor:pointer;" onclick="switchToPost('${p.id}')">
<div class="post-title" style="font-size:16px;font-weight:600;">${p.title || '无标题'}</div>
<div class="post-content" style="font-size:14px;color:var(--text-secondary);">${(p.content || '').substring(0, 100)}${(p.content || '').length > 100 ? '...' : ''}</div>
<div style="font-size:12px;color:var(--text-light);margin-top:8px;">${time}</div>
</div>
`;
});
}
container.innerHTML = html;
const dmBtn = document.getElementById('dmBtn');
if (dmBtn) {
dmBtn.addEventListener('click', function() {
openPrivateChat(user.id, user.username);
});
}
} catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message + '</div>';
}
}
function showUserPage(username) {
document.getElementById('app').style.display = 'none';
document.querySelectorAll('.page-slide').forEach(el => {
el.classList.remove('active', 'slide-out');
});
const el = document.getElementById('pageUser');
el.classList.add('active');
el.style.animation = 'none';
void el.offsetHeight;
el.style.animation = '';
currentPage = 'user';
renderUserProfile(username);
}