初始提交 - FutureOSS v1.0 插件化运行时框架

一切皆为插件的开发者工具运行时框架

🧩 核心特性:
  - 插件热插拔 (importlib 动态加载)
  - 依赖自动解析 (拓扑排序 + 循环检测)
  - 企业级稳定 (熔断/降级/重试/隔离)
  - 事件驱动 (发布/订阅事件总线)
  - 完整配置 (YAML 配置 + 热重载)
This commit is contained in:
Falck
2026-04-06 09:57:10 +08:00
commit 76147bae94
174 changed files with 15626 additions and 0 deletions

View File

@@ -0,0 +1,168 @@
/**
* OSS Community 认证页面 JS
* 处理登录/注册表单提交
*/
// 切换密码可见性
function togglePassword(fieldId = 'password') {
const input = document.getElementById(fieldId);
const icon = document.getElementById(`eyeIcon-${fieldId}`) || document.getElementById('eyeIcon');
if (input.type === 'password') {
input.type = 'text';
icon.innerHTML = `
<path stroke-linecap="round" stroke-linejoin="round" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"/>
`;
} else {
input.type = 'password';
icon.innerHTML = `
<path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
<path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
`;
}
}
// 显示错误消息
function showError(message) {
const errorEl = document.getElementById('errorMessage');
const successEl = document.getElementById('successMessage');
if (errorEl) {
errorEl.textContent = message;
errorEl.style.display = 'block';
}
if (successEl) {
successEl.style.display = 'none';
}
}
// 显示成功消息
function showSuccess(message) {
const successEl = document.getElementById('successMessage');
const errorEl = document.getElementById('errorMessage');
if (successEl) {
successEl.textContent = message;
successEl.style.display = 'block';
}
if (errorEl) {
errorEl.style.display = 'none';
}
}
// 隐藏消息
function hideMessages() {
const errorEl = document.getElementById('errorMessage');
const successEl = document.getElementById('successMessage');
if (errorEl) errorEl.style.display = 'none';
if (successEl) successEl.style.display = 'none';
}
// 设置按钮加载状态
function setButtonLoading(loading) {
const btn = document.getElementById('submitBtn');
const text = btn.querySelector('.btn-text');
const spinner = btn.querySelector('.btn-spinner');
if (loading) {
btn.disabled = true;
text.style.display = 'none';
spinner.style.display = 'block';
} else {
btn.disabled = false;
text.style.display = 'inline';
spinner.style.display = 'none';
}
}
// 登录表单
const loginForm = document.getElementById('loginForm');
if (loginForm) {
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
hideMessages();
setButtonLoading(true);
const formData = {
username: document.getElementById('username').value.trim(),
password: document.getElementById('password').value,
remember: document.getElementById('remember').checked
};
try {
const response = await fetch('api/auth.php?action=login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
});
const result = await response.json();
if (result.success) {
showSuccess('登录成功!正在跳转...');
setTimeout(() => {
window.location.href = 'index.php';
}, 1000);
} else {
showError(result.message || '登录失败,请检查用户名和密码');
}
} catch (error) {
showError('网络错误,请稍后重试');
} finally {
setButtonLoading(false);
}
});
}
// 注册表单
const registerForm = document.getElementById('registerForm');
if (registerForm) {
registerForm.addEventListener('submit', async (e) => {
e.preventDefault();
hideMessages();
setButtonLoading(true);
const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirmPassword').value;
// 前端验证
if (password !== confirmPassword) {
showError('两次输入的密码不一致');
setButtonLoading(false);
return;
}
if (password.length < 6) {
showError('密码长度至少 6 个字符');
setButtonLoading(false);
return;
}
const formData = {
username: document.getElementById('username').value.trim(),
email: document.getElementById('email').value.trim(),
password: password
};
try {
const response = await fetch('api/auth.php?action=register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
});
const result = await response.json();
if (result.success) {
showSuccess('注册成功!正在跳转到登录页...');
setTimeout(() => {
window.location.href = 'login.php';
}, 1500);
} else {
showError(result.message || '注册失败,请稍后重试');
}
} catch (error) {
showError('网络错误,请稍后重试');
} finally {
setButtonLoading(false);
}
});
}

View File

@@ -0,0 +1,255 @@
/**
* OSS Community Module
* Handles rendering of categories, stats, and posts list.
* Designed to be SPA-friendly (re-initializable).
*/
// Global state variables
let currentPage = 1;
let currentCategory = '';
let currentSort = 'latest';
// Expose initialization function globally for SPA Router
window.initCommunity = function() {
// Check if we are deep-linked (e.g. ?page=2)
const params = new URLSearchParams(window.location.search);
if(params.has('page')) currentPage = parseInt(params.get('page'));
// Fetch and Render Data
loadCategories();
loadStats();
loadPosts();
// Bind Events (to the new DOM elements created by SPA)
bindCommunityEvents();
};
function bindCommunityEvents() {
const catList = document.getElementById('categoryList');
if (catList) {
catList.addEventListener('click', e => {
const li = e.target.closest('li');
if (!li) return;
document.querySelectorAll('.category-list li').forEach(el => el.classList.remove('active'));
li.classList.add('active');
currentCategory = li.dataset.id || '';
currentPage = 1;
document.getElementById('currentCategory').textContent = li.querySelector('span:nth-child(2)').textContent + '帖子';
loadPosts();
});
}
const sortOptions = document.querySelector('.sort-options');
if (sortOptions) {
sortOptions.addEventListener('click', e => {
if (!e.target.classList.contains('sort-btn')) return;
document.querySelectorAll('.sort-btn').forEach(btn => btn.classList.remove('active'));
e.target.classList.add('active');
currentSort = e.target.dataset.sort;
currentPage = 1;
loadPosts();
});
}
}
// --- Data Loading Functions ---
const API = './api/index.php'; // Relative to community/ directory
async function loadCategories() {
try {
const res = await fetch(`${API}?action=categories`);
const data = await res.json();
const list = document.getElementById('categoryList');
if (!list) return;
// Keep the "All" item (first child) if it exists
const allItem = list.firstElementChild;
list.innerHTML = '';
if (allItem) list.appendChild(allItem);
data.categories.forEach(cat => {
const li = document.createElement('li');
li.dataset.id = cat.id;
li.innerHTML = `<span class="cat-icon">${getIconSvg(cat.icon)}</span><span>${cat.name}</span>`;
list.appendChild(li);
});
} catch (e) {
console.error('Failed to load categories', e);
}
}
async function loadStats() {
try {
const res = await fetch(`${API}?action=stats`);
const data = await res.json();
animateValue('statPosts', 0, data.posts, 1000);
animateValue('statReplies', 0, data.replies, 1000);
animateValue('statUsers', 0, data.users, 1000);
const countAll = document.getElementById('countAll');
if (countAll) countAll.textContent = data.posts;
} catch (e) {
console.error('Failed to load stats', e);
}
}
async function loadPosts() {
const list = document.getElementById('postsList');
if (!list) return;
list.innerHTML = '<div class="empty-state"><div class="loading-spinner"></div><p>正在连接节点...</p></div>';
try {
const params = new URLSearchParams({ action: 'posts', page: currentPage });
if (currentCategory) params.append('category_id', currentCategory);
const res = await fetch(`${API}?${params}`);
const data = await res.json();
list.innerHTML = '';
if (data.posts.length === 0) {
list.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">📭</div>
<h3>暂无帖子</h3>
<p>成为第一个发帖的人吧!</p>
</div>
`;
return;
}
data.posts.forEach((post, index) => {
const card = document.createElement('div');
card.className = 'post-card';
card.dataset.postId = post.id;
card.style.animationDelay = `${index * 0.1}s`;
card.innerHTML = `
<div class="post-header">
<div class="post-avatar">${post.username[0].toUpperCase()}</div>
<div class="post-meta">
<div class="post-author">${escapeHtml(post.username)}</div>
<div class="post-time">${timeAgo(post.created_at)}</div>
</div>
<div class="post-tags">
<span class="tag">${post.category_name}</span>
${post.is_pinned ? '<span class="pinned-badge"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="12" height="12"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg> 置顶</span>' : ''}
</div>
</div>
<div class="post-title">${escapeHtml(post.title)}</div>
<div class="post-excerpt">${escapeHtml(post.content.substring(0, 150))}...</div>
<div class="post-stats">
<span>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
${post.views}
</span>
<span>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>
${post.likes}
</span>
<span>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>
${post.reply_count || 0}
</span>
</div>
`;
list.appendChild(card);
});
renderPagination(data.pages);
} catch (e) {
list.innerHTML = '<div class="empty-state"><p>加载失败,请稍后重试</p></div>';
}
}
function renderPagination(pages) {
const container = document.getElementById('pagination');
if (!container) return;
container.innerHTML = '';
if (pages <= 1) return;
for (let i = 1; i <= pages; i++) {
const btn = document.createElement('button');
btn.className = `page-btn ${i === currentPage ? 'active' : ''}`;
btn.textContent = i;
btn.onclick = () => {
currentPage = i;
loadPosts();
window.scrollTo({ top: 0, behavior: 'smooth' });
};
container.appendChild(btn);
}
}
// --- Utilities ---
function animateValue(id, start, end, duration) {
const obj = document.getElementById(id);
if (!obj) return;
let startTimestamp = null;
const step = (timestamp) => {
if (!startTimestamp) startTimestamp = timestamp;
const progress = Math.min((timestamp - startTimestamp) / duration, 1);
obj.textContent = Math.floor(progress * (end - start) + start);
if (progress < 1) {
window.requestAnimationFrame(step);
}
};
window.requestAnimationFrame(step);
}
function timeAgo(dateStr) {
const now = new Date();
const date = new Date(dateStr);
const seconds = Math.floor((now - date) / 1000);
const intervals = [
[31536000, '年'], [2592000, '个月'], [604800, '周'],
[86400, '天'], [3600, '小时'], [60, '分钟']
];
for (const [secondsCount, label] of intervals) {
const count = Math.floor(seconds / secondsCount);
if (count >= 1) return `${count}${label}`;
}
return '刚刚';
}
function escapeHtml(str) {
if (!str) return '';
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
function getIconSvg(name) {
const icons = {
megaphone: '<svg viewBox="0 0 24 24"><path d="M3 11l18-5v12L3 13v-2zm11.5 1a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zM7 20v-2h10v2H7z"/></svg>',
question: '<svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"/></svg>',
chat: '<svg viewBox="0 0 24 24"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>',
puzzle: '<svg viewBox="0 0 24 24"><path d="M20.5 11H19V7c0-1.1-.9-2-2-2h-4V3.5C13 2.12 11.88 1 10.5 1S8 2.12 8 3.5V5H4c-1.1 0-2 .9-2 2v3.8h1.5c1.49 0 2.7 1.21 2.7 2.7s-1.21 2.7-2.7 2.7H2V20c0 1.1.9 2 2 2h3.8v-1.5c0-1.49 1.21-2.7 2.7-2.7s2.7 1.21 2.7 2.7V22H17c1.1 0 2-.9 2-2v-4h1.5c1.38 0 2.5-1.12 2.5-2.5S21.88 11 20.5 11z"/></svg>',
bug: '<svg viewBox="0 0 24 24"><path d="M14 12c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2zM7.56 14.05l1.66-1.66c.36.36.87.59 1.44.65.24.02.47.04.69.04.48 0 .94-.07 1.39-.2l1.32 1.32c-.65.18-1.33.28-2.03.32C10.18 14.64 8.72 14.33 7.56 14.05zM17.77 9.48l-1.32 1.32c-.45-.13-.91-.2-1.39-.2-.22 0-.45.02-.69.04-.57.06-1.08.29-1.44.65l-1.66-1.66c1.16-.28 2.62-.59 4.48-.47.69.04 1.37.14 2.02.32zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg>'
};
return icons[name] || icons['chat'];
}
// showCreateModal 函数已移至 post-modal.php 中定义
// 此处仅保留兼容性封装
window.showCreateModal = window.showCreateModal || function() {
if (typeof window.showCreatePostModal === 'function') {
window.showCreatePostModal();
} else {
console.warn('发帖模态框未加载');
}
};
// Auto-init if not loaded via SPA (Hard refresh case)
document.addEventListener('DOMContentLoaded', () => {
if (typeof AppRouter === 'undefined') {
window.initCommunity();
}
});

View File

@@ -0,0 +1,91 @@
document.addEventListener('DOMContentLoaded', () => {
const trigger = document.getElementById('dockUserMenuBtn');
const popover = document.getElementById('dockUserMenu');
const logoutBtn = document.getElementById('logoutBtn');
const deleteBtn = document.getElementById('deleteAccountBtn');
const myPostCount = document.getElementById('myPostCount');
// 获取用户文章数量
async function fetchMyPostCount() {
if (!myPostCount) return;
try {
const res = await fetch('api/auth.php?action=my-post-count');
if (res.ok) {
const data = await res.json();
if (data.success) {
myPostCount.textContent = data.count;
}
}
} catch (err) {
console.error('Failed to fetch post count:', err);
}
}
// 页面加载时获取文章数量
fetchMyPostCount();
if (trigger && popover) {
// 点击图标切换面板
trigger.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
const isActive = popover.classList.contains('active');
if (isActive) {
popover.classList.remove('active');
} else {
// 计算位置:在图标右侧
const rect = trigger.getBoundingClientRect();
// Dock 通常在左侧,我们定位在图标右边,稍微向上偏移一点居中
popover.style.left = `${rect.right + 16}px`;
popover.style.top = `${rect.top + 10}px`;
popover.classList.add('active');
}
});
// 点击外部关闭
document.addEventListener('click', (e) => {
if (!popover.contains(e.target) && !trigger.contains(e.target)) {
popover.classList.remove('active');
}
});
// 退出登录逻辑
if (logoutBtn) {
logoutBtn.addEventListener('click', async () => {
try {
const originalText = logoutBtn.innerHTML;
logoutBtn.innerHTML = '<span class="spinner"></span> 退出中...';
logoutBtn.disabled = true;
// 使用相对路径,因为 JS 可能在子目录中运行
// 注意:这里假设 api/auth.php 相对于当前页面路径可用
// 在 community/index.php 中api/ 是同级目录
const res = await fetch('api/auth.php?action=logout');
if (res.ok) {
// 退出成功,刷新页面
window.location.reload();
} else {
logoutBtn.innerHTML = originalText;
logoutBtn.disabled = false;
alert('退出失败,请重试');
}
} catch (err) {
console.error('Logout error:', err);
logoutBtn.innerHTML = '退出失败';
logoutBtn.disabled = false;
}
});
}
// 注销账户逻辑
if (deleteBtn) {
deleteBtn.addEventListener('click', () => {
if (confirm('确定要注销(永久删除)此账户吗?\n此操作不可撤销所有数据将被清除。')) {
alert('该功能暂未开放,请联系管理员。');
}
});
}
}
});

View File

@@ -0,0 +1,252 @@
/**
* OSS Community Editor JS
* Markdown 编辑器、实时预览、表单提交
*/
document.addEventListener('DOMContentLoaded', () => {
initEditor();
initToolbar();
initTags();
initForm();
});
// 初始化编辑器
function initEditor() {
const textarea = document.getElementById('postContent');
const titleInput = document.getElementById('postTitle');
// Tab 键支持
if (textarea) {
textarea.addEventListener('keydown', (e) => {
if (e.key === 'Tab') {
e.preventDefault();
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
textarea.value = textarea.value.substring(0, start) + ' ' + textarea.value.substring(end);
textarea.selectionStart = textarea.selectionEnd = start + 2;
}
});
}
}
// 初始化工具栏
function initToolbar() {
const buttons = document.querySelectorAll('.md-btn');
const textarea = document.getElementById('postContent');
if (!textarea) return;
buttons.forEach(btn => {
btn.addEventListener('click', () => {
const action = btn.dataset.md;
insertMarkdown(textarea, action);
});
});
}
function insertMarkdown(textarea, action) {
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const selected = textarea.value.substring(start, end);
let insertion = '';
switch (action) {
case 'bold':
insertion = `**${selected || '粗体文本'}**`;
break;
case 'italic':
insertion = `*${selected || '斜体文本'}*`;
break;
case 'heading':
insertion = `\n## ${selected || '标题'}\n`;
break;
case 'quote':
insertion = `\n> ${selected || '引用文本'}\n`;
break;
case 'code':
insertion = selected.includes('\n') ? `\n\`\`\`\n${selected || '代码块'}\n\`\`\`\n` : `\`${selected || '行内代码'}\``;
break;
case 'link':
insertion = `[${selected || '链接文本'}](url)`;
break;
case 'list':
insertion = `\n- ${selected || '列表项'}\n`;
break;
}
textarea.value = textarea.value.substring(0, start) + insertion + textarea.value.substring(end);
textarea.focus();
textarea.selectionStart = textarea.selectionEnd = start + insertion.length;
}
// 初始化标签
function initTags() {
const tagInput = document.getElementById('tagInput');
const tagsContainer = document.getElementById('tagsContainer');
if (!tagInput || !tagsContainer) return;
tagInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
const tagName = tagInput.value.trim();
if (tagName) {
addTag(tagName);
tagInput.value = '';
}
}
});
}
function addTag(name) {
const tagsContainer = document.getElementById('tagsContainer');
if (!tagsContainer) return;
// 检查是否已存在
const existing = tagsContainer.querySelectorAll('.tag-item');
for (const tag of existing) {
if (tag.textContent.trim().replace('×', '').trim() === name) {
return;
}
}
const tagEl = document.createElement('span');
tagEl.className = 'tag-item';
tagEl.innerHTML = `
${name}
<button type="button" class="tag-remove" onclick="this.parentElement.remove()">&times;</button>
`;
tagsContainer.appendChild(tagEl);
}
// 初始化表单
function initForm() {
const form = document.getElementById('postEditorForm');
const saveBtn = document.getElementById('savePostBtn');
if (!form || !saveBtn) return;
saveBtn.addEventListener('click', async (e) => {
e.preventDefault();
const postId = document.getElementById('editPostId').value;
const title = document.getElementById('postTitle').value.trim();
const content = document.getElementById('postContent').value.trim();
const categoryId = document.getElementById('postCategory').value;
// 收集标签
const tags = [];
document.querySelectorAll('#tagsContainer .tag-item').forEach(tag => {
const name = tag.textContent.replace('×', '').trim();
if (name) tags.push(name);
});
// 验证
if (!title) {
showError('请输入帖子标题');
return;
}
if (title.length < 5) {
showError('标题至少 5 个字符');
return;
}
if (!content) {
showError('请输入帖子内容');
return;
}
if (content.length < 10) {
showError('内容至少 10 个字符');
return;
}
if (!categoryId) {
showError('请选择分类');
return;
}
// 提交
setSaveButtonLoading(true);
const formData = {
title: title,
content: content,
category_id: categoryId,
tags: tags
};
if (postId) {
formData.id = parseInt(postId);
}
const action = postId ? 'update' : 'create';
const url = `api/posts.php?action=${action}`;
try {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
});
const result = await response.json();
if (result.success) {
showSuccess(postId ? '更新成功!' : '发布成功!正在跳转...');
setTimeout(() => {
window.location.href = `post.php?id=${result.post_id || postId}`;
}, 1000);
} else {
showError(result.message || '操作失败');
}
} catch (error) {
showError('网络错误,请稍后重试');
} finally {
setSaveButtonLoading(false);
}
});
}
function showSuccess(message) {
const toast = document.getElementById('successToast');
const msgEl = document.getElementById('successMessage');
if (toast && msgEl) {
msgEl.textContent = message;
toast.style.display = 'flex';
setTimeout(() => { toast.style.display = 'none'; }, 3000);
}
}
function showError(message) {
const toast = document.getElementById('errorToast');
const msgEl = document.getElementById('errorMessage');
if (toast && msgEl) {
msgEl.textContent = message;
toast.style.display = 'flex';
setTimeout(() => { toast.style.display = 'none'; }, 4000);
}
}
function setSaveButtonLoading(loading) {
const btn = document.getElementById('savePostBtn');
if (!btn) return;
if (loading) {
btn.disabled = true;
btn.style.opacity = '0.6';
btn.innerHTML = `
<svg class="btn-spinner" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" stroke-linecap="round" opacity="0.25"/>
<path d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" fill="currentColor" opacity="0.75"/>
</svg>
处理中...
`;
} else {
btn.disabled = false;
btn.style.opacity = '1';
btn.innerHTML = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>
</svg>
${document.getElementById('editPostId').value ? '保存修改' : '发布帖子'}
`;
}
}

View File

@@ -0,0 +1,91 @@
/**
* OSS Community - 实时轮询系统
* 每2秒从数据库刷新所有数据
*/
class CommunityPollingSystem {
constructor() {
this.interval = 2000;
this.timer = null;
this.isRunning = false;
this.listeners = { user: [], posts: [], stats: [], categories: [] };
this.cache = { user: null, posts: null, stats: null, categories: null };
}
start() {
if (this.isRunning) return;
this.isRunning = true;
this._fetchAll();
this.timer = setInterval(() => this._fetchAll(), this.interval);
}
stop() {
clearInterval(this.timer);
this.isRunning = false;
this.timer = null;
}
on(event, callback) {
if (this.listeners[event]) this.listeners[event].push(callback);
}
async _fetch(url) {
try {
const res = await fetch(url);
return res.ok ? await res.json() : null;
} catch { return null; }
}
async _fetchAll() {
// 并行请求所有接口
const [userData, postsData, statsData, catsData] = await Promise.all([
this._fetch('api/auth.php?action=current-user'),
this._fetch('api/index.php?action=posts'),
this._fetch('api/index.php?action=stats'),
this._fetch('api/index.php?action=categories')
]);
// 用户数据
if (userData && userData.success) {
const changed = JSON.stringify(userData) !== JSON.stringify(this.cache.user);
this.cache.user = userData;
if (changed) this._notify('user', userData);
}
// 帖子数据(含 views, likes, replies
if (postsData && postsData.posts) {
const changed = JSON.stringify(postsData.posts) !== JSON.stringify(this.cache.posts);
this.cache.posts = postsData.posts;
if (changed) this._notify('posts', postsData);
}
// 统计数据(含 hot_posts
if (statsData) {
const changed = JSON.stringify(statsData) !== JSON.stringify(this.cache.stats);
this.cache.stats = statsData;
if (changed) this._notify('stats', statsData);
}
// 分类
if (catsData && catsData.categories) {
const changed = JSON.stringify(catsData.categories) !== JSON.stringify(this.cache.categories);
this.cache.categories = catsData.categories;
if (changed) this._notify('categories', catsData);
}
}
_notify(event, data) {
(this.listeners[event] || []).forEach(fn => {
try { fn(data); } catch(e) {}
});
}
}
window.Polling = new CommunityPollingSystem();
document.addEventListener('DOMContentLoaded', () => {
const dock = document.getElementById('dock');
if (dock && dock.dataset.loggedIn === '1') {
window.Polling.start();
}
});

View File

@@ -0,0 +1,236 @@
/**
* OSS Community - 文章抽屉交互逻辑
*/
document.addEventListener('DOMContentLoaded', () => {
initPostDrawer();
});
let drawerInitialized = false;
let currentDrawerPostId = null;
let drawerPollTimer = null;
function initPostDrawer() {
if (drawerInitialized) return;
drawerInitialized = true;
createDrawerElements();
// 全局点击事件委托
document.addEventListener('click', (e) => {
const postCard = e.target.closest('.post-card');
if (postCard && postCard.dataset.postId) {
e.preventDefault();
e.stopPropagation();
openPostDrawer(postCard.dataset.postId);
}
});
const overlay = document.getElementById('postDrawerOverlay');
if (overlay) overlay.addEventListener('click', closePostDrawer);
const closeBtn = document.getElementById('postDrawerClose');
if (closeBtn) closeBtn.addEventListener('click', closePostDrawer);
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') closePostDrawer();
});
// 监听轮询数据更新抽屉内的 views/likes
if (window.Polling) {
window.Polling.on('posts', (data) => {
if (!data.posts || !currentDrawerPostId) return;
const post = data.posts.find(p => p.id == currentDrawerPostId);
if (post) updateDrawerStats(post);
});
}
}
function createDrawerElements() {
if (document.getElementById('postDrawerOverlay')) return;
// 创建遮罩层
const overlay = document.createElement('div');
overlay.id = 'postDrawerOverlay';
overlay.className = 'post-drawer-overlay';
// 创建抽屉
const drawer = document.createElement('div');
drawer.id = 'postDrawer';
drawer.className = 'post-drawer';
drawer.innerHTML = `
<div class="post-drawer-header">
<button class="post-drawer-close" id="postDrawerClose" aria-label="关闭">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="18" y1="6" x2="6" y2="18"/>
<line x1="6" y1="6" x2="18" y2="18"/>
</svg>
</button>
<h2 class="post-drawer-title" id="postDrawerTitle"></h2>
<div class="post-drawer-meta" id="postDrawerMeta"></div>
</div>
<div class="post-drawer-body">
<div class="post-drawer-content" id="postDrawerContent"></div>
</div>
<div class="post-drawer-footer" id="postDrawerFooter"></div>
`;
document.body.appendChild(overlay);
document.body.appendChild(drawer);
// 绑定关闭按钮
document.getElementById('postDrawerClose').addEventListener('click', closePostDrawer);
}
async function openPostDrawer(postId) {
const drawer = document.getElementById('postDrawer');
const overlay = document.getElementById('postDrawerOverlay');
const titleEl = document.getElementById('postDrawerTitle');
const metaEl = document.getElementById('postDrawerMeta');
const contentEl = document.getElementById('postDrawerContent');
const footerEl = document.getElementById('postDrawerFooter');
if (!drawer || !overlay) return;
// 显示加载状态
titleEl.textContent = '加载中...';
metaEl.innerHTML = '';
contentEl.innerHTML = '<div style="text-align:center;padding:40px;color:#64748b;">正在加载文章内容...</div>';
footerEl.innerHTML = '';
// 显示抽屉(先滑入,再加载内容)
overlay.classList.add('active');
drawer.classList.add('active');
document.body.style.overflow = 'hidden';
try {
const response = await fetch(`api/index.php?action=post&id=${postId}`);
if (!response.ok) throw new Error('加载失败');
const data = await response.json();
if (!data.post) throw new Error('帖子不存在');
const post = data.post;
const replies = data.replies || [];
currentDrawerPostId = post.id;
// 更新标题和元信息
titleEl.textContent = post.title;
metaEl.innerHTML = `
<div class="post-drawer-avatar">${post.username.charAt(0).toUpperCase()}</div>
<div class="post-drawer-user-info">
<div class="post-drawer-username">${escapeHtml(post.username)}</div>
<div class="post-drawer-date">${formatDate(post.created_at)}</div>
</div>
<span class="post-drawer-category">${escapeHtml(post.category_name)}</span>
`;
// 更新内容(使用 marked 解析 Markdown
if (typeof marked !== 'undefined') {
contentEl.innerHTML = marked.parse(post.content);
} else {
contentEl.innerHTML = escapeHtml(post.content).replace(/\n/g, '<br>');
}
// 更新底部统计
footerEl.innerHTML = `
<div class="post-drawer-stat">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
${post.views} 浏览
</div>
<div class="post-drawer-stat">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>
${post.likes} 点赞
</div>
<div class="post-drawer-stat">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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>
`;
// 如果有回复,在内容下方显示
if (replies.length > 0) {
contentEl.innerHTML += `
<hr style="margin:2em 0;border:none;height:1px;background:rgba(99,102,241,0.2);">
<h3 style="color:#e2e8f0;margin-bottom:1em;font-size:18px;">回复 (${replies.length})</h3>
${replies.map(reply => `
<div style="padding:16px;background:rgba(30,41,59,0.4);border-radius:12px;margin-bottom:12px;border:1px solid rgba(99,102,241,0.1);">
<div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
<div style="width:28px;height:28px;border-radius:6px;background:linear-gradient(135deg,#6366f1,#8b5cf6);display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:white;flex-shrink:0;">
${reply.username.charAt(0).toUpperCase()}
</div>
<span style="color:#e2e8f0;font-weight:600;font-size:13px;">${escapeHtml(reply.username)}</span>
<span style="color:#64748b;font-size:12px;margin-left:auto;">${formatDate(reply.created_at)}</span>
</div>
<div style="color:#cbd5e1;font-size:14px;line-height:1.6;">${escapeHtml(reply.content).replace(/\n/g, '<br>')}</div>
</div>
`).join('')}
`;
}
} catch (error) {
console.error('Failed to load post:', error);
contentEl.innerHTML = `
<div style="text-align:center;padding:40px;color:#ef4444;">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:48px;height:48px;margin:0 auto 16px;opacity:0.5;">
<circle cx="12" cy="12" r="10"/>
<line x1="12" y1="8" x2="12" y2="12"/>
<line x1="12" y1="16" x2="12.01" y2="16"/>
</svg>
<p style="font-size:16px;font-weight:600;margin-bottom:8px;">加载失败</p>
<p style="font-size:14px;">${error.message || '未知错误,请稍后重试'}</p>
</div>
`;
}
}
function closePostDrawer() {
const drawer = document.getElementById('postDrawer');
const overlay = document.getElementById('postDrawerOverlay');
if (drawer) drawer.classList.remove('active');
if (overlay) overlay.classList.remove('active');
document.body.style.overflow = '';
currentDrawerPostId = null;
}
function updateDrawerStats(post) {
const footerEl = document.getElementById('postDrawerFooter');
if (!footerEl || !currentDrawerPostId) return;
footerEl.innerHTML = `
<div class="post-drawer-stat">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
${post.views} 浏览
</div>
<div class="post-drawer-stat">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>
${post.likes} 点赞
</div>
<div class="post-drawer-stat">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>
${post.reply_count || 0} 回复
</div>
`;
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function formatDate(dateString) {
const date = new Date(dateString);
const now = new Date();
const diff = now - date;
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(diff / 3600000);
const days = Math.floor(diff / 86400000);
if (minutes < 1) return '刚刚';
if (minutes < 60) return `${minutes} 分钟前`;
if (hours < 24) return `${hours} 小时前`;
if (days < 7) return `${days} 天前`;
return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
}

View File

@@ -0,0 +1,108 @@
/**
* OSS Community - 轮询数据实时更新
*/
document.addEventListener('DOMContentLoaded', () => {
if (!window.Polling) return;
// ========== 用户数据(称号、权限) ==========
let prevTitle = '', prevPerms = {};
window.Polling.on('user', (data) => {
if (!data.success || !data.user) return;
const { title, role } = data.user;
// 更新称号徽章
if (title !== prevTitle) {
prevTitle = title;
const avatar = document.getElementById('dockUserAvatar');
if (avatar) {
const name = avatar.dataset.tooltip.split(' - ')[0] || avatar.dataset.tooltip;
avatar.dataset.tooltip = title ? `${name} - ${title}` : name;
}
let badge = document.querySelector('.user-title-badge');
if (title) {
if (!badge) { badge = document.createElement('span'); badge.className = 'user-title-badge'; if (avatar) avatar.appendChild(badge); }
badge.textContent = title;
} else if (badge) badge.remove();
}
// 权限控制
if (data.permissions && JSON.stringify(data.permissions) !== JSON.stringify(prevPerms)) {
prevPerms = data.permissions;
document.querySelectorAll('.admin-only').forEach(el => el.style.display = prevPerms.can_manage_users ? '' : 'none');
document.querySelectorAll('.moderator-only').forEach(el => el.style.display = prevPerms.can_manage_posts ? '' : 'none');
}
});
// ========== 帖子数据实时更新 views/likes/replies ==========
window.Polling.on('posts', (data) => {
if (!data.posts || !Array.isArray(data.posts)) return;
data.posts.forEach(post => {
// 更新帖子卡片上的浏览、点赞、回复数
const cards = document.querySelectorAll(`.post-card[data-post-id="${post.id}"]`);
cards.forEach(card => {
const statsEls = card.querySelectorAll('.post-stats span');
if (statsEls.length >= 3) {
// views
const viewsSvg = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>';
// likes
const likesSvg = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>';
// replies
const repliesSvg = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>';
statsEls[0].innerHTML = viewsSvg + ` ${post.views}`;
statsEls[1].innerHTML = likesSvg + ` ${post.likes}`;
statsEls[2].innerHTML = repliesSvg + ` ${post.reply_count || 0}`;
}
});
// 更新个人主页帖子列表的 stats
const myListItems = document.querySelectorAll(`.my-post-item[data-post-id="${post.id}"] .my-post-meta`);
myListItems.forEach(meta => {
const spans = meta.querySelectorAll('span');
if (spans.length >= 4) {
spans[1].textContent = `👁️ ${post.views} 浏览`;
spans[2].textContent = `❤️ ${post.likes} 点赞`;
spans[3].textContent = `💬 ${post.reply_count || 0} 回复`;
}
});
});
});
// ========== 统计数字实时更新 ==========
window.Polling.on('stats', (data) => {
if (data.posts !== undefined) animateNumber('statPosts', data.posts);
if (data.replies !== undefined) animateNumber('statReplies', data.replies);
if (data.users !== undefined) animateNumber('statUsers', data.users);
const countAll = document.getElementById('countAll');
if (countAll) countAll.textContent = data.posts || 0;
// 更新热门帖子 views如果有这个区域
if (data.hot_posts && Array.isArray(data.hot_posts)) {
data.hot_posts.forEach(hp => {
const hotItems = document.querySelectorAll(`.hot-post-item[data-post-id="${hp.id}"]`);
hotItems.forEach(item => {
const viewsEl = item.querySelector('.hot-views');
if (viewsEl) viewsEl.textContent = hp.views;
});
});
}
});
// ========== 分类更新 ==========
window.Polling.on('categories', (data) => {
if (!data.categories) return;
const countAll = document.getElementById('countAll');
if (countAll) countAll.textContent = data.posts || data.categories.length;
});
});
// 数字动画
function animateNumber(id, target) {
const el = document.getElementById(id);
if (!el) return;
const current = parseInt(el.textContent) || 0;
if (current === target) return;
el.textContent = target;
}