优化前端显示

This commit is contained in:
2026-03-13 23:28:00 +08:00
parent 4be862d66b
commit 33d2231bed
10 changed files with 675 additions and 210 deletions

View File

@@ -5,7 +5,8 @@ import { svelteKitHandler } from 'better-auth/svelte-kit';
import { getTextDirection } from '$lib/paraglide/runtime';
import { paraglideMiddleware } from '$lib/paraglide/server';
/** @type {import('@sveltejs/kit').Handle} */ const handleParaglide = ({ event, resolve }) =>
/** @type {import('@sveltejs/kit').Handle} */
const handleParaglide = ({ event, resolve }) =>
paraglideMiddleware(event.request, ({ request, locale }) => {
event.request = request;
@@ -17,7 +18,8 @@ import { paraglideMiddleware } from '$lib/paraglide/server';
});
});
/** @type {import('@sveltejs/kit').Handle} */ const handleBetterAuth = async ({
/** @type {import('@sveltejs/kit').Handle} */
const handleBetterAuth = async ({
event,
resolve
}) => {
@@ -33,8 +35,43 @@ import { paraglideMiddleware } from '$lib/paraglide/server';
return svelteKitHandler({ event, resolve, auth, building });
};
export /** @type {import('@sveltejs/kit').Handle} */ const handle = sequence(
handleParaglide,
handleBetterAuth
);
/** @type {import('@sveltejs/kit').Handle} */
const handleCache = async ({ event, resolve }) => {
const response = await resolve(event);
// 克隆响应以便修改头
const newResponse = new Response(response.body, response);
// 为静态资源添加缓存头
const url = new URL(event.request.url);
const pathname = url.pathname;
// 静态资源缓存 1 年
if (pathname.startsWith('/_app/') || pathname.match(/\.[a-f0-9]+\.(css|js)$/)) {
newResponse.headers.set('Cache-Control', 'public, max-age=31536000, immutable');
}
// API 响应缓存 1 分钟(相册列表、照片列表等)
else if (pathname.startsWith('/api/')) {
newResponse.headers.set('Cache-Control', 'public, max-age=60, stale-while-revalidate=300');
}
// 图片预览接口缓存 1 小时
else if (pathname.match(/\/api\/.*\/(preview|file)$/)) {
newResponse.headers.set('Cache-Control', 'public, max-age=3600, stale-while-revalidate=86400');
}
// 页面 HTML 不缓存或短时缓存
else if (pathname.startsWith('/album/')) {
// 相册页面:短时缓存,快速更新
newResponse.headers.set('Cache-Control', 'public, max-age=30, stale-while-revalidate=300');
}
else {
newResponse.headers.set('Cache-Control', 'public, max-age=0, stale-while-revalidate=60');
}
return newResponse;
};
export const handle = sequence(
handleParaglide,
handleBetterAuth,
handleCache
);

View File

@@ -2,10 +2,12 @@ const API_BASE = '/api/v1';
/**
* @param {string} endpoint
* @param {typeof fetch} [customFetch]
* @returns {Promise<any>}
*/
async function fetchApi(endpoint) {
const response = await fetch(`${API_BASE}${endpoint}`);
export async function fetchApi(endpoint, customFetch) {
const fetchFn = customFetch ?? fetch;
const response = await fetchFn(`${API_BASE}${endpoint}`);
if (!response.ok) {
if (response.status === 404) {
return null;

View File

@@ -1,5 +1,4 @@
import { betterAuth } from 'better-auth/minimal';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { sveltekitCookies } from 'better-auth/svelte-kit';
import { env } from '$env/dynamic/private';
import { getRequestEvent } from '$app/server';

View File

@@ -1,6 +1,7 @@
<script>
import { page } from '$app/state';
import { locales, localizeHref } from '$lib/paraglide/runtime';
import { resolve } from '$app/paths';
import favicon from '$lib/assets/favicon.svg';
let { children } = $props();

View File

@@ -0,0 +1,10 @@
import { fetchApi } from '$lib/api/client';
export async function load({ fetch }) {
try {
const albums = await fetchApi('/album', fetch);
return { albums: albums ?? [] };
} catch (error) {
return { albums: [] };
}
}

View File

@@ -1,22 +1,11 @@
<script>
import { onMount } from 'svelte';
import { getAlbums } from '$lib/api/client';
import { albums, loading, no_albums } from '$lib/paraglide/messages';
import { resolve } from '$app/paths';
let { data } = $props();
/** @type {import('$lib/api/types').Album[]} */
let albums_list = $state([]);
let loading_state = $state(true);
let error = $state(/** @type {string|null} */ (null));
onMount(async () => {
try {
albums_list = await getAlbums();
} catch (e) {
error = e instanceof Error ? e.message : 'Unknown error';
} finally {
loading_state = false;
}
});
let albums_list = $derived(data.albums ?? []);
</script>
<svelte:head>
@@ -28,16 +17,12 @@
<h1>{albums()}</h1>
</header>
{#if loading_state}
<div class="loading">{loading()}</div>
{:else if error}
<div class="error">{error}</div>
{:else if albums_list.length === 0}
{#if albums_list.length === 0}
<div class="empty">{no_albums()}</div>
{:else}
<div class="album-grid">
{#each albums_list as album (album.id)}
<a href="/album/{album.id}" class="album-card">
<a href={resolve(`/album/${album.id}`)} class="album-card">
<div class="album-icon">📁</div>
<h3 class="album-name">{album.name}</h3>
<p class="album-date">
@@ -66,18 +51,12 @@
color: #1a1a1a;
}
.loading,
.empty,
.error {
.empty {
text-align: center;
padding: 4rem 2rem;
color: #666;
}
.error {
color: #dc2626;
}
.album-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));

View File

@@ -0,0 +1,45 @@
import { fetchApi } from '$lib/api/client';
/** @type {import('./$types').PageServerLoad} */
export async function load({ params, fetch, url }) {
const albumId = params.id;
// 支持分页参数,默认每页 100 张照片
const page = parseInt(url.searchParams.get('page') || '1', 10);
const pageSize = parseInt(url.searchParams.get('pageSize') || '100', 10);
try {
const [album, photos] = await Promise.all([
fetchApi(`/album/${albumId}`, fetch),
// 如果后端支持分页,传递 page 和 pageSize 参数
fetchApi(`/album/${albumId}/photo?page=${page}&pageSize=${pageSize}`, fetch)
]);
if (!album) {
return {
album: null,
photos: [],
hasMore: false,
totalPhotos: 0
};
}
// 检测后端是否返回了分页信息
const hasMore = photos?.length === pageSize;
const totalPhotos = photos?.total ?? photos?.length ?? 0;
return {
album,
photos: photos?.items ?? photos ?? [],
hasMore,
totalPhotos
};
} catch (error) {
return {
album: null,
photos: [],
hasMore: false,
totalPhotos: 0
};
}
}

View File

@@ -1,83 +1,107 @@
<script>
import { onMount, onDestroy } from 'svelte';
import { page } from '$app/state';
import { getAlbum, getAlbumPhotos, getPhotoFileUrl, getPhotoPreviewUrl } from '$lib/api/client';
import { albums, loading, no_albums, back, photo_count } from '$lib/paraglide/messages';
import { albums, back, photo_count, loading } from '$lib/paraglide/messages';
import { resolve } from '$app/paths';
import { getPhotoPreviewUrl } from '$lib/api/client';
let { data } = $props();
/** @type {import('$lib/api/types').Album|null} */
let album = $state(null);
let album = $derived(data.album);
/** @type {import('$lib/api/types').Photo[]} */
let photos = $state([]);
let loading_state = $state(true);
let error = $state(/** @type {string|null} */ (null));
// 分批加载配置
const BATCH_SIZE = 100;
let initialPhotos = $derived(data.photos ?? []);
let hasMore = $derived(data.hasMore ?? false);
// 所有已加载的照片(支持分页追加)
let allPhotos = $state([...initialPhotos]);
// 分批加载配置 - 前端虚拟滚动
const BATCH_SIZE = 50;
let displayedCount = $state(BATCH_SIZE);
// 当前页码
let currentPage = $state(1);
const PAGE_SIZE = 100;
/** @type {HTMLDivElement|null} */
let scrollContainer = $state(null);
/** @type {IntersectionObserver|null} */
let observer = $state(null);
/** @type {HTMLDivElement|null} */
let loadMoreTrigger = $state(null);
/** @type {boolean} */
let isLoading = $state(false);
onMount(async () => {
const albumId = parseInt(page.params.id ?? '');
if (isNaN(albumId)) {
error = 'Invalid album id';
loading_state = false;
return;
}
try {
[album, photos] = await Promise.all([getAlbum(albumId), getAlbumPhotos(albumId)]);
if (!album) {
error = 'Album not found';
}
} catch (e) {
error = e instanceof Error ? e.message : 'Unknown error';
} finally {
loading_state = false;
// 监听数据变化,重置状态
$effect(() => {
if (data.photos) {
allPhotos = [...initialPhotos];
displayedCount = BATCH_SIZE;
currentPage = 1;
isLoading = false;
}
});
onMount(() => {
// 设置 Intersection Observer 监听加载更多
observer = new IntersectionObserver(
// 监听滚动容器和加载更多触发器
$effect(() => {
if (!scrollContainer || !loadMoreTrigger || isLoading) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && displayedCount < photos.length) {
loadMore();
if (entries[0].isIntersecting && !isLoading) {
if (displayedCount < allPhotos.length) {
loadMore();
} else if (hasMore) {
loadNextPage();
}
}
},
{
root: scrollContainer,
rootMargin: '200px',
rootMargin: '100px',
threshold: 0
}
);
observer.observe(loadMoreTrigger);
return () => {
if (observer) {
observer.disconnect();
}
observer.disconnect();
};
});
onMount(() => {
if (loadMoreTrigger && observer) {
observer.observe(loadMoreTrigger);
}
});
// 前端分批加载
function loadMore() {
if (displayedCount >= photos.length) return;
displayedCount = Math.min(displayedCount + BATCH_SIZE, photos.length);
if (displayedCount >= allPhotos.length) return;
displayedCount = Math.min(displayedCount + BATCH_SIZE, allPhotos.length);
}
// 加载下一页(从服务器)
async function loadNextPage() {
if (isLoading) return;
isLoading = true;
currentPage++;
try {
const response = await fetch(
`${page.url.pathname}?page=${currentPage}&pageSize=${PAGE_SIZE}`
);
const newData = await response.json();
if (newData.photos) {
const newPhotos = newData.photos.items ?? newData.photos;
allPhotos = [...allPhotos, ...newPhotos];
hasMore = newPhotos.length === PAGE_SIZE;
displayedCount += BATCH_SIZE;
}
} catch (error) {
console.error('Failed to load more photos:', error);
} finally {
isLoading = false;
}
}
function getVisiblePhotos() {
return photos.slice(0, displayedCount);
return allPhotos.slice(0, displayedCount);
}
</script>
@@ -87,38 +111,38 @@
<div class="container">
<header class="header">
<a href="/" class="back-link">{back()}</a>
<a href={resolve('/')} class="back-link">← {back()}</a>
{#if album}
<h1>{album.name}</h1>
<p class="photo-count">
{photo_count({ count: photos.length })}
{photo_count({ count: data.totalPhotos || allPhotos.length })}
</p>
{/if}
</header>
{#if loading_state}
<div class="loading">{loading()}</div>
{:else if error}
<div class="error">{error}</div>
{:else if photos.length === 0}
<div class="empty">{no_albums()}</div>
{#if !album || (allPhotos.length === 0 && !hasMore)}
<div class="empty">暂无照片</div>
{:else}
<div class="photo-scroll-container" bind:this={scrollContainer}>
<div class="photo-grid">
{#each getVisiblePhotos() as photo (photo.id)}
<a href="/photo/{photo.id}" class="photo-card">
<a href={resolve(`/photo/${photo.id}`)} class="photo-card">
<div class="photo-wrapper">
{#if photo.mimeType.startsWith('video/')}
{#if photo.mimeType?.startsWith('video/')}
<div class="video-indicator">🎬</div>
<div class="photo-placeholder">
<span>{photo.fileName}</span>
</div>
{:else}
{@const previewBase = getPhotoPreviewUrl(photo.id)}
<img
src={getPhotoPreviewUrl(photo.id)}
src={previewBase}
srcset="{previewBase}?w=400 400w, {previewBase}?w=800 800w"
sizes="(max-width: 768px) 150px, (max-width: 1200px) 200px, 250px"
alt={photo.fileName}
loading="lazy"
decoding="async"
class="photo-image"
/>
{/if}
</div>
@@ -127,13 +151,17 @@
{/each}
</div>
{#if displayedCount < photos.length}
<div class="load-more-trigger" bind:this={loadMoreTrigger}>
<div class="loading-more">{loading()}</div>
{#if isLoading}
<div class="loading-trigger">
<div class="loading-spinner">{loading()}</div>
</div>
{:else}
{:else if displayedCount < allPhotos.length || hasMore}
<div class="load-more-trigger" bind:this={loadMoreTrigger}>
<div class="loading-more">{loading()}...</div>
</div>
{:else if allPhotos.length > 0}
<div class="load-complete">
✓ 已加载全部 {photos.length} 张照片
✓ 已加载全部 {allPhotos.length} 张照片
</div>
{/if}
</div>
@@ -145,7 +173,7 @@
max-width: 1400px;
margin: 0 auto;
padding: 2rem;
height: calc(100vh - 4rem);
min-height: calc(100vh - 4rem);
display: flex;
flex-direction: column;
}
@@ -180,22 +208,18 @@
margin: 0;
}
.loading,
.empty,
.error {
.empty {
text-align: center;
padding: 4rem 2rem;
color: #666;
}
.error {
color: #dc2626;
font-size: 1.125rem;
}
.photo-scroll-container {
flex: 1;
overflow-y: auto;
scroll-behavior: smooth;
min-height: 400px;
}
.photo-scroll-container::-webkit-scrollbar {
@@ -218,11 +242,17 @@
.photo-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 1rem;
padding-bottom: 2rem;
}
@media (min-width: 768px) {
.photo-grid {
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
}
}
.photo-card {
display: block;
text-decoration: none;
@@ -232,22 +262,23 @@
.photo-wrapper {
position: relative;
aspect-ratio: 1;
background: #f3f4f6;
background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 100%);
border-radius: 8px;
overflow: hidden;
margin-bottom: 0.5rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.photo-wrapper img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s;
transition: transform 0.3s ease;
background: #e5e7eb;
}
.photo-card:hover .photo-wrapper img {
transform: scale(1.05);
transform: scale(1.08);
}
.photo-placeholder {
@@ -260,18 +291,20 @@
font-size: 0.875rem;
padding: 1rem;
text-align: center;
word-break: break-word;
}
.video-indicator {
position: absolute;
top: 0.5rem;
right: 0.5rem;
background: rgba(0, 0, 0, 0.7);
background: rgba(0, 0, 0, 0.75);
color: white;
padding: 0.25rem 0.5rem;
border-radius: 4px;
padding: 0.35rem 0.6rem;
border-radius: 6px;
font-size: 0.875rem;
z-index: 1;
backdrop-filter: blur(4px);
}
.photo-name {
@@ -281,16 +314,29 @@
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 0 0.25rem;
}
.load-more-trigger {
.load-more-trigger,
.loading-trigger {
text-align: center;
padding: 2rem;
}
.loading-more {
.loading-more,
.loading-spinner {
display: inline-block;
color: #6b7280;
font-size: 0.95rem;
}
.loading-spinner {
animation: pulse 1.5s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { opacity: 0.5; }
50% { opacity: 1; }
}
.load-complete {
@@ -298,5 +344,6 @@
padding: 2rem;
color: #10b981;
font-size: 0.875rem;
font-weight: 500;
}
</style>

View File

@@ -0,0 +1,70 @@
import { fetchApi } from '$lib/api/client';
/** @type {import('./$types').PageServerLoad} */
export async function load({ params, fetch }) {
const photoId = params.id;
try {
// 获取当前照片信息
const photo = await fetchApi(`/photo/${photoId}`, fetch);
if (!photo) {
return {
photo: null,
currentIndex: 0,
totalPhotos: 0,
hasPrev: false,
hasNext: false,
prevPhotoId: null,
nextPhotoId: null
};
}
// 默认导航信息
let currentIndex = 0;
let totalPhotos = 1;
let prevPhotoId = null;
let nextPhotoId = null;
// 如果有 albumId尝试获取相册中的照片列表
if (photo.albumId) {
try {
const albumPhotos = await fetchApi(`/album/${photo.albumId}/photo`, fetch);
const photos = Array.isArray(albumPhotos) ? albumPhotos : [];
if (photos.length > 0) {
const index = photos.findIndex(p => String(p.id) === String(photoId));
if (index >= 0) {
currentIndex = index;
totalPhotos = photos.length;
prevPhotoId = index > 0 ? photos[index - 1].id : null;
nextPhotoId = index < photos.length - 1 ? photos[index + 1].id : null;
}
}
} catch (e) {
// 静默失败,使用默认值
}
}
return {
photo,
currentIndex,
totalPhotos,
hasPrev: prevPhotoId !== null,
hasNext: nextPhotoId !== null,
prevPhotoId,
nextPhotoId
};
} catch (error) {
console.error('Failed to load photo:', error);
return {
photo: null,
currentIndex: 0,
totalPhotos: 0,
hasPrev: false,
hasNext: false,
prevPhotoId: null,
nextPhotoId: null
};
}
}

View File

@@ -1,75 +1,112 @@
<script>
import { onMount } from 'svelte';
import { page } from '$app/state';
import { getPhoto, getPhotoFileUrl, getAlbumPhotos, getPhotoPreviewUrl } from '$lib/api/client';
import { m, loading } from '$lib/paraglide/messages';
import { m } from '$lib/paraglide/messages';
import { resolve } from '$app/paths';
import { getPhotoPreviewUrl, getPhotoFileUrl } from '$lib/api/client';
import { goto } from '$app/navigation';
let { data } = $props();
/** @type {import('$lib/api/types').Photo|null} */
let photo = $state(null);
/** @type {import('$lib/api/types').Photo[]} */
let albumPhotos = $state([]);
let currentIndex = $state(0);
let loading_state = $state(true);
let error = $state(/** @type {string|null} */ (null));
let photo = $derived(data.photo);
let currentIndex = $derived(data.currentIndex ?? 0);
let totalPhotos = $derived(data.totalPhotos ?? 0);
let hasPrev = $derived(data.hasPrev ?? false);
let hasNext = $derived(data.hasNext ?? false);
let prevPhotoId = $derived(data.prevPhotoId);
let nextPhotoId = $derived(data.nextPhotoId);
onMount(async () => {
const photoId = parseInt(page.params.id ?? '');
if (isNaN(photoId)) {
error = 'Invalid photo id';
loading_state = false;
return;
}
// 导航加载状态(切换照片时)
let isNavigating = $state(false);
let loadError = $state(false);
try {
photo = await getPhoto(photoId);
if (!photo) {
error = 'Photo not found';
} else {
albumPhotos = await getAlbumPhotos(photo.albumId);
currentIndex = albumPhotos.findIndex((p) => p.id === photoId);
}
} catch (e) {
error = e instanceof Error ? e.message : 'Unknown error';
} finally {
loading_state = false;
}
});
// 触摸滑动支持
let touchStartX = 0;
let touchEndX = 0;
const SWIPE_THRESHOLD = 50;
function goToPrevious() {
if (currentIndex > 0) {
const prevPhoto = albumPhotos[currentIndex - 1];
history.pushState({}, '', `/photo/${prevPhoto.id}`);
photo = albumPhotos[currentIndex - 1];
currentIndex--;
}
if (!hasPrev || isNavigating) return;
navigateToPhoto(prevPhotoId);
}
function goToNext() {
if (currentIndex < albumPhotos.length - 1) {
const nextPhoto = albumPhotos[currentIndex + 1];
history.pushState({}, '', `/photo/${nextPhoto.id}`);
photo = albumPhotos[currentIndex + 1];
currentIndex++;
if (!hasNext || isNavigating) return;
navigateToPhoto(nextPhotoId);
}
async function navigateToPhoto(photoId) {
if (isNavigating) return;
isNavigating = true;
loadError = false;
try {
await goto(`/photo/${photoId}`, { keepFocus: true });
} catch (error) {
console.error('Failed to navigate:', error);
loadError = true;
} finally {
isNavigating = false;
}
}
function handleClose() {
if (photo) {
if (photo?.albumId) {
goto(resolve(`/album/${photo.albumId}`));
} else {
history.back();
}
}
onMount(() => {
/** @param {Event} event */
// 触摸事件处理
function handleTouchStart(event) {
touchStartX = event.touches[0].clientX;
}
function handleTouchMove(event) {
touchEndX = event.touches[0].clientX;
}
function handleTouchEnd() {
if (!touchStartX || !touchEndX) return;
const diff = touchStartX - touchEndX;
if (Math.abs(diff) > SWIPE_THRESHOLD) {
if (diff > 0) {
goToNext();
} else {
goToPrevious();
}
}
touchStartX = 0;
touchEndX = 0;
}
// 键盘导航
$effect(() => {
function handleKeydown(event) {
const keyboardEvent = /** @type {KeyboardEvent} */ (event);
if (keyboardEvent.key === 'ArrowLeft') {
goToPrevious();
} else if (keyboardEvent.key === 'ArrowRight') {
goToNext();
} else if (keyboardEvent.key === 'Escape') {
handleClose();
if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
return;
}
switch (keyboardEvent.key) {
case 'ArrowLeft':
event.preventDefault();
goToPrevious();
break;
case 'ArrowRight':
event.preventDefault();
goToNext();
break;
case 'Escape':
event.preventDefault();
handleClose();
break;
}
}
@@ -85,22 +122,86 @@
}
};
});
// 智能预加载
$effect(() => {
let cancelled = false;
let preloadTimeout;
preloadTimeout = setTimeout(() => {
if (cancelled) return;
if (hasNext && nextPhotoId) {
const nextImg = new Image();
nextImg.src = getPhotoPreviewUrl(nextPhotoId);
nextImg.fetchPriority = 'low';
}
if (hasPrev && prevPhotoId) {
const prevImg = new Image();
prevImg.src = getPhotoPreviewUrl(prevPhotoId);
prevImg.fetchPriority = 'low';
}
}, 300);
return () => {
cancelled = true;
clearTimeout(preloadTimeout);
};
});
// 图片加载完成
function handleImageLoad() {
isNavigating = false;
}
function handleImageError() {
isNavigating = false;
loadError = true;
}
</script>
<svelte:head>
<title>{photo ? photo.fileName : loading()}</title>
<title>{photo ? photo.fileName : m.loading()}</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
</svelte:head>
<div class="viewer-container" role="application" tabindex="0">
{#if loading_state}
<div class="loading">{m.loading()}</div>
{:else if error}
<div class="error">{m.error()}</div>
{:else if photo}
<div
class="viewer-container"
role="application"
tabindex="0"
ontouchstart={handleTouchStart}
ontouchmove={handleTouchMove}
ontouchend={handleTouchEnd}
>
{#if !photo}
<div class="loading">
<div class="loading-spinner"></div>
<p>{m.loading()}</p>
</div>
{:else}
<!-- 导航加载指示器 -->
{#if isNavigating}
<div class="loading-indicator">
<div class="loading-spinner small"></div>
</div>
{/if}
<!-- 错误提示 -->
{#if loadError}
<div class="error-toast">
<span>加载失败</span>
<button onclick={() => loadError = false}>重试</button>
</div>
{/if}
<div class="viewer-header">
<a href="/album/{photo.albumId}" class="back-link">{m.back()}</a>
<a href={resolve(`/album/${photo.albumId}`)} class="back-link">
<span class="back-icon"></span>
<span class="back-text">{m.back()}</span>
</a>
<span class="photo-index">
{currentIndex + 1} / {albumPhotos.length}
{currentIndex + 1} / {totalPhotos}
</span>
</div>
@@ -108,39 +209,67 @@
<button
class="nav-button prev"
onclick={goToPrevious}
disabled={currentIndex === 0}
disabled={!hasPrev || isNavigating}
aria-label="Previous photo"
type="button"
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M15 18l-6-6 6-6" />
</svg>
</button>
<div class="image-wrapper">
{#if photo.mimeType.startsWith('video/')}
<video controls>
{#if photo.mimeType?.startsWith('video/')}
<video
controls
playsinline
onloadeddata={handleImageLoad}
onerror={handleImageError}
>
<source src={getPhotoFileUrl(photo.id)} type={photo.mimeType} />
</video>
{:else}
<img src={getPhotoPreviewUrl(photo.id)} alt={photo.fileName} />
{@const previewSrc = getPhotoPreviewUrl(photo.id)}
<img
src={previewSrc}
srcset="{previewSrc}?w=800 800w, {previewSrc}?w=1200 1200w, {previewSrc}?w=1600 1600w"
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 80vw, 60vw"
alt={photo.fileName}
onload={handleImageLoad}
onerror={handleImageError}
decoding="async"
/>
{/if}
</div>
<button
class="nav-button next"
onclick={goToNext}
disabled={currentIndex === albumPhotos.length - 1}
disabled={!hasNext || isNavigating}
aria-label="Next photo"
type="button"
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M9 18l6-6-6-6" />
</svg>
</button>
</div>
<div class="photo-info">
<h2>{photo.fileName}</h2>
<p class="meta">
{Math.round(photo.fileSize / 1024)} KB •
{photo.width && photo.height ? `${photo.width}×${photo.height}` : ''}
{new Date(photo.createdAt).toLocaleDateString()}
</p>
<div class="photo-details">
<h2>{photo.fileName}</h2>
<p class="meta">
{#if photo.fileSize}
<span>{Math.round(photo.fileSize / 1024)} KB</span>
{/if}
{#if photo.width && photo.height}
<span>{photo.width}×{photo.height}</span>
{/if}
{#if photo.createdAt}
<span>{new Date(photo.createdAt).toLocaleDateString()}</span>
{/if}
</p>
</div>
</div>
{/if}
</div>
@@ -155,48 +284,140 @@
flex-direction: column;
z-index: 1000;
outline: none;
overflow: hidden;
touch-action: pan-y;
}
.viewer-container:focus {
outline: none;
}
.loading,
.error {
/* 加载状态 */
.loading {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
font-size: 1.25rem;
gap: 1rem;
}
.error {
color: #ef4444;
.loading-spinner {
width: 48px;
height: 48px;
border: 3px solid rgba(255, 255, 255, 0.3);
border-top-color: white;
border-radius: 50%;
animation: spin 1s linear infinite;
}
.loading-spinner.small {
width: 24px;
height: 24px;
border-width: 2px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.loading p {
color: #9ca3af;
font-size: 1rem;
margin: 0;
}
.loading-indicator {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 100;
pointer-events: none;
}
/* 错误提示 */
.error-toast {
position: absolute;
top: 80px;
left: 50%;
transform: translateX(-50%);
background: rgba(239, 68, 68, 0.9);
color: white;
padding: 0.75rem 1.5rem;
border-radius: 8px;
display: flex;
align-items: center;
gap: 1rem;
z-index: 101;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
.error-toast button {
background: rgba(255, 255, 255, 0.2);
border: none;
color: white;
padding: 0.25rem 0.75rem;
border-radius: 4px;
cursor: pointer;
font-size: 0.875rem;
}
.error-toast button:hover {
background: rgba(255, 255, 255, 0.3);
}
/* 头部 */
.viewer-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 1.5rem;
background: rgba(0, 0, 0, 0.5);
padding: 0.75rem 1rem;
background: linear-gradient(to bottom, rgba(0, 0, 0, 0.8), transparent);
position: absolute;
top: 0;
left: 0;
right: 0;
z-index: 10;
}
.back-link {
display: flex;
align-items: center;
gap: 0.5rem;
color: white;
text-decoration: none;
font-size: 1rem;
font-size: 0.95rem;
padding: 0.5rem 0.75rem;
background: rgba(255, 255, 255, 0.1);
border-radius: 6px;
transition: background 0.2s;
}
.back-link:hover {
text-decoration: underline;
background: rgba(255, 255, 255, 0.2);
}
.back-icon {
font-size: 1.25rem;
line-height: 1;
}
@media (max-width: 640px) {
.back-text {
display: none;
}
}
.photo-index {
color: #9ca3af;
color: #d1d5db;
font-size: 0.875rem;
background: rgba(255, 255, 255, 0.1);
padding: 0.35rem 0.75rem;
border-radius: 6px;
}
/* 内容区域 */
.viewer-content {
flex: 1;
display: flex;
@@ -212,6 +433,7 @@
display: flex;
align-items: center;
justify-content: center;
position: relative;
}
.image-wrapper img,
@@ -221,6 +443,7 @@
object-fit: contain;
}
/* 导航按钮 */
.nav-button {
position: absolute;
top: 50%;
@@ -228,18 +451,32 @@
background: rgba(255, 255, 255, 0.1);
color: white;
border: none;
font-size: 3rem;
padding: 1rem;
padding: 0.75rem;
cursor: pointer;
transition: background 0.2s;
transition: all 0.2s;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
z-index: 5;
}
.nav-button svg {
width: 24px;
height: 24px;
}
.nav-button:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.2);
background: rgba(255, 255, 255, 0.25);
transform: translateY(-50%) scale(1.1);
}
.nav-button:active:not(:disabled) {
transform: translateY(-50%) scale(0.95);
}
.nav-button:disabled {
opacity: 0.3;
opacity: 0.2;
cursor: not-allowed;
}
@@ -251,9 +488,39 @@
right: 1rem;
}
@media (max-width: 768px) {
.nav-button {
padding: 0.5rem;
}
.nav-button svg {
width: 20px;
height: 20px;
}
.nav-button.prev {
left: 0.5rem;
}
.nav-button.next {
right: 0.5rem;
}
}
/* 照片信息 */
.photo-info {
padding: 1rem 1.5rem;
background: rgba(0, 0, 0, 0.5);
padding: 1rem;
background: linear-gradient(to top, rgba(0, 0, 0, 0.9), transparent);
position: absolute;
bottom: 0;
left: 0;
right: 0;
z-index: 10;
}
.photo-details {
max-width: 800px;
margin: 0 auto;
}
.photo-info h2 {
@@ -263,11 +530,19 @@
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: white;
}
.photo-info .meta {
font-size: 0.875rem;
font-size: 0.8rem;
color: #9ca3af;
margin: 0;
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
}
.photo-info .meta span {
display: inline-flex;
align-items: center;
}
</style>