/** * Pages模块 - 页面渲染逻辑 */ const Pages = (function() { // ========== 工具方法 ========== // 格式化时间 function formatTime(timestamp) { if (!timestamp) return ''; const date = new Date(timestamp); const now = new Date(); const diff = now - date; if (diff < 60000) return '刚刚'; if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'; if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'; if (diff < 604800000) return Math.floor(diff / 86400000) + '天前'; return date.toLocaleDateString('zh-CN'); } // 处理封面图片错误 function handleCoverError(img) { img.onerror = null; img.src = 'data:image/svg+xml,' + encodeURIComponent(` 暂无封面 `); } // 清理HTML内容中的换行标签 function cleanContent(content) { if (!content) return ''; return content .replace(//gi, '\n') .replace(/ /g, ' ') .replace(/<[^>]+>/g, '') .trim(); } // ========== 书架页面 ========== async function renderShelf() { const $content = $('#app-content'); $content.html(`

我的书架

${renderSkeletonGrid(6)}
`); try { const userId = Store.getUserId(); const data = await API.getShelf({ userId, page: 0, size: 50 }); const items = data.content || []; if (items.length === 0) { $('#shelf-grid').html(`

书架空空如也

去发现页面找本好书吧

`); return; } // 获取每本书的详情 const novels = await Promise.all( items.map(item => API.getNovelDetail(item.novelId).catch(() => null)) ); // 更新书架缓存 Store.setShelfCache(items.map(i => i.novelId)); let html = ''; novels.forEach((novel, index) => { if (!novel) return; const position = Store.getReadingPosition(novel.id); html += renderShelfItem(novel, position); }); $('#shelf-grid').html(html); // 绑定图片错误处理 $('#shelf-grid img').on('error', function() { handleCoverError(this); }); } catch (error) { console.error('加载书架失败:', error); Toast.show('加载失败,请重试'); } } function renderShelfItem(novel, position) { const progress = position ? Math.min(100, Math.round((position.chapterIndex / (novel.lastChapterIndex || 1)) * 100)) : 0; return `
${novel.name}
${novel.name}
${novel.author}
${progress > 0 ? `
` : ''}
`; } // ========== 发现页面 ========== async function renderExplore() { const $content = $('#app-content'); $content.html(`

发现好书

探索精彩小说世界

🎲 随机推荐

${renderSkeletonScroll(5)}

热门标签

全部小说

${renderSkeletonList(5)}
`); // 加载随机推荐 loadRandomNovels(); // 加载标签 loadTags(); // 加载小说列表 loadNovels(0); // 绑定刷新随机推荐按钮 $('#refresh-random').on('click', function() { loadRandomNovels(); }); } // 加载随机推荐 async function loadRandomNovels() { $('#random-novels').html(renderSkeletonScroll(6)); try { const novels = await API.getRandomNovels(12); if (novels.length === 0) { $('#random-novels').html('

暂无推荐

'); return; } let html = ''; novels.forEach(novel => { const isInShelf = Store.isInShelfCache(novel.id); html += `
${novel.name} ${isInShelf ? '
' : ''}
${novel.name}
${novel.author || '未知'}
`; }); $('#random-novels').html(html); // 绑定图片错误处理 $('#random-novels img').on('error', function() { handleCoverError(this); }); } catch (error) { console.error('加载随机推荐失败:', error); $('#random-novels').html('

加载失败

'); } } // 渲染横向滚动骨架屏 function renderSkeletonScroll(count) { let html = ''; for (let i = 0; i < count; i++) { html += `
`; } return html; } let currentPage = 0; let isLoadingMore = false; let hasMore = true; let currentTag = null; // 保存当前选择的标签 async function loadTags() { try { const tags = await API.getPopularTags(15); let html = ''; tags.forEach(tag => { html += ``; }); $('#tags-cloud').html(html); } catch (error) { console.error('加载标签失败:', error); } } let currentAuthor = null; // 保存当前选择的作者 async function loadNovels(page, tag = null, author = null, append = false) { if (isLoadingMore) return; isLoadingMore = true; // 如果不是追加加载,保存当前筛选条件 if (!append) { currentPage = 0; hasMore = true; currentTag = tag; // 保存当前选择的标签 currentAuthor = author; // 保存当前选择的作者 $('#novel-list').html(renderSkeletonList(5)); } // 追加加载时使用已保存的筛选条件 const useTag = append ? currentTag : tag; const useAuthor = append ? currentAuthor : author; try { const params = { page, size: 20 }; if (useTag) params.tag = useTag; if (useAuthor) params.keyword = useAuthor; // 使用keyword参数搜索作者 const data = await API.searchNovels(params); const novels = data.content || []; hasMore = !data.last; // 如果有作者筛选,只保留该作者的作品 let filteredNovels = novels; if (useAuthor) { filteredNovels = novels.filter(novel => novel.author === useAuthor); } let html = ''; filteredNovels.forEach(novel => { const isInShelf = Store.isInShelfCache(novel.id); html += renderNovelCard(novel, isInShelf); }); if (append) { $('#novel-list').append(html); } else { // 显示筛选信息 let filterInfo = ''; if (useAuthor) { filterInfo = `
作者:${useAuthor}
`; } else if (useTag) { filterInfo = `
标签:${useTag}
`; } const listHtml = html || '

暂无小说

'; $('#novel-list').html(filterInfo ? (filterInfo + listHtml) : listHtml); } // 更新加载更多按钮 if (hasMore && filteredNovels.length > 0) { $('#load-more').html(''); } else { $('#load-more').html('没有更多了'); } currentPage = page; // 绑定图片错误处理 $('#novel-list img').on('error', function() { handleCoverError(this); }); // 重新绑定清除筛选按钮事件(只在非追加模式下绑定,避免重复绑定) if (!append) { $(document).off('click', '.clear-filter-btn').on('click', '.clear-filter-btn', function(e) { e.preventDefault(); e.stopPropagation(); const filterType = $(this).data('type'); if (filterType === 'author') { currentAuthor = null; loadNovels(0, currentTag, null); } else if (filterType === 'tag') { currentTag = null; $('.tag-btn').removeClass('active'); loadNovels(0, null, currentAuthor); } }); } } catch (error) { console.error('加载小说失败:', error); Toast.show('加载失败,请重试'); } finally { isLoadingMore = false; } } function renderNovelCard(novel, inShelf = false) { const synopsis = cleanContent(novel.synopsis).substring(0, 80); const tags = (novel.tags || []).slice(0, 2); // 检查书架状态(如果没有传入,则从缓存中检查) const isInShelf = inShelf !== undefined ? inShelf : Store.isInShelfCache(novel.id); return `
${novel.name} ${isInShelf ? '
已收藏
' : ''}
${novel.name}
${novel.author || '未知'}
${synopsis}...
${tags.map(t => `${t}`).join('')}
`; } // ========== 历史页面 ========== async function renderHistory() { const $content = $('#app-content'); $content.html(`

阅读历史

${renderSkeletonList(5)}
`); try { const userId = Store.getUserId(); const data = await API.getHistory({ userId, page: 0, size: 50 }); const items = data.content || []; if (items.length === 0) { $('#history-list').html(`

暂无阅读记录

开始阅读后会在这里显示

`); return; } // 获取小说详情和章节信息 const historyWithDetails = await Promise.all( items.map(async (item) => { try { const [novel, chapter] = await Promise.all([ API.getNovelDetail(item.novelId), API.getChapterById(item.chapterId) ]); return { ...item, novel, chapter }; } catch { return null; } }) ); let html = ''; historyWithDetails.filter(Boolean).forEach(item => { html += renderHistoryItem(item); }); $('#history-list').html(html || '

暂无记录

'); // 绑定图片错误处理 $('#history-list img').on('error', function() { handleCoverError(this); }); } catch (error) { console.error('加载历史失败:', error); Toast.show('加载失败,请重试'); } } function renderHistoryItem(item) { return `
${item.novel?.name || ''}
${item.novel?.name || '未知'}
${item.chapter?.title || '未知章节'}
${formatTime(item.lastReadAt)}
`; } // ========== 书签页面 ========== async function renderBookmarks() { const $content = $('#app-content'); $content.html(`

我的书签

${renderSkeletonList(5)}
`); try { const userId = Store.getUserId(); const data = await API.getBookmarks({ userId, page: 0, size: 50 }); const items = data.content || []; if (items.length === 0) { $('#bookmarks-list').html(`

暂无书签

阅读时点击书签按钮添加

`); return; } // 获取小说和章节详情 const bookmarksWithDetails = await Promise.all( items.map(async (item) => { try { const [novel, chapter] = await Promise.all([ API.getNovelDetail(item.novelId), API.getChapterById(item.chapterId) ]); return { ...item, novel, chapter }; } catch { return null; } }) ); let html = ''; bookmarksWithDetails.filter(Boolean).forEach(item => { html += renderBookmarkItem(item); }); $('#bookmarks-list').html(html || '

暂无书签

'); // 绑定图片错误处理 $('#bookmarks-list img').on('error', function() { handleCoverError(this); }); } catch (error) { console.error('加载书签失败:', error); Toast.show('加载失败,请重试'); } } function renderBookmarkItem(item) { return `
${item.novel?.name || ''}
${item.novel?.name || '未知'}
${item.chapter?.title || '未知章节'}
${item.note ? `
${item.note}
` : ''}
${formatTime(item.createdAt)}
`; } // ========== 小说详情页面 ========== async function renderDetail(novelId) { const $content = $('#app-content'); $content.html(`
`); try { const novel = await API.getNovelDetail(novelId); Store.setState('currentNovel', novel); // 检查是否在书架 const inShelf = Store.isInShelfCache(novelId); // 获取阅读位置 const position = Store.getReadingPosition(novelId); $content.html(renderDetailPage(novel, inShelf, position)); // 加载前几章节 loadPreviewChapters(novelId); // 绑定图片错误处理 $('.detail-cover img').on('error', function() { handleCoverError(this); }); } catch (error) { console.error('加载详情失败:', error); Toast.show('加载失败,请重试'); } } function renderDetailPage(novel, inShelf, position) { const synopsis = cleanContent(novel.synopsis); const tags = novel.tags || []; return `
${novel.name}

${novel.name}

${novel.author || '未知'}
${novel.chapterCount || 0}
章节
${novel.status === 1 ? '完结' : '连载'}
状态
${tags.map(t => `${t}`).join('')}

简介

${synopsis}

目录 共${novel.chapterCount || 0}章

加载中...
`; } async function loadPreviewChapters(novelId) { try { const data = await API.getChapters(novelId, { page: 0, size: 5 }); const chapters = data.content || []; let html = ''; chapters.forEach(chapter => { html += `
${chapter.index + 1} ${chapter.title}
`; }); $('#chapters-preview').html(html || '

暂无章节

'); } catch (error) { console.error('加载章节失败:', error); } } // ========== 搜索功能 ========== async function renderSearchResults(keyword) { const $results = $('#search-results'); $results.html('
搜索中...
'); // 保存当前搜索关键词用于高亮 currentSearchKeyword = keyword; try { const data = await API.searchNovels({ keyword, page: 0, size: 30 }); const novels = data.content || []; if (novels.length === 0) { $results.html('
未找到相关小说
'); return; } let html = '
'; novels.forEach(novel => { const isInShelf = Store.isInShelfCache(novel.id); html += renderNovelCard(novel, isInShelf, keyword); }); html += '
'; $results.html(html); // 绑定图片错误处理 $results.find('img').on('error', function() { handleCoverError(this); }); } catch (error) { console.error('搜索失败:', error); $results.html('
搜索失败,请重试
'); } } async function renderSearchByTag(tag) { const $results = $('#search-results'); $results.html('
加载中...
'); try { const data = await API.searchNovels({ tag, page: 0, size: 30 }); const novels = data.content || []; if (novels.length === 0) { $results.html('
该标签下暂无小说
'); return; } let html = '
'; novels.forEach(novel => { const isInShelf = Store.isInShelfCache(novel.id); html += renderNovelCard(novel, isInShelf); }); html += '
'; $results.html(html); // 绑定图片错误处理 $results.find('img').on('error', function() { handleCoverError(this); }); } catch (error) { console.error('加载失败:', error); $results.html('
加载失败,请重试
'); } } // ========== 骨架屏 ========== function renderSkeletonGrid(count) { let html = ''; for (let i = 0; i < count; i++) { html += `
`; } return html; } function renderSkeletonList(count) { let html = ''; for (let i = 0; i < count; i++) { html += `
`; } return html; } // 按作者搜索(公开函数) function searchByAuthor(author) { if (!author) return; // 切换到发现页面 if (window.location.hash !== '#/explore') { window.location.hash = '#/explore'; // 等待页面渲染完成后加载该作者的作品 setTimeout(() => { loadNovels(0, null, author); }, 300); } else { // 如果已经在发现页面,直接加载 loadNovels(0, null, author); } } // 公开API return { renderShelf, renderExplore, renderHistory, renderBookmarks, renderDetail, renderSearchResults, renderSearchByTag, loadNovels, searchByAuthor, currentPage: () => currentPage, hasMore: () => hasMore }; })();