update code level

This commit is contained in:
lychang
2026-03-25 14:06:49 +08:00
parent 448eef2319
commit e05cf48063
7 changed files with 254 additions and 192 deletions

View File

@@ -53,8 +53,8 @@ function initSearch() {
// 初始化无限滚动
function initInfiniteScroll() {
let scrollTimeout;
window.addEventListener('scroll', function() {
window.addEventListener('scroll', function () {
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(handleScroll, 100);
});
@@ -63,12 +63,12 @@ function initInfiniteScroll() {
// 处理滚动事件
function handleScroll() {
if (isLoadingMore || !hasMoreAlbums) return;
// 检查是否滚动到底部
const scrollTop = window.scrollY || document.documentElement.scrollTop;
const scrollHeight = document.documentElement.scrollHeight;
const clientHeight = window.innerHeight;
// 当距离底部还有200px时开始加载
if (scrollTop + clientHeight >= scrollHeight - 200) {
loadMoreAlbums();
@@ -78,7 +78,7 @@ function handleScroll() {
// 加载更多相册
async function loadMoreAlbums() {
if (isLoadingMore || !hasMoreAlbums) return;
isLoadingMore = true;
try {
await loadAlbums();
@@ -101,18 +101,13 @@ function showLoadMoreError() {
<span>加载失败,<a href="javascript:void(0)" onclick="loadMoreAlbums()">点击重试</a></span>
</div>
`;
const existingError = container.querySelector('.load-more-error');
if (existingError) {
existingError.remove();
}
container.appendChild(errorElement);
}
// 防抖搜索
function debouncedSearch() {
searchAlbums();
container.appendChild(errorElement);
}
// 显示骨架屏
@@ -196,7 +191,7 @@ function appendAlbums(albums) {
</div>
`;
}).join('');
// 移除加载指示器并添加新相册
hideLoadingMore();
container.insertAdjacentHTML('beforeend', newAlbumsHTML);
@@ -222,37 +217,37 @@ async function loadAlbums(reset = false) {
showLoadingMore();
}
const response = await fetch(`${API_BASE}/albums?page=${currentPage}&limit=${albumsPerPage}`);
const response = await fetch(`${API_BASE}/albums`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const newAlbums = await response.json();
// 检查是否还有更多数据
if (newAlbums.length < albumsPerPage) {
hasMoreAlbums = false;
}
// 合并到现有相册列表
allAlbums = [...allAlbums, ...newAlbums];
if (currentPage === 1) {
displayAlbums(allAlbums);
} else {
appendAlbums(newAlbums);
}
updateStats(allAlbums);
// 初始化图片懒加载
initLazyLoading();
// 预加载下一批图片
preloadNextBatchImages();
currentPage++;
// 隐藏加载更多指示器
hideLoadingMore();
} catch (error) {
@@ -264,7 +259,7 @@ async function loadAlbums(reset = false) {
// 搜索相册
// 防抖搜索函数
function debouncedSearch() {
async function debouncedSearch() {
const searchTerm = document.getElementById('search-input').value.toLowerCase().trim();
if (searchTerm === '') {
@@ -274,28 +269,19 @@ function debouncedSearch() {
return;
}
// 在当前已加载的数据集中搜索
const filteredAlbums = searchInLoadedAlbums(searchTerm);
if (filteredAlbums.length > 0) {
// 如果当前已加载的数据中有匹配项,直接显示
displayAlbums(filteredAlbums);
document.getElementById('stats').innerHTML = `在当前页面中找到 ${filteredAlbums.length} 个包含 "${searchTerm}" 的相册`;
} else {
// 如果没有找到匹配项,显示提示信息
showSearchHint(searchTerm);
}
// 直接使用后端搜索API进行全站搜索
await performServerSearch(searchTerm);
}
// 在当前已加载的数据集中搜索
function searchInLoadedAlbums(searchTerm) {
if (!allAlbums.length) return [];
return allAlbums.filter(album => {
// 搜索标题和描述
const titleMatch = album.title.toLowerCase().includes(searchTerm);
const descriptionMatch = album.description && album.description.toLowerCase().includes(searchTerm);
return titleMatch || descriptionMatch;
});
}
@@ -328,21 +314,21 @@ async function performServerSearch(searchTerm) {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const serverResults = await response.json();
if (serverResults.length === 0) {
showError(`没有找到包含 "${searchTerm}" 的相册`);
return;
}
// 显示服务器搜索结果
displayAlbums(serverResults);
document.getElementById('stats').innerHTML = `在全站找到 ${serverResults.length} 个包含 "${searchTerm}" 的相册`;
// 初始化图片懒加载
initLazyLoading();
} catch (error) {
console.error('全站搜索失败:', error);
showError('全站搜索失败,请重试');
@@ -416,7 +402,7 @@ function initLazyLoading() {
threshold: 0.01
});
}
const lazyImages = document.querySelectorAll('img.lazy');
lazyImages.forEach(img => {
lazyLoadObserver.observe(img);
@@ -427,14 +413,14 @@ function initLazyLoading() {
function preloadNextBatchImages() {
const imagesToPreload = [];
const visibleImages = document.querySelectorAll('img.lazy');
// 预加载前10张可见图片
visibleImages.forEach((img, index) => {
if (index < 10 && img.dataset.src) {
imagesToPreload.push(img.dataset.src);
}
});
// 使用link预加载
imagesToPreload.forEach(src => {
const link = document.createElement('link');
@@ -461,20 +447,24 @@ function showError(message) {
document.getElementById('stats').innerHTML = '';
}
// 键盘事件处理
function handleKeyPress(event) {
if (event.key === 'Enter') {
searchAlbums();
}
// 搜索相册函数
async function searchAlbums() {
await debouncedSearch();
}
// 性能监控
function logPerformance() {
if ('performance' in window) {
window.addEventListener('load', () => {
setTimeout(() => {
const navigationTiming = performance.getEntriesByType('navigation')[0];
console.log('页面加载时间:', navigationTiming.loadEventEnd - navigationTiming.navigationStart, 'ms');
if (navigationTiming && navigationTiming.loadEventEnd && navigationTiming.navigationStart) {
const loadTime = navigationTiming.loadEventEnd - navigationTiming.navigationStart;
console.log('页面加载时间:', loadTime, 'ms');
} else {
console.log('页面加载时间: 无法计算');
}
}, 0);
});
}
@@ -502,7 +492,7 @@ function preloadCriticalResources() {
'/assets/css/style.css',
'/assets/webfonts/fa-solid-900.woff2'
];
criticalResources.forEach(resource => {
const link = document.createElement('link');
link.rel = 'preload';
@@ -511,13 +501,13 @@ function preloadCriticalResources() {
link.crossOrigin = 'anonymous';
document.head.appendChild(link);
});
// 预加载第一屏可能需要的图片
setTimeout(() => {
const firstScreenImages = [
'/assets/placeholder.svg'
];
firstScreenImages.forEach(img => {
const preload = document.createElement('link');
preload.rel = 'preload';
@@ -532,7 +522,7 @@ function preloadCriticalResources() {
function optimizeScrollPerformance() {
// 使用requestAnimationFrame优化滚动
let ticking = false;
function updateOnScroll() {
// 在滚动时暂停非关键任务
if (!ticking) {
@@ -544,8 +534,8 @@ function optimizeScrollPerformance() {
ticking = true;
}
}
window.addEventListener('scroll', updateOnScroll, { passive: true });
window.addEventListener('scroll', updateOnScroll, {passive: true});
}
// 延迟加载非关键图片
@@ -589,7 +579,7 @@ function openRandomAlbum() {
const randomButton = document.querySelector('.random-button');
randomButton.style.transform = 'scale(0.95)';
randomButton.disabled = true;
// 显示加载状态
const originalText = randomButton.textContent;
randomButton.textContent = '随机加载中...';
@@ -623,7 +613,7 @@ function openRandomAlbum() {
randomButton.disabled = false;
randomButton.textContent = originalText;
}, 200);
alert(error.message);
});
}
@@ -771,7 +761,7 @@ function previewFavorite(index) {
// 显示预览模态框
function showPreviewModal(index) {
const favorite = currentFavorites[index];
// 构建模态框HTML
const modalHtml = `
<div class="preview-modal" id="previewModal">
@@ -830,16 +820,16 @@ function showPreviewModal(index) {
</div>
</div>
`;
// 添加到页面
document.body.insertAdjacentHTML('beforeend', modalHtml);
// 显示模态框
setTimeout(() => {
const modal = document.getElementById('previewModal');
modal.classList.add('active');
}, 10);
// 监听键盘事件
document.addEventListener('keydown', handlePreviewKeydown);
}
@@ -853,7 +843,7 @@ function closePreviewModal() {
modal.remove();
}, 300);
}
// 移除键盘事件监听
document.removeEventListener('keydown', handlePreviewKeydown);
}
@@ -870,30 +860,30 @@ function navigatePreview(direction) {
function updatePreviewContent(newIndex) {
const favorite = currentFavorites[newIndex];
currentPreviewIndex = newIndex;
// 更新标题和相册信息
const titleElement = document.querySelector('.preview-title h3');
const infoElement = document.querySelector('.preview-info');
if (titleElement) titleElement.textContent = favorite.image.title || '未命名图片';
if (infoElement) infoElement.textContent = `来自: ${favorite.album_title}`;
// 更新计数器
const counterElement = document.querySelector('.preview-counter');
if (counterElement) counterElement.textContent = `${newIndex + 1} / ${currentFavorites.length}`;
// 更新导航按钮状态
const prevButton = document.querySelector('.preview-prev');
const nextButton = document.querySelector('.preview-next');
if (prevButton) prevButton.disabled = newIndex === 0;
if (nextButton) nextButton.disabled = newIndex === currentFavorites.length - 1;
// 更新元数据
const metaElements = document.querySelectorAll('.preview-meta .meta-item');
if (metaElements.length >= 3) {
metaElements[0].innerHTML = `<i class="fas fa-calendar"></i> ${formatDate(favorite.favorite.created_at)}`;
metaElements[1].innerHTML = `<i class="fas fa-ruler-combined"></i> ${favorite.image.width} × ${favorite.image.height}`;
}
// 更新操作按钮
const openAlbumButton = document.querySelector('.preview-action:first-child');
const removeButton = document.querySelector('.preview-remove');
@@ -903,22 +893,22 @@ function updatePreviewContent(newIndex) {
if (removeButton) {
removeButton.onclick = () => removeFavoriteFromPreview(favorite.favorite.id);
}
// 更新图片
const imageElement = document.getElementById('preview-image');
if (imageElement ) {
if (imageElement) {
// 显示加载状态
imageElement.style.opacity = '0';
// 加载新图片
const newImage = new Image();
newImage.src = `${API_BASE}/original/${favorite.image.id}`;
newImage.alt = favorite.image.title || '预览图片';
newImage.className = 'preview-image';
newImage.onload = function() {
newImage.onload = function () {
// 替换图片
if (imageElement.parentNode) {
imageElement.parentNode.replaceChild(newImage, imageElement);
@@ -928,8 +918,8 @@ function updatePreviewContent(newIndex) {
newImage.style.opacity = '1';
};
newImage.onerror = function() {
newImage.onerror = function () {
// 图片加载失败
imageElement.innerHTML = '<i class="fas fa-exclamation-triangle"></i><span>图片加载失败</span>';
};
@@ -1010,7 +1000,6 @@ function openFavoriteImage(favoriteId) {
}
// 导出函数供全局使用
window.handleKeyPress = handleKeyPress;
window.searchAlbums = searchAlbums;
window.openRandomAlbum = openRandomAlbum;
window.showFavorites = showFavorites;