index.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. // 获取文档结构
  2. async function loadDocumentStructure() {
  3. const loading = document.getElementById('loading');
  4. const error = document.getElementById('error');
  5. const container = document.getElementById('categories-container');
  6. try {
  7. const response = await fetch('/api/structure');
  8. if (!response.ok) {
  9. const errorData = await response.json().catch(() => ({}));
  10. throw new Error(errorData.error || `加载失败 (${response.status})`);
  11. }
  12. const structure = await response.json();
  13. // 验证数据结构
  14. if (!Array.isArray(structure) || structure.length === 0) {
  15. throw new Error('文档结构为空或格式错误');
  16. }
  17. // 隐藏加载提示
  18. loading.style.display = 'none';
  19. // 渲染分类卡片
  20. renderCategories(structure);
  21. } catch (err) {
  22. console.error('Error loading structure:', err);
  23. loading.style.display = 'none';
  24. error.style.display = 'block';
  25. error.textContent = `加载失败:${err.message || '请稍后重试'}`;
  26. }
  27. }
  28. // 渲染分类卡片
  29. function renderCategories(structure) {
  30. const container = document.getElementById('categories-container');
  31. structure.forEach(category => {
  32. const card = document.createElement('div');
  33. card.className = 'category-card';
  34. const title = document.createElement('h2');
  35. title.className = 'category-title';
  36. title.textContent = category.name;
  37. const docCount = document.createElement('p');
  38. docCount.className = 'doc-count';
  39. docCount.textContent = `${category.docs.length} 篇文档`;
  40. const button = document.createElement('button');
  41. button.className = 'read-btn';
  42. button.textContent = '开始阅读';
  43. button.onclick = () => {
  44. // 跳转到阅读页,并传递分类名
  45. window.location.href = `/reader.html?category=${encodeURIComponent(category.name)}`;
  46. };
  47. card.appendChild(title);
  48. card.appendChild(docCount);
  49. card.appendChild(button);
  50. container.appendChild(card);
  51. });
  52. }
  53. // 登出功能
  54. function setupLogout() {
  55. const logoutBtn = document.getElementById('logout-btn');
  56. if (logoutBtn) {
  57. logoutBtn.addEventListener('click', async () => {
  58. if (!confirm('确定要登出吗?')) {
  59. return;
  60. }
  61. try {
  62. const response = await fetch('/api/logout', {
  63. method: 'POST',
  64. headers: {
  65. 'Content-Type': 'application/json'
  66. }
  67. });
  68. if (response.ok) {
  69. // 登出成功,跳转到登录页
  70. window.location.href = '/login.html';
  71. } else {
  72. alert('登出失败,请稍后重试');
  73. }
  74. } catch (error) {
  75. console.error('Logout error:', error);
  76. alert('登出失败,请稍后重试');
  77. }
  78. });
  79. }
  80. }
  81. // 页面加载时执行
  82. document.addEventListener('DOMContentLoaded', () => {
  83. loadDocumentStructure();
  84. setupLogout();
  85. });