Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
feat: 新增 PhotoViewer、渐进式图像渲染器
HoshinoSuzumib78d16b40823
diff --git a/app/assets/css/tailwind.css b/app/assets/css/tailwind.cssindex 043f8ce7..34928883 100644--- a/app/assets/css/tailwind.css+++ b/app/assets/css/tailwind.css@@ -1,5 +1,5 @@-@import "tailwindcss";-@import "@nuxt/ui";+@import 'tailwindcss';+@import '@nuxt/ui';:root {--ui-text-dimmed: var(--ui-color-neutral-400);@@ -41,3 +41,8 @@--ui-border-inverted: var(--color-white);}+@theme {+ --font-sans: Rubik, 'Noto Sans SC', sans-serif;++ --leading-normal: normal;+}diff --git a/app/components/DateRangeIndicator.vue b/app/components/DateRangeIndicator.vueindex f3cee69c..efa1ee90 100644--- a/app/components/DateRangeIndicator.vue+++ b/app/components/DateRangeIndicator.vue@@ -5,6 +5,7 @@ const props = defineProps<{dateRange?: stringlocations?: stringisVisible: boolean+ isMobile?: booleanclass?: string}>()@@ -12,7 +13,7 @@ const shouldShow = computed(() => {return props.isVisible && !!props.dateRange})-const variants = {+const dateRangeVariants = {initial: {opacity: 0,x: -20,@@ -24,32 +25,62 @@ const variants = {scale: 1,},}++const mobileVariants = {+ initial: {+ opacity: 0,+ y: -20,+ },+ animate: {+ opacity: 1,+ y: 0,+ },+}</script><template><div><AnimatePresence>+ <!-- Desktop Date Range Indicator --><motion.div- v-if="shouldShow"- class="fixed top-4 left-4 z-50 lg:top-6 lg:left-6"- :initial="variants.initial"- :animate="variants.animate"- :exit="variants.initial"+ v-if="shouldShow && !isMobile"+ class="fixed top-4 left-4 z-50 lg:top-6 lg:left-6 flex flex-col gap-1 bg-black/40 backdrop-blur-3xl rounded-xl border border-white/10 px-4 py-2 shadow-2xl"+ :initial="dateRangeVariants.initial"+ :animate="dateRangeVariants.animate"+ :exit="dateRangeVariants.initial":transition="{type: 'spring',duration: 0.4,bounce: 0.15,}"+ >+ <span class="text-white text-4xl font-black leading-normal tracking-wide">{{ dateRange }}</span>+ <span v-if="locations" class="text-white/60 text-xl font-bold">{{ locations }}</span>+ </motion.div>++ <!-- Mobile Date Range Indicator -->+ <motion.div+ v-if="shouldShow && isMobile"+ class="fixed inset-0 bottom-auto z-50"+ :initial="mobileVariants.initial"+ :animate="mobileVariants.animate"+ :exit="mobileVariants.initial"+ :transition="{+ type: 'spring',+ duration: 0.3,+ bounce: 0.1,+ }"><div- class="flex flex-col gap-1 bg-black/60 backdrop-blur-[70px] rounded-xl border border-white/10 px-4 py-2 shadow-2xl"+ class="bg-black/60 backdrop-blur-3xl border-b border-white/10 px-4 py-2 shadow-2xl">- <span class="text-white text-4xl font-black">{{ dateRange }}</span>- <span class="text-white/60 text-xl font-bold">{{ locations }}</span>+ <span class="text-white text-lg font-medium">{{ dateRange }}</span>+ <span v-if="locations" class="text-white/60 text-xs ml-2">{{ locations }}</span></div></motion.div></AnimatePresence></div></template>-<style scoped></style>+<style scoped>+</style>diff --git a/app/components/masonry/HeaderItem.vue b/app/components/masonry/HeaderItem.vueindex 208aa5d1..0be2cd05 100644--- a/app/components/masonry/HeaderItem.vue+++ b/app/components/masonry/HeaderItem.vue@@ -1,6 +1,6 @@<script lang="ts" setup>defineProps<{- stats: {+ stats?: {total: numberwithDates: numberwithTitles: number@@ -23,12 +23,12 @@ defineProps<{Photo Gallery</h1><div class="text-gray-600 dark:text-gray-400 space-y-1">- <p class="text-lg">{{ stats.total }} 张照片</p>+ <p class="text-lg">{{ stats?.total }} 张照片</p><div class="text-sm space-y-1"><p v-if="dateRangeText">时间跨度: {{ dateRangeText }}</p><p>- {{ stats.withDates }} 张包含拍摄时间 ·- {{ stats.withExif }} 张包含 EXIF 数据+ {{ stats?.withDates }} 张包含拍摄时间 ·+ {{ stats?.withExif }} 张包含 EXIF 数据</p></div></div>diff --git a/app/components/masonry/Item.vue b/app/components/masonry/Item.vueindex 029f39cf..fd1909b6 100644--- a/app/components/masonry/Item.vue+++ b/app/components/masonry/Item.vue@@ -18,6 +18,7 @@ const emit = defineEmits<{'visibility-change': [{ index: number; isVisible: boolean; date: string | Date },]+ openViewer: [number]}>()const itemKey = computed(() => {@@ -70,6 +71,7 @@ const itemVariants = {:photo="photo":index="index"@visibility-change="emit('visibility-change', $event)"+ @open-viewer="emit('openViewer', $event)"/></motion.div></template>diff --git a/app/components/masonry/PhotoItem.client.vue b/app/components/masonry/PhotoItem.client.vueindex 25f7a8df..92fd62d1 100644--- a/app/components/masonry/PhotoItem.client.vue+++ b/app/components/masonry/PhotoItem.client.vue@@ -9,6 +9,7 @@ const emit = defineEmits<{'visibility-change': [{ index: number; isVisible: boolean; date: string | Date },]+ openViewer: [number]}>()// Constants@@ -195,6 +196,7 @@ onMounted(() => {:style="{marginBottom: `${ITEM_GAP}px`,}"+ @click="emit('openViewer', props.index)"><divclass="relative group overflow-hidden transition-all duration-300"@@ -207,7 +209,7 @@ onMounted(() => {><Thumbhash:thumbhash="photo.thumbnailHash"- class="w-full h-full object-cover filter blur-sm"+ class="w-full h-full object-cover scale-110":alt="photo.title || 'Photo placeholder'"/></div>@@ -243,7 +245,7 @@ onMounted(() => {<div class="flex flex-col"><pv-if="photo.title"- class="text-base font-medium"+ class="text-base font-medium text-ellipsis line-clamp-1">{{ photo.title }}</p>@@ -278,13 +280,10 @@ onMounted(() => {<!-- Camera info from EXIF if available --><divv-if="photo.exif && (photo.exif.Make || photo.exif.Model)"- class="text-sm opacity-70 mt-1 flex items-center gap-0.5"+ class="text-sm opacity-70 mt-1 flex items-center gap-1">- <Icon- name="tabler:camera"- class="mt-[1px]"- />- <span class="text-xs font-medium">+ <Icon name="tabler:camera" />+ <span class="text-xs font-medium text-ellipsis line-clamp-1">{{[photo.exif.Make, photo.exif.Model].filter(Boolean).join(' ')}}@@ -302,11 +301,10 @@ onMounted(() => {><divv-if="photo.exif.FocalLength"- class="flex items-center gap-0.5"+ class="flex items-center gap-1"><Iconname="streamline:image-accessories-lenses-photos-camera-shutter-picture-photography-pictures-photo-lens"- class="mt-[1px]"/><span class="text-xs font-medium">{{photo.exif.FocalLengthIn35mmFormat@@ -314,24 +312,18 @@ onMounted(() => {</div><divv-if="photo.exif.FNumber"- class="flex items-center gap-0.5"+ class="flex items-center gap-1">- <Icon- name="tabler:aperture"- class="mt-[1px]"- />+ <Icon name="tabler:aperture" /><span class="text-xs font-medium">f/{{ photo.exif.FNumber }}</span></div><divv-if="photo.exif.ExposureTime"- class="flex items-center gap-0.5"+ class="flex items-center gap-1">- <Icon- name="material-symbols:shutter-speed"- class="mt-[1px]"- />+ <Icon name="material-symbols:shutter-speed" /><span class="text-xs font-medium">{{ formatExposureTime(photo.exif.ExposureTime) }}</span>@@ -340,10 +332,7 @@ onMounted(() => {v-if="photo.exif.ISO"class="flex items-center gap-0.5">- <Icon- name="carbon:iso-outline"- class="mt-[1px]"- />+ <Icon name="carbon:iso-outline" /><span class="text-xs font-medium">{{ photo.exif.ISO }}</span></div></div>diff --git a/app/components/masonry/Root.vue b/app/components/masonry/Root.vueindex bee17e6e..40b17cd4 100644--- a/app/components/masonry/Root.vue+++ b/app/components/masonry/Root.vue@@ -197,6 +197,9 @@ onMounted(() => {window.removeEventListener('scroll', handleScroll)})})++const viewerIndex = ref(0)+const isViewerOpen = ref(false)</script><template>@@ -204,35 +207,9 @@ onMounted(() => {<DateRangeIndicator:date-range="dateRange":is-visible="!!dateRange && showFloatingActions"+ :is-mobile="isMobile"/>- <!-- Mobile Date Range Indicator -->- <div- v-if="isMobile && dateRange && showFloatingActions"- class="fixed top-0 right-0 left-0 z-50"- >- <div- class="bg-black/60 backdrop-blur-[70px] border-b border-white/10 px-4 py-3"- >- <span class="text-white text-sm">{{ dateRange }}</span>- </div>- </div>-- <!-- Mobile Floating Action Button -->- <div- v-if="isMobile && showFloatingActions"- class="fixed bottom-6 right-6 z-50"- >- <button- class="w-14 h-14 bg-blue-500 rounded-full shadow-lg flex items-center justify-center"- >- <Icon- name="mdi:plus"- class="w-6 h-6 text-white"- />- </button>- </div>-<!-- Masonry Container --><divclass="p-1 lg:px-0 lg:pb-0"@@ -261,9 +238,21 @@ onMounted(() => {:hasAnimated:first-screen-items="FIRST_SCREEN_ITEMS_COUNT"@visibility-change="handleVisibilityChange"+ @open-viewer="idx => {+ viewerIndex = idx+ isViewerOpen = true+ }"/></div></div>++ <PhotoViewer+ :photos="photos"+ :current-index="viewerIndex"+ :is-open="isViewerOpen"+ @close="isViewerOpen = false"+ @index-change="viewerIndex = $event"+ /></div></template>diff --git a/app/components/photo/GalleryThumbnail.vue b/app/components/photo/GalleryThumbnail.vuenew file mode 100644index 00000000..5d447a51--- /dev/null+++ b/app/components/photo/GalleryThumbnail.vue@@ -0,0 +1,218 @@+<script setup lang="ts">+import { computed, ref, onMounted, onUnmounted, watch, nextTick } from 'vue'+import { motion } from 'motion-v'++interface Props {+ photos: Photo[]+ currentIndex: number+}++const props = defineProps<Props>()+const emit = defineEmits<{+ indexChange: [index: number]+}>()++// DOM 引用+const galleryScrollContainer = ref<HTMLDivElement>()+const containerClientWidth = ref(0)++// 响应式断点+const isSmallScreen = useMediaQuery('(max-width: 768px)')++// 缩略图配置+const THUMBNAIL_CONFIG = {+ size: { sm: 48, lg: 64 },+ gap: { sm: 8, lg: 12 },+ padding: { sm: 12, lg: 16 }+} as const++// 计算当前设备的样式配置+const currentThumbnailSize = computed(() =>+ isSmallScreen.value ? THUMBNAIL_CONFIG.size.sm : THUMBNAIL_CONFIG.size.lg+)++const currentGapSize = computed(() =>+ isSmallScreen.value ? THUMBNAIL_CONFIG.gap.sm : THUMBNAIL_CONFIG.gap.lg+)++const currentPaddingSize = computed(() =>+ isSmallScreen.value ? THUMBNAIL_CONFIG.padding.sm : THUMBNAIL_CONFIG.padding.lg+)++// 处理缩略图列表+const thumbnailList = computed(() => {+ return props.photos.map((photo, index) => ({+ ...photo,+ index,+ isActive: index === props.currentIndex+ }))+})++// 处理缩略图点击+const onThumbnailClick = (index: number) => {+ // 通知父组件索引变化,这会触发 currentIndex 的更新+ // 然后 watch 会自动处理后续的高分辨率图片加载+ emit('indexChange', index)+}++// 容器尺寸管理+const updateContainerSize = () => {+ if (galleryScrollContainer.value) {+ containerClientWidth.value = galleryScrollContainer.value.clientWidth+ }+}++// 滚动到指定的缩略图位置+const scrollToActiveThumbnail = async () => {+ if (!galleryScrollContainer.value) return++ await nextTick()++ const containerWidth = containerClientWidth.value+ const thumbnailSize = currentThumbnailSize.value+ const gapSize = currentGapSize.value++ const thumbnailLeftPosition = props.currentIndex * thumbnailSize + gapSize * props.currentIndex+ const targetScrollLeft = thumbnailLeftPosition - containerWidth / 2 + thumbnailSize / 2++ galleryScrollContainer.value.scrollTo({+ left: targetScrollLeft,+ behavior: 'smooth',+ })+}++// 处理滚轮横向滚动+const onScrollWheel = (event: WheelEvent) => {+ if (!galleryScrollContainer.value) return++ // 阻止默认垂直滚动+ event.preventDefault()++ // 优先使用触控板横向滚动,否则将垂直滚动转为横向+ const deltaAmount = Math.abs(event.deltaX) > Math.abs(event.deltaY)+ ? event.deltaX+ : event.deltaY++ galleryScrollContainer.value.scrollLeft += deltaAmount+}++// 生命周期管理+onMounted(() => {+ updateContainerSize()++ // 观察容器尺寸变化+ if (galleryScrollContainer.value) {+ const sizeObserver = new ResizeObserver(updateContainerSize)+ sizeObserver.observe(galleryScrollContainer.value)++ // 绑定滚轮事件+ galleryScrollContainer.value.addEventListener('wheel', onScrollWheel, { passive: false })++ onUnmounted(() => {+ sizeObserver.disconnect()+ if (galleryScrollContainer.value) {+ galleryScrollContainer.value.removeEventListener('wheel', onScrollWheel)+ }+ })+ }+})++// 响应式监听+watch(() => props.currentIndex, (newIndex, oldIndex) => {+ scrollToActiveThumbnail()+ // 这里不需要再次 emit,因为索引变化是由外部传入的+ // 只需要确保滚动位置正确即可+}, { immediate: true })++watch(isSmallScreen, scrollToActiveThumbnail)+</script>++<template>+ <motion.div+ :initial="{ opacity: 0, y: 100 }"+ :animate="{ opacity: 1, y: 0 }"+ :exit="{ opacity: 0, y: 100 }"+ :transition="{ type: 'spring', duration: 0.4, bounce: 0, delay: 0.1 }"+ class="gallery-thumbnail-container bg-black/20 backdrop-blur-xl border-t border-white/10 shrink-0 z-10"+ >+ <div+ ref="galleryScrollContainer"+ class="gallery-scroll-area overflow-x-auto scrollbar-none flex"+ :style="{+ gap: `${currentGapSize}px`,+ padding: `${currentPaddingSize}px`,+ }"+ >+ <button+ v-for="photo in thumbnailList"+ :key="photo.id"+ type="button"+ class="thumbnail-item relative flex-shrink-0 rounded-lg overflow-hidden border-2 transition-all duration-200 contain-intrinsic-size"+ :class="{+ 'thumbnail-active border-white shadow-lg scale-110': photo.isActive,+ 'thumbnail-inactive border-white/20 hover:border-white/40 grayscale-50 hover:grayscale-0':+ !photo.isActive,+ }"+ :style="{+ width: `${currentThumbnailSize}px`,+ height: `${currentThumbnailSize}px`,+ }"+ @click="onThumbnailClick(photo.index)"+ >+ <Thumbhash+ v-if="photo.thumbnailHash"+ :thumbhash="photo.thumbnailHash"+ class="absolute inset-0 w-full h-full"+ />+ <img+ v-if="photo.thumbnailUrl"+ :src="photo.thumbnailUrl"+ :alt="photo.title || 'Photo thumbnail'"+ class="absolute inset-0 w-full h-full object-cover"+ loading="lazy"+ />+ <div+ v-else-if="!photo.thumbnailHash"+ class="absolute inset-0 w-full h-full bg-gray-700 flex items-center justify-center"+ >+ <Icon+ name="tabler:photo"+ class="w-6 h-6 text-gray-400"+ />+ </div>+ </button>+ </div>+ </motion.div>+</template>++<style scoped>+/* 滚动条隐藏 */+.scrollbar-none {+ scrollbar-width: none; /* Firefox */+ -ms-overflow-style: none; /* IE and Edge */+}++.scrollbar-none::-webkit-scrollbar {+ display: none; /* Webkit browsers */+}++/* 备用滚动条样式(如需要显示时使用) */+.gallery-scroll-area::-webkit-scrollbar {+ height: 6px;+}++.gallery-scroll-area::-webkit-scrollbar-track {+ background: rgba(255, 255, 255, 0.1);+ border-radius: 3px;+}++.gallery-scroll-area::-webkit-scrollbar-thumb {+ background: rgba(255, 255, 255, 0.3);+ border-radius: 3px;+ transition: background-color 0.2s ease;+}++.gallery-scroll-area::-webkit-scrollbar-thumb:hover {+ background: rgba(255, 255, 255, 0.5);+}+</style>diff --git a/app/components/photo/InfoPanel.vue b/app/components/photo/InfoPanel.vuenew file mode 100644index 00000000..9a4a6caf--- /dev/null+++ b/app/components/photo/InfoPanel.vue@@ -0,0 +1,315 @@+<script setup lang="ts">+import { ref, computed } from 'vue'+import { motion, AnimatePresence } from 'motion-v'+import type { NeededExif } from '../../../shared/types/photo'+import { useMediaQuery } from '~/composables/useMediaQuery'++interface Props {+ currentPhoto: Photo+ exifData?: NeededExif | null+ onClose?: () => void+}++const props = defineProps<Props>()++// 格式化曝光时间+const formatExposureTime = (+ exposureTime: string | number | undefined,+): string => {+ if (!exposureTime) return ''++ let seconds: number++ if (typeof exposureTime === 'string') {+ if (exposureTime.includes('/')) {+ const parts = exposureTime.split('/')+ if (parts.length === 2 && parts[0] && parts[1]) {+ const numerator = parseFloat(parts[0])+ const denominator = parseFloat(parts[1])+ if (!isNaN(numerator) && !isNaN(denominator) && denominator !== 0) {+ seconds = numerator / denominator+ } else {+ return exposureTime+ }+ } else {+ return exposureTime+ }+ } else {+ seconds = parseFloat(exposureTime)+ if (isNaN(seconds)) {+ return exposureTime+ }+ }+ } else {+ seconds = exposureTime+ }++ if (seconds >= 1) {+ return `${seconds}s`+ } else {+ const denominator = Math.round(1 / seconds)+ return `1/${denominator}`+ }+}++// 格式化日期+const formatDate = (date: string | undefined): string => {+ if (!date) return ''+ const d = new Date(date)+ return d.toLocaleDateString('zh-CN', {+ year: 'numeric',+ month: 'long',+ day: 'numeric',+ hour: '2-digit',+ minute: '2-digit',+ })+}++// 格式化文件大小+const formatFileSize = (bytes: number | undefined): string => {+ if (!bytes) return ''+ const mb = bytes / 1024 / 1024+ return `${mb.toFixed(2)} MB`+}++// EXIF 数据项+const exifItems = computed(() => {+ if (!props.exifData) return []++ const items = []++ // 基本信息+ if (props.currentPhoto.width && props.currentPhoto.height) {+ items.push({+ label: '尺寸',+ value: `${props.currentPhoto.width} × ${props.currentPhoto.height}`,+ icon: 'tabler:dimensions',+ })+ }++ if (props.currentPhoto.fileSize) {+ items.push({+ label: '文件大小',+ value: formatFileSize(props.currentPhoto.fileSize),+ icon: 'tabler:file',+ })+ }++ if (props.currentPhoto.dateTaken) {+ items.push({+ label: '拍摄时间',+ value: formatDate(props.currentPhoto.dateTaken),+ icon: 'tabler:calendar',+ })+ }++ // 相机信息+ if (props.exifData.Make && props.exifData.Model) {+ items.push({+ label: '相机',+ value: `${props.exifData.Make} ${props.exifData.Model}`,+ icon: 'tabler:camera',+ })+ }++ if (props.exifData.LensMake && props.exifData.LensModel) {+ items.push({+ label: '镜头',+ value: `${props.exifData.LensMake} ${props.exifData.LensModel}`,+ icon: 'tabler:focus-2',+ })+ }++ // 拍摄参数+ if (props.exifData.FocalLengthIn35mmFormat) {+ items.push({+ label: '焦距',+ value: `${props.exifData.FocalLengthIn35mmFormat}`,+ icon: 'tabler:zoom-in',+ })+ }++ if (props.exifData.FNumber) {+ items.push({+ label: '光圈',+ value: `f/${props.exifData.FNumber}`,+ icon: 'tabler:aperture',+ })+ }++ if (props.exifData.ExposureTime) {+ items.push({+ label: '快门速度',+ value: formatExposureTime(props.exifData.ExposureTime),+ icon: 'tabler:clock',+ })+ }++ if (props.exifData.ISO) {+ items.push({+ label: 'ISO',+ value: props.exifData.ISO.toString(),+ icon: 'tabler:sun',+ })+ }++ // GPS 信息+ if (props.exifData.GPSLatitude && props.exifData.GPSLongitude) {+ const lat =+ typeof props.exifData.GPSLatitude === 'number'+ ? props.exifData.GPSLatitude+ : parseFloat(props.exifData.GPSLatitude)+ const lng =+ typeof props.exifData.GPSLongitude === 'number'+ ? props.exifData.GPSLongitude+ : parseFloat(props.exifData.GPSLongitude)+ items.push({+ label: 'GPS 坐标',+ value: `${lat.toFixed(6)}, ${lng.toFixed(6)}`,+ icon: 'tabler:map-pin',+ })+ }++ return items+})++const isMobile = useMediaQuery('(max-width: 768px)')+</script>++<template>+ <motion.div+ :initial="{+ opacity: 0,+ x: isMobile ? 0 : 80,+ y: isMobile ? 20 : 0,+ }"+ :animate="{+ opacity: 1,+ x: 0,+ y: 0,+ }"+ :exit="{+ opacity: 0,+ x: isMobile ? 0 : 80,+ y: isMobile ? 20 : 0,+ }"+ :transition="{ type: 'spring', duration: 0.4, bounce: 0, delay: 0.1 }"+ class="bg-black/30 backdrop-blur-xl border-white/10"+ :class="{+ 'fixed inset-x-2 bottom-2 max-h-[60vh] border rounded-xl z-50': isMobile,+ 'w-80 border-l': !isMobile,+ }"+ >+ <!-- 移动端头部 -->+ <div+ v-if="isMobile && onClose"+ class="flex items-center justify-between p-4 border-b border-white/10"+ >+ <h3 class="text-lg font-medium text-white">照片信息</h3>+ <button+ type="button"+ class="p-1 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition-colors"+ @click="onClose"+ >+ <Icon+ name="tabler:x"+ class="w-5 h-5"+ />+ </button>+ </div>++ <!-- 内容区域 -->+ <div class="p-4 overflow-y-auto max-h-full">+ <!-- 照片标题 -->+ <div+ v-if="currentPhoto.title"+ class="mb-4"+ >+ <h3+ class="text-lg font-medium text-white mb-1 text-ellipsis line-clamp-1"+ >+ {{ currentPhoto.title }}+ </h3>+ </div>++ <!-- 照片描述 -->+ <div+ v-if="currentPhoto.description"+ class="mb-4 text-sm text-white/80"+ >+ {{ currentPhoto.description }}+ </div>++ <!-- EXIF 信息 -->+ <div+ v-if="exifItems.length > 0"+ class="space-y-3"+ >+ <h4 class="text-sm font-medium text-white/90 uppercase tracking-wide">+ 照片信息+ </h4>++ <div class="space-y-2">+ <div+ v-for="item in exifItems"+ :key="item.label"+ class="flex items-center gap-3 text-sm"+ >+ <Icon+ :name="item.icon"+ class="w-4 h-4 text-white/60 flex-shrink-0"+ />+ <div class="flex-1 min-w-0">+ <div class="text-white/60">{{ item.label }}</div>+ <div class="text-white font-medium truncate">+ {{ item.value }}+ </div>+ </div>+ </div>+ </div>+ </div>++ <!-- 标签 -->+ <div+ v-if="currentPhoto.tags && currentPhoto.tags.length > 0"+ class="mt-4"+ >+ <h4+ class="text-sm font-medium text-white/90 uppercase tracking-wide mb-2"+ >+ 标签+ </h4>+ <div class="flex flex-wrap gap-1">+ <span+ v-for="tag in currentPhoto.tags"+ :key="tag"+ class="px-2 py-1 text-xs bg-white/10 text-white rounded-full"+ >+ {{ tag }}+ </span>+ </div>+ </div>+ </div>+ </motion.div>+</template>++<style scoped>+/* 自定义滚动条样式 */+.overflow-y-auto::-webkit-scrollbar {+ width: 4px;+}++.overflow-y-auto::-webkit-scrollbar-track {+ background: rgba(255, 255, 255, 0.1);+ border-radius: 2px;+}++.overflow-y-auto::-webkit-scrollbar-thumb {+ background: rgba(255, 255, 255, 0.3);+ border-radius: 2px;+}++.overflow-y-auto::-webkit-scrollbar-thumb:hover {+ background: rgba(255, 255, 255, 0.5);+}+</style>diff --git a/app/components/photo/LoadingIndicator.vue b/app/components/photo/LoadingIndicator.vuenew file mode 100644index 00000000..e15251a8--- /dev/null+++ b/app/components/photo/LoadingIndicator.vue@@ -0,0 +1,163 @@+<script setup lang="ts">+import { AnimatePresence, motion } from 'motion-v'++export interface LoadingState {+ isVisible: boolean+ isConverting: boolean+ isHeic: boolean+ progress: number+ bytesLoaded: number+ bytesTotal: number+ codec?: string++ isWebGLLoading?: boolean+ webglMessage?: string+ webglQuality?: string++ isError?: boolean+ message?: string+ errorMessage?: string+}++const defaultLoadingState: LoadingState = {+ isVisible: false,+ isConverting: false,+ isHeic: false,+ progress: 0,+ bytesLoaded: 0,+ bytesTotal: 0,+ codec: undefined,++ isWebGLLoading: false,+ webglMessage: undefined,+ webglQuality: 'unknown',++ isError: false,+ message: undefined,+ errorMessage: undefined,+}++const loadingState = ref<LoadingState>(defaultLoadingState)++export interface LoadingIndicatorRef {+ updateLoadingState: (state: Partial<LoadingState>) => void+ resetLoadingState: () => void+}++const updateLoadingState = (state: Partial<LoadingState>): void => {+ loadingState.value =+ state.isVisible === false+ ? defaultLoadingState+ : { ...loadingState.value, ...state }+}++const resetLoadingState = (): void => {+ loadingState.value = defaultLoadingState+}++defineExpose({+ updateLoadingState,+ resetLoadingState,+} satisfies LoadingIndicatorRef)++const loadingVariants = {+ initial: {+ opacity: 0,+ x: 20,+ y: 10,+ scale: 0.9,+ },+ animate: {+ opacity: 1,+ x: 0,+ y: 0,+ scale: 1,+ },+}+</script>++<template>+ <AnimatePresence>+ <motion.div+ v-show="loadingState.isVisible"+ key="loading-indicator"+ class="absolute bottom-4 right-4 z-40 pointer-events-none bg-black/40 backdrop-blur-3xl rounded-xl border border-white/10 p-3 shadow-2xl"+ :initial="loadingVariants.initial"+ :animate="loadingVariants.animate"+ :exit="loadingVariants.initial"+ :transition="{+ type: 'spring',+ duration: 0.3,+ bounce: 0,+ }"+ >+ <div class="flex items-start gap-2 text-white">+ <Icon+ name="tabler:loader-2"+ class="text-lg animate-spin"+ />+ <div class="flex flex-col min-w-0 gap-0.5">+ <template v-if="loadingState.isError">+ <p class="text-xs font-medium text-red-400">+ {{ loadingState.errorMessage || '图片加载失败' }}+ </p>+ <p class="text-xs text-white/70">正在加载图片</p>+ </template>++ <template v-else-if="loadingState.isConverting">+ <p class="text-xs font-medium text-white tabular-nums">+ {{ loadingState.message || '正在转换中...' }}+ </p>+ </template>++ <template v-else-if="loadingState.isWebGLLoading">+ <div class="flex items-center gap-2">+ <p class="text-xs font-medium text-white">+ {{ loadingState.webglMessage || '正在加载 WebGL...' }}+ </p>+ <span+ v-if="loadingState.webglQuality !== 'unknown'"+ class="text-xs tabular-nums"+ :style="{+ color:+ loadingState.webglQuality === 'high'+ ? '#4ade80'+ : loadingState.webglQuality === 'medium'+ ? '#fbbf24'+ : loadingState.webglQuality === 'low'+ ? '#f87171'+ : '#94a3b8',+ }"+ >+ {{ loadingState.webglQuality }}+ </span>+ </div>+ <p class="text-xs text-white/70">正在构建纹理</p>+ </template>++ <template v-else>+ <div class="flex items-center gap-2">+ <p class="text-xs font-medium text-white">+ {{+ loadingState.isHeic ? 'HEIC 图片加载中...' : '正在加载图片'+ }}+ </p>+ <span class="text-xs text-white/60 tabular-nums">+ {{ Math.round(loadingState.progress) }}%+ </span>+ </div>+ <p+ v-if="loadingState.bytesTotal > 0"+ class="text-xs text-white/70 tabular-nums"+ >+ {{ (loadingState.bytesLoaded / 1024 / 1024).toFixed(1) }}MB /+ {{ (loadingState.bytesTotal / 1024 / 1024).toFixed(1) }}MB+ </p>+ </template>+ </div>+ </div>+ </motion.div>+ </AnimatePresence>+</template>++<style scoped></style>diff --git a/app/components/photo/ProgressiveImage.vue b/app/components/photo/ProgressiveImage.vuenew file mode 100644index 00000000..ce0d755e--- /dev/null+++ b/app/components/photo/ProgressiveImage.vue@@ -0,0 +1,172 @@+<script setup lang="ts">+import { WebGLImageViewer } from '@chronoframe/webgl-image'+import type { LoadingIndicatorRef } from './LoadingIndicator.vue'++interface Props {+ src: string+ thumbnailSrc?: string+ alt?: string+ width?: number+ height?: number+ className?: string+ enablePan?: boolean+ enableZoom?: boolean+ isCurrentImage?: boolean+ loadingIndicatorRef: LoadingIndicatorRef | null+ onProgress?: (progress: number) => void+ onError?: () => void+ onZoomChange?: (isZoomed: boolean) => void+ onBlobSrcChange?: (blobSrc: string | null) => void+ isLivePhoto?: boolean+ livePhotoVideoUrl?: string+ isHDR?: boolean+}++const props = withDefaults(defineProps<Props>(), {+ enablePan: true,+ enableZoom: true,+ isCurrentImage: true,+})++const imageRef = ref<HTMLImageElement>()+const containerRef = ref<HTMLDivElement>()++// state+const highResLoaded = ref(false)+const highResRendered = ref(false)+const hasError = ref(false)+const currentSrc = ref<string | null>()++// 使用 WebGLImageViewer 的引用+const webglViewerRef = ref()++const showThumbnail = computed(() => {+ return props.thumbnailSrc && (!highResRendered.value || hasError.value)+})++const showWebGLViewer = computed(() => {+ return (+ highResLoaded.value &&+ currentSrc.value &&+ props.isCurrentImage &&+ !hasError.value+ )+})++const loadImage = () => {+ useImageLoader(+ props.src,+ props.isCurrentImage,+ highResLoaded.value,+ hasError.value,+ props.loadingIndicatorRef,+ props.onProgress,+ props.onError,+ (src) => (currentSrc.value = src),+ (loaded) => (highResLoaded.value = loaded),+ (error) => (hasError.value = error),+ (rendered) => (highResRendered.value = rendered),+ )+}++// 监听 isCurrentImage 的变化,当变为 true 时触发图片加载+watch(+ () => props.isCurrentImage,+ (isCurrent, wasCurrent) => {+ if (isCurrent && !wasCurrent && !highResLoaded.value && !hasError.value) {+ // 当图片变为当前图片且尚未加载高分辨率图片时,触发加载+ loadImage()+ }+ },+ { immediate: false },+)++// 监听 src 的变化,当源地址改变时重置状态并重新加载+watch(+ () => props.src,+ (newSrc, oldSrc) => {+ if (newSrc !== oldSrc) {+ // 重置状态+ highResLoaded.value = false+ highResRendered.value = false+ hasError.value = false+ currentSrc.value = null++ // 如果是当前图片,立即开始加载+ if (props.isCurrentImage) {+ loadImage()+ }+ }+ },+ { immediate: false },+)++// 初始加载+loadImage()++const handleWebGLStateChange = useWebGLWorkState(props.loadingIndicatorRef)++// 处理缩放状态变化+const handleZoomChange = (originalScale: number, relativeScale: number) => {+ const isZoomed = relativeScale > 1.1 // 认为缩放超过 1.1 倍算作缩放状态+ if (props.onZoomChange) {+ props.onZoomChange(isZoomed)+ }+}+</script>++<template>+ <div+ ref="containerRef"+ class="relative w-full h-full flex items-center justify-center"+ >+ <!-- 缩略图 (加载时显示) -->+ <img+ v-if="showThumbnail"+ :src="thumbnailSrc"+ :alt="alt"+ class="absolute inset-0 w-full h-full object-contain"+ />++ <!-- WebGL 图片查看器 -->+ <WebGLImageViewer+ v-if="showWebGLViewer"+ ref="webglViewerRef"+ :src="currentSrc!"+ :class="className"+ class="w-full h-full"+ :width="width"+ :height="height"+ :center-on-init="true"+ :limit-to-bounds="true"+ :smooth="true"+ :min-scale="1"+ :max-scale="5"+ :wheel="{ step: 0.2, wheelDisabled: false, touchPadDisabled: false }"+ :pinch="{ step: 0.2, disabled: !enableZoom }"+ :double-click="{+ step: 0.7,+ disabled: !enableZoom,+ mode: 'toggle',+ animationTime: 300,+ }"+ :panning="{ disabled: !enablePan, velocityDisabled: false }"+ @zoom-change="handleZoomChange"+ @loading-state-change="handleWebGLStateChange"+ />++ <!-- 错误状态 -->+ <div+ v-if="hasError"+ class="flex flex-col items-center justify-center text-white/70 gap-2"+ >+ <Icon+ name="tabler:photo-off"+ class="w-12 h-12"+ />+ <p class="text-sm">图片加载失败</p>+ </div>+ </div>+</template>++<style scoped></style>diff --git a/app/components/photo/Viewer.vue b/app/components/photo/Viewer.vuenew file mode 100644index 00000000..0d7da130--- /dev/null+++ b/app/components/photo/Viewer.vue@@ -0,0 +1,383 @@+<script setup lang="ts">+import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'+import { motion, AnimatePresence } from 'motion-v'+import { Swiper, SwiperSlide } from 'swiper/vue'+import { Navigation, Keyboard, Virtual } from 'swiper/modules'+import type { Swiper as SwiperType } from 'swiper'++// Import Swiper styles+import 'swiper/css'+import 'swiper/css/navigation'++import LoadingIndicator from './LoadingIndicator.vue'+import ProgressiveImage from './ProgressiveImage.vue'+import GalleryThumbnail from './GalleryThumbnail.vue'+import InfoPanel from './InfoPanel.vue'+import type { LoadingIndicatorRef } from './LoadingIndicator.vue'+import { useMediaQuery } from '~/composables/useMediaQuery'++interface Props {+ photos: Photo[]+ currentIndex: number+ isOpen: boolean+}++const props = defineProps<Props>()++const emit = defineEmits<{+ close: []+ indexChange: [index: number]+}>()++// Refs+const containerRef = ref<HTMLDivElement>()+const swiperRef = ref<SwiperType>()+const loadingIndicatorRef = ref<LoadingIndicatorRef>()++// State+const isImageZoomed = ref(false)+const showExifPanel = ref(false)+const currentBlobSrc = ref<string | null>(null)++// Computed+const currentPhoto = computed(() => props.photos[props.currentIndex])+const isMobile = useMediaQuery('(max-width: 768px)')++// 当 PhotoViewer 关闭时重置状态+watch(+ () => props.isOpen,+ (isOpen) => {+ if (!isOpen) {+ isImageZoomed.value = false+ showExifPanel.value = false+ currentBlobSrc.value = null+ }+ },+)++// 同步 Swiper 的索引+watch(+ () => props.currentIndex,+ (newIndex) => {+ if (swiperRef.value && swiperRef.value.activeIndex !== newIndex) {+ swiperRef.value.slideTo(newIndex, 300)+ }+ // 切换图片时重置缩放状态+ isImageZoomed.value = false+ },+)++// 当图片缩放状态改变时,控制 Swiper 的触摸行为+watch(isImageZoomed, (isZoomed) => {+ if (swiperRef.value) {+ swiperRef.value.allowTouchMove = !isZoomed+ }+})++// Navigation methods+const handlePrevious = () => {+ if (props.currentIndex > 0) {+ emit('indexChange', props.currentIndex - 1)+ swiperRef.value?.slidePrev()+ }+}++const handleNext = () => {+ if (props.currentIndex < props.photos.length - 1) {+ emit('indexChange', props.currentIndex + 1)+ swiperRef.value?.slideNext()+ }+}++// Handle Swiper events+const handleSwiperInit = (swiper: SwiperType) => {+ swiperRef.value = swiper+ swiper.allowTouchMove = !isImageZoomed.value+}++const handleSlideChange = (swiper: SwiperType) => {+ emit('indexChange', swiper.activeIndex)+}++// Handle image events+const handleZoomChange = (isZoomed: boolean) => {+ isImageZoomed.value = isZoomed+}++const handleBlobSrcChange = (blobSrc: string | null) => {+ currentBlobSrc.value = blobSrc+}++// Keyboard navigation+const handleKeyDown = (event: KeyboardEvent) => {+ if (!props.isOpen) return++ switch (event.key) {+ case 'ArrowLeft':+ event.preventDefault()+ handlePrevious()+ break+ case 'ArrowRight':+ event.preventDefault()+ handleNext()+ break+ case 'Escape':+ event.preventDefault()+ emit('close')+ break+ case 'i':+ case 'I':+ event.preventDefault()+ showExifPanel.value = !showExifPanel.value+ break+ }+}++onMounted(() => {+ document.addEventListener('keypress', handleKeyDown)+})++onUnmounted(() => {+ document.removeEventListener('keypress', handleKeyDown)+})++// Swiper modules+const swiperModules = [Navigation, Keyboard, Virtual]+</script>++<template>+ <Teleport to="body">+ <!-- 背景层 -->+ <AnimatePresence>+ <motion.div+ v-if="isOpen"+ :initial="{ opacity: 0 }"+ :animate="{ opacity: 1 }"+ :exit="{ opacity: 0 }"+ :transition="{ duration: 0.3 }"+ class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50"+ @click="emit('close')"+ />+ </AnimatePresence>++ <!-- 交叉溶解的 Thumbhash 背景 -->+ <AnimatePresence mode="sync">+ <motion.div+ v-if="isOpen && currentPhoto?.thumbnailHash"+ :key="currentPhoto.id"+ :initial="{ opacity: 0 }"+ :animate="{ opacity: 1 }"+ :exit="{ opacity: 0 }"+ :transition="{ duration: 0.3 }"+ class="fixed inset-0 z-40"+ >+ <Thumbhash+ :thumbhash="currentPhoto.thumbnailHash"+ class="w-full h-full scale-110"+ />+ </motion.div>+ </AnimatePresence>++ <!-- 主内容区域 -->+ <AnimatePresence>+ <motion.div+ v-if="isOpen"+ :initial="{ opacity: 0 }"+ :animate="{ opacity: 1 }"+ :exit="{ opacity: 0 }"+ :transition="{ duration: 0.3 }"+ ref="containerRef"+ class="fixed inset-0 z-50 flex items-center justify-center"+ :style="{ touchAction: isMobile ? 'manipulation' : 'none' }"+ @click.self="emit('close')"+ >+ <div+ class="flex w-full h-full"+ :class="isMobile ? 'flex-col' : 'flex-row'"+ >+ <!-- 图片显示区域 -->+ <div class="z-10 flex min-h-0 min-w-0 flex-1 flex-col">+ <div class="group relative flex min-h-0 min-w-0 flex-1">+ <!-- 顶部工具栏 -->+ <motion.div+ :initial="{ opacity: 0 }"+ :animate="{ opacity: 1 }"+ :exit="{ opacity: 0 }"+ :transition="{ duration: 0.3 }"+ class="pointer-events-none absolute z-30 flex items-center justify-between"+ :class="+ isMobile ? 'top-2 right-2 left-2' : 'top-4 right-4 left-4'+ "+ >+ <!-- 左侧工具按钮 -->+ <div class="flex items-center gap-2">+ <!-- 信息按钮 - 在移动设备上显示 -->+ <button+ v-if="isMobile"+ type="button"+ class="pointer-events-auto flex size-8 items-center justify-center rounded-full text-white backdrop-blur-xl duration-200"+ :class="+ showExifPanel+ ? 'bg-white/30'+ : 'bg-black/30 hover:bg-black/40'+ "+ @click="showExifPanel = !showExifPanel"+ >+ <Icon name="tabler:info-circle" />+ </button>+ </div>++ <!-- 右侧按钮组 -->+ <div class="flex items-center gap-2">+ <!-- 关闭按钮 -->+ <button+ type="button"+ class="pointer-events-auto flex size-8 items-center justify-center rounded-full text-white backdrop-blur-xl duration-200 bg-black/30 hover:bg-black/40"+ @click="emit('close')"+ >+ <Icon name="tabler:x" />+ </button>+ </div>+ </motion.div>++ <!-- 加载指示器 -->+ <LoadingIndicator ref="loadingIndicatorRef" />++ <!-- Swiper 容器 -->+ <Swiper+ :modules="swiperModules"+ :space-between="0"+ :slides-per-view="1"+ :initial-slide="currentIndex"+ :virtual="true"+ :keyboard="{+ enabled: true,+ onlyInViewport: true,+ }"+ class="h-full w-full"+ :style="{ touchAction: isMobile ? 'pan-x' : 'pan-y' }"+ @swiper="handleSwiperInit"+ @slide-change="handleSlideChange"+ >+ <SwiperSlide+ v-for="(photo, index) in photos"+ :key="photo.id"+ :virtual-index="index"+ class="flex items-center justify-center"+ >+ <motion.div+ :initial="{ opacity: 0.5, scale: 0.95 }"+ :animate="{ opacity: 1, scale: 1 }"+ :exit="{ opacity: 0, scale: 0.95 }"+ :transition="{ type: 'spring', duration: 0.4, bounce: 0 }"+ class="relative flex h-full w-full items-center justify-center"+ >+ <ProgressiveImage+ class="h-full w-full object-contain"+ :loading-indicator-ref="loadingIndicatorRef || null"+ :is-current-image="index === currentIndex"+ :src="photo.originalUrl!"+ :thumbnail-src="photo.thumbnailUrl!"+ :alt="photo.title || ''"+ :width="+ index === currentIndex+ ? (currentPhoto?.width ?? undefined)+ : undefined+ "+ :height="+ index === currentIndex+ ? (currentPhoto?.height ?? undefined)+ : undefined+ "+ :enable-pan="+ index === currentIndex+ ? !isMobile || isImageZoomed+ : true+ "+ :enable-zoom="true"+ :on-zoom-change="+ index === currentIndex ? handleZoomChange : undefined+ "+ :on-blob-src-change="+ index === currentIndex ? handleBlobSrcChange : undefined+ "+ />+ </motion.div>+ </SwiperSlide>+ </Swiper>++ <!-- 自定义导航按钮 (桌面端) -->+ <template v-if="!isMobile">+ <button+ v-if="currentIndex > 0"+ type="button"+ class="absolute top-1/2 left-4 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full text-white opacity-0 backdrop-blur-sm duration-200 group-hover:opacity-100 bg-black/30 hover:bg-black/40"+ @click="handlePrevious"+ >+ <Icon+ name="tabler:chevron-left"+ class="text-xl"+ />+ </button>++ <button+ v-if="currentIndex < photos.length - 1"+ type="button"+ class="absolute top-1/2 right-4 z-20 flex size-8 -translate-y-1/2 items-center justify-center rounded-full text-white opacity-0 backdrop-blur-sm duration-200 group-hover:opacity-100 bg-black/30 hover:bg-black/40"+ @click="handleNext"+ >+ <Icon+ name="tabler:chevron-right"+ class="text-xl"+ />+ </button>+ </template>+ </div>++ <!-- 缩略图导航 -->+ <Suspense>+ <GalleryThumbnail+ :current-index="currentIndex"+ :photos="photos"+ @index-change="(index: number) => emit('indexChange', index)"+ />+ </Suspense>+ </div>++ <!-- EXIF 面板 - 在桌面端始终显示,在移动端根据状态显示 -->+ <Suspense>+ <AnimatePresence v-if="isMobile">+ <InfoPanel+ v-if="showExifPanel && currentPhoto"+ :current-photo="currentPhoto"+ :exif-data="currentPhoto?.exif"+ :on-close="() => (showExifPanel = false)"+ />+ </AnimatePresence>+ <InfoPanel+ v-else-if="currentPhoto"+ :current-photo="currentPhoto"+ :exif-data="currentPhoto?.exif"+ />+ </Suspense>+ </div>+ </motion.div>+ </AnimatePresence>+ </Teleport>+</template>++<style scoped>+/* Swiper 样式调整 */+.swiper {+ width: 100%;+ height: 100%;+}++.swiper-slide {+ text-align: center;+ font-size: 18px;+ display: flex;+ justify-content: center;+ align-items: center;+}+</style>diff --git a/app/composables/useImageLoader.ts b/app/composables/useImageLoader.tsnew file mode 100644index 00000000..86a4263b--- /dev/null+++ b/app/composables/useImageLoader.ts@@ -0,0 +1,58 @@+import type { LoadingIndicatorRef } from "~/components/photo/LoadingIndicator.vue";+import { ImageLoaderManager } from "~/libs/image-loader-manager";++export const useImageLoader = (+ src: string,+ isCurrentImage: boolean,+ highResLoaded: boolean,+ error: boolean,+ loadingIndicatorRef?: LoadingIndicatorRef | null,+ onProgress?: (progress: number) => void,+ onError?: () => void,+ updateBlobSrc?: (blobSrc: string | null) => void,+ updateHighResLoaded?: (highResLoaded: boolean) => void,+ updateError?: (error: boolean) => void,+ updateHighResImageRendered?: (isRendered: boolean) => void+) => {+ if (highResLoaded || !isCurrentImage || error) return++ const loaderManager = new ImageLoaderManager()++ const cleanup = () => {+ updateBlobSrc?.(null)+ updateHighResImageRendered?.(false)+ updateHighResLoaded?.(false)+ updateError?.(false)+ }++ const loadImage = async () => {+ try {+ const loadResult = await loaderManager.loadImage(src, {+ onProgress,+ onError,+ onUpdateLoadingState: (state) => {+ loadingIndicatorRef?.updateLoadingState(state)+ },+ })++ updateBlobSrc?.(loadResult.blobSrc)+ updateHighResLoaded?.(true)+ } catch (err) {+ updateError?.(true)+ loadingIndicatorRef?.updateLoadingState({+ isVisible: true,+ isError: true,+ message: "载入图片失败"+ })+ }+ }++ onUnmounted(() => {+ cleanup()+ })++ cleanup()+ loadImage()++ return loaderManager+}\ No newline at end of filediff --git a/app/composables/useMediaQuery.ts b/app/composables/useMediaQuery.tsnew file mode 100644index 00000000..b50bed4d--- /dev/null+++ b/app/composables/useMediaQuery.ts@@ -0,0 +1,45 @@+import { ref, onMounted, onUnmounted } from 'vue'++/**+ * 媒体查询 composable+ * @param query CSS 媒体查询字符串+ * @returns 是否匹配媒体查询的响应式引用+ */+export function useMediaQuery(query: string) {+ const matches = ref(false)+ let mediaQuery: MediaQueryList | null = null++ const updateMatches = () => {+ if (mediaQuery) {+ matches.value = mediaQuery.matches+ }+ }++ onMounted(() => {+ if (typeof window !== 'undefined') {+ mediaQuery = window.matchMedia(query)+ matches.value = mediaQuery.matches++ // 监听媒体查询变化+ if (mediaQuery.addEventListener) {+ mediaQuery.addEventListener('change', updateMatches)+ } else {+ // 兼容旧版浏览器+ mediaQuery.addListener(updateMatches)+ }+ }+ })++ onUnmounted(() => {+ if (mediaQuery) {+ if (mediaQuery.removeEventListener) {+ mediaQuery.removeEventListener('change', updateMatches)+ } else {+ // 兼容旧版浏览器+ mediaQuery.removeListener(updateMatches)+ }+ }+ })++ return matches+}diff --git a/app/composables/useWebGLWorkState.ts b/app/composables/useWebGLWorkState.tsnew file mode 100644index 00000000..cf2e2b7e--- /dev/null+++ b/app/composables/useWebGLWorkState.ts@@ -0,0 +1,27 @@+import type { LoadingIndicatorRef } from '~/components/photo/LoadingIndicator.vue'+import { LoadingState } from '@chronoframe/webgl-image'++export const useWebGLWorkState = (+ loadingIndicatorRef: LoadingIndicatorRef | null,+) => {+ return (+ isLoading: boolean,+ state?: LoadingState,+ quality?: 'high' | 'medium' | 'low' | 'unknown',+ ) => {+ let message = ''++ if (state === LoadingState.TEXTURE_LOADING) {+ message = '正在创建纹理'+ } else if (state === LoadingState.IMAGE_LOADING) {+ message = '正在加载图像'+ }++ loadingIndicatorRef?.updateLoadingState({+ isVisible: isLoading,+ isWebGLLoading: isLoading,+ webglMessage: message,+ webglQuality: quality,+ })+ }+}diff --git a/app/layouts/dashboard.vue b/app/layouts/dashboard.vueindex ac4d2f7e..50abf6bf 100644--- a/app/layouts/dashboard.vue+++ b/app/layouts/dashboard.vue@@ -16,18 +16,32 @@ const items = ref<NavigationMenuItem[]>([label: 'Workers',icon: 'tabler:automatic-gearbox',to: '/dashboard/workers',- }+ },])++const { loggedIn, user } = useUserSession()++const handleLogin = () => {+ window.location.href = '/api/auth/github'+}</script><template>- <header class="w-full px-4 border-b border-default flex items-center gap-4">+ <header+ v-if="loggedIn"+ class="w-full px-4 border-b border-default flex items-center gap-4"+ ><div class="flex items-center gap-2"><Iconname="tabler:photo-circle"class="size-6 text-primary"/>- <h1 class="text-lg font-medium text-nowrap">Timothy Yin's Photos</h1>+ <NuxtLink+ to="/"+ class="text-lg font-medium text-nowrap"+ >+ Timothy Yin's Photos+ </NuxtLink></div><UNavigationMenuvariant="pill"@@ -38,9 +52,26 @@ const items = ref<NavigationMenuItem[]>([class="w-full"/></header>- <main>+ <main v-if="loggedIn && user?.isAdmin"><NuxtPage /></main>+ <div+ v-else+ class="h-svh flex flex-col gap-4 items-center justify-center"+ >+ <Icon+ name="tabler:alert-triangle"+ class="size-12 text-primary"+ />+ <p class="text-gray-500">+ {{+ !user?.isAdmin+ ? 'Please login to view dashboard'+ : 'Sorry, you do not have access to this page.'+ }}+ </p>+ <UButton @click="handleLogin">Login with GitHub</UButton>+ </div></template><style scoped></style>diff --git a/app/libs/image-loader-manager.ts b/app/libs/image-loader-manager.tsnew file mode 100644index 00000000..dfb6d8a6--- /dev/null+++ b/app/libs/image-loader-manager.ts@@ -0,0 +1,181 @@+import { fileTypeFromBlob } from 'file-type'+import { LRUCache } from './lru'++export interface ImageLoaderState {+ isVisible: boolean+ isHeic?: boolean+ progress?: number+ bytesLoaded?: number+ bytesTotal?: number+ isConverting?: boolean+ message?: string+ codec?: string+}++export interface ImageLoaderCallbacks {+ onProgress?: (progress: number) => void+ onError?: () => void+ onUpdateLoadingState?: (state: Partial<ImageLoaderState>) => void+}++export interface ImageLoaderResult {+ blobSrc: string+ resultUrl?: string+}++export interface ImageLoaderCacheResult {+ blobSrc: string+ originalSize: number+ format: string+}++const normalImageCache: LRUCache<string, ImageLoaderCacheResult> = new LRUCache<+ string,+ ImageLoaderCacheResult+>(10, (v, k, reason) => {+ try {+ URL.revokeObjectURL(v.blobSrc)+ console.log(`已释放 Blob URL - ${k} (${reason})`)+ } catch (err) {+ console.warn(`Blob URL 释放失败 (${k}):`, err)+ }+})++export class ImageLoaderManager {+ private lastXHR: XMLHttpRequest | null = null+ private timer: NodeJS.Timeout | null = null++ private async isValidImageBlob(blob: Blob): Promise<boolean> {+ if (blob.size === 0) return false++ try {+ const fileType = await fileTypeFromBlob(blob)++ if (!fileType) return false+ if (!fileType.mime.startsWith('image/')) return false++ return true+ } catch (err) {+ return false+ }+ }++ async loadImage(+ src: string,+ callbacks: ImageLoaderCallbacks = {},+ ): Promise<ImageLoaderResult> {+ const { onProgress, onError, onUpdateLoadingState } = callbacks++ onUpdateLoadingState?.({+ isVisible: true,+ })++ return new Promise((resolve, reject) => {+ this.timer = setTimeout(async () => {+ const xhr = new XMLHttpRequest()+ xhr.open('GET', src)+ xhr.responseType = 'blob'++ xhr.onload = async () => {+ if (xhr.status === 200) {+ try {+ const blob = xhr.response as Blob+ if (!(await this.isValidImageBlob(blob))) {+ onError?.()+ onUpdateLoadingState?.({+ isVisible: false,+ })+ return+ }++ const processResult = await this.processNormalImage(+ blob,+ src,+ callbacks,+ )+ resolve(processResult)+ } catch (err) {+ onError?.()+ onUpdateLoadingState?.({+ isVisible: false,+ })+ reject(err)+ }+ } else {+ onError?.()+ onUpdateLoadingState?.({+ isVisible: false,+ })+ reject(new Error(`Failed to load image: ${xhr.status}`))+ }+ }++ xhr.onprogress = (event) => {+ if (event.lengthComputable) {+ const progress = (event.loaded / event.total) * 100+ onProgress?.(progress)+ onUpdateLoadingState?.({+ progress,+ bytesLoaded: event.loaded,+ bytesTotal: event.total,+ })+ }+ }++ xhr.onerror = () => {+ onError?.()+ onUpdateLoadingState?.({+ isVisible: false,+ })+ reject(new Error(`Failed to load image`))+ }++ xhr.send()++ this.lastXHR = xhr+ }, 300)+ })+ }++ async processNormalImage(+ blob: Blob,+ originalUrl: string,+ callbacks: ImageLoaderCallbacks,+ ) {+ const { onUpdateLoadingState } = callbacks+ const cacheKey = originalUrl+ const cacheResult = normalImageCache.get(cacheKey)+ if (cacheResult) {+ onUpdateLoadingState?.({+ isVisible: false,+ })+ return {+ blobSrc: cacheResult.blobSrc,+ }+ }+ const url = URL.createObjectURL(blob)+ const result: ImageLoaderCacheResult = {+ blobSrc: originalUrl,+ originalSize: blob.size,+ format: blob.type,+ }+ normalImageCache.set(cacheKey, result)+ onUpdateLoadingState?.({+ isVisible: false,+ })+ return {+ blobSrc: originalUrl,+ }+ }++ cleanup() {+ if (this.lastXHR) {+ this.lastXHR.abort()+ this.lastXHR = null+ }+ if (this.timer) {+ clearTimeout(this.timer)+ this.timer = null+ }+ }+}diff --git a/app/libs/lru.ts b/app/libs/lru.tsnew file mode 100644index 00000000..d9441206--- /dev/null+++ b/app/libs/lru.ts@@ -0,0 +1,172 @@+/**+ * 最近最少使用 (LRU) 缓存实现+ * 提供高效的缓存管理,支持自动淘汰和资源清理+ */++type CleanupHandler<K, V> = (item: V, key: K, context: string) => void++export class LRUCache<K, V> {+ private readonly capacity: number+ private readonly storage = new Map<K, V>()+ private readonly onEvict?: CleanupHandler<K, V>++ constructor(+ maxSize = 10,+ cleanupFn?: CleanupHandler<K, V>,+ ) {+ this.capacity = Math.max(1, maxSize)+ this.onEvict = cleanupFn+ }++ get(key: K): V | undefined {+ const item = this.storage.get(key)+ if (item === undefined) {+ return undefined+ }++ // 重新插入以更新访问顺序+ this.storage.delete(key)+ this.storage.set(key, item)+ return item+ }++ set(key: K, value: V): void {+ // 处理已存在的键+ if (this.storage.has(key)) {+ const existingValue = this.storage.get(key)!+ this.executeCleanup(existingValue, key, `更新缓存项: ${String(key)}`)+ this.storage.delete(key)+ } else {+ // 检查容量限制+ this.ensureCapacity()+ }++ this.storage.set(key, value)+ this.logCacheOperation('添加', key)+ }++ delete(key: K): boolean {+ const item = this.storage.get(key)+ if (item === undefined) {+ return false+ }++ this.executeCleanup(item, key, `手动删除: ${String(key)}`)+ return this.storage.delete(key)+ }++ has(key: K): boolean {+ return this.storage.has(key)+ }++ clear(): void {+ const itemCount = this.storage.size++ for (const [key, item] of this.storage.entries()) {+ this.executeCleanup(item, key, `清空缓存: ${String(key)}`)+ }++ this.storage.clear()+ console.info(`缓存已清空,共释放 ${itemCount} 个项目`)+ }++ size(): number {+ return this.storage.size+ }++ getStats(): { size: number; maxSize: number; keys: K[] } {+ return {+ size: this.storage.size,+ maxSize: this.capacity,+ keys: [...this.storage.keys()],+ }+ }++ values(): IterableIterator<V> {+ return this.storage.values()+ }++ entries(): IterableIterator<[K, V]> {+ return this.storage.entries()+ }++ /**+ * 确保缓存容量不超限+ */+ private ensureCapacity(): void {+ while (this.storage.size >= this.capacity) {+ const oldestKey = this.storage.keys().next().value+ if (oldestKey !== undefined) {+ const oldestValue = this.storage.get(oldestKey)!+ this.executeCleanup(oldestValue, oldestKey, `容量限制淘汰: ${String(oldestKey)}`)+ this.storage.delete(oldestKey)+ }+ }+ }++ /**+ * 安全执行清理回调+ */+ private executeCleanup(item: V, key: K, context: string): void {+ if (!this.onEvict) return++ try {+ this.onEvict(item, key, context)+ } catch (err) {+ console.warn(`缓存清理失败 (${context}):`, err)+ }+ }++ /**+ * 记录缓存操作日志+ */+ private logCacheOperation(action: string, key: K): void {+ console.info(+ `LRU 缓存: ${action} ${String(key)},当前大小: ${this.storage.size}/${this.capacity}`,+ )+ }+}++/**+ * 创建专用于 Blob URL 管理的缓存实例+ * 在项目淘汰时自动释放 Object URL 资源+ */+export function createBlobUrlCache<T extends { url?: string }>(+ maxSize = 10,+): LRUCache<string, T> {+ const urlRevoker = (item: T, key: string, context: string) => {+ if (!item.url) return++ try {+ URL.revokeObjectURL(item.url)+ console.info(`已释放 Blob URL - ${context}`)+ } catch (err) {+ console.warn(`Blob URL 释放失败 (${context}):`, err)+ }+ }++ return new LRUCache<string, T>(maxSize, urlRevoker)+}++/**+ * Vue 组合式函数,用于在组件中管理 LRU 缓存生命周期+ * 组件卸载时自动执行缓存清理+ */+export function useLRUCache<K, V>(+ maxSize = 10,+ cleanupFn?: CleanupHandler<K, V>,+): LRUCache<K, V> {+ const cacheInstance = shallowRef<LRUCache<K, V> | null>(null)++ // 懒初始化缓存实例+ if (!cacheInstance.value) {+ cacheInstance.value = new LRUCache(maxSize, cleanupFn)+ }++ // 组件生命周期结束时清理资源+ onBeforeUnmount(() => {+ cacheInstance.value?.clear()+ })++ return cacheInstance.value+}\ No newline at end of filediff --git a/package.json b/package.jsonindex 0fcfe03f..ccd677ba 100644--- a/package.json+++ b/package.json@@ -41,12 +41,14 @@"eslint": "^9.0.0","exifr": "^7.1.3","exiftool-vendored": "^30.3.0",+ "file-type": "^21.0.0","heic-convert": "^2.1.0","heic-to": "^1.2.2","motion-v": "^1.7.0","nuxt": "^4.0.3","nuxt-auth-utils": "0.5.23","sharp": "^0.34.3",+ "swiper": "^11.2.10","tailwind-merge": "^3.3.1","tailwindcss": "^4.1.12","thumbhash": "^0.1.1",diff --git a/packages/webgl-image/src/index.ts b/packages/webgl-image/src/index.tsindex 97bb1ff2..1606ceb8 100644--- a/packages/webgl-image/src/index.ts+++ b/packages/webgl-image/src/index.ts@@ -17,8 +17,9 @@ export type {DebugInfo,TouchState,EngineConfig,- LoadingState,-} from './types/index'+} from './types'++export { LoadingState } from './types'// 常量导出export {@@ -53,4 +54,4 @@ export {createShader,createShaderProgram,createProgram,-} from './shaders'\ No newline at end of file+} from './shaders'diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 344d7e0f..7bd8bb57 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -74,6 +74,9 @@ importers:exiftool-vendored:specifier: ^30.3.0version: 30.3.0+ file-type:+ specifier: ^21.0.0+ version: 21.0.0heic-convert:specifier: ^2.1.0version: 2.1.0@@ -92,6 +95,9 @@ importers:sharp:specifier: ^0.34.3version: 0.34.3+ swiper:+ specifier: ^11.2.10+ version: 11.2.10tailwind-merge:specifier: ^3.3.1version: 3.3.1@@ -476,6 +482,9 @@ packages:resolution: {integrity: sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ==}engines: {node: '>=6.9.0'}+ '@borewit/[email protected]':+ resolution: {integrity: sha512-5L/uBxmjaCIX5h8Z+uu+kA9BQLkc/Wl06UGR5ajNRxu+/XjonB5i8JpgFMrPj3LXTCPA0pv8yxUvbUi+QthGGA==}+'@capsizecss/[email protected]':resolution: {integrity: sha512-Ju2I/Qn3c1OaU8FgeW4Tc22D4C9NwyVfKzNmzst59bvxBjPoLYNZMqFYn+HvCtn4MpXwiaDtCE8fNuQLpdi9yA==}@@ -2755,6 +2764,13 @@ packages:peerDependencies:vue: ^2.7.0 || ^3.0.0+ '@tokenizer/[email protected]':+ resolution: {integrity: sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg==}+ engines: {node: '>=18'}++ '@tokenizer/[email protected]':+ resolution: {integrity: sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==}+'@trysound/[email protected]':resolution: {integrity: sha512-L7z9BgrNEcYyUYtF+HaEfiS5ebkh9jXqbszz7pC0hRBPaatV0XjSD3+eHrpqFemQfgwiFF0QPIarnIihIDn7OA==}engines: {node: '>=10.13.0'}@@ -4538,10 +4554,17 @@ packages:resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==}engines: {node: ^12.20 || >= 14.13}+ resolution: {integrity: sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==}+resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==}engines: {node: '>=16.0.0'}+ resolution: {integrity: sha512-ek5xNX2YBYlXhiUXui3D/BXa3LdqPmoLJ7rqEx2bKJ7EAUEfmXgW0Das7Dc6Nr9MvqaOnIqiPV0mZk/r/UpNAg==}+ engines: {node: '>=20'}+resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==}@@ -6414,6 +6437,10 @@ packages:resolution: {integrity: sha512-7ZvoFTiCnGxBtDqJ//Cu6fWtZtc7Y3x+QOirG15wztbdngGSkht27o2pyGWrVy0b4WAy3jbKmnoK6g5VlVNUUw==}+ resolution: {integrity: sha512-KIy5nylvC5le1OdaaoCJ07L+8iQzJHGH6pWDuzS+d07Cu7n1MZ2x26P8ZKIWfbK02+XIL8Mp4RkWeqdUCrDMfg==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-FL8EeKFFyNQv5cMnXI31CIMCsFarSVI2bF0U0ImeNE3g/F1IvJQyqzOXxPBRXiwQfyBTlbNe88jh1jFW0O/jiQ==}@@ -6453,6 +6480,10 @@ packages:engines: {node: '>=16'}hasBin: true+ resolution: {integrity: sha512-RMeVUUjTQH+6N3ckimK93oxz6Sn5la4aDlgPzB+rBrG/smPdCTicXyhxa+woIpopz+jewEloiEE3lKo1h9w2YQ==}+ engines: {node: '>= 4.7.0'}+resolution: {integrity: sha512-MeQTA1r0litLUf0Rp/iisCaL8761lKAZHaimlbGK4j0HysC4PLfqygQj9srcs0m2RdtDYnF8UuYyKpbjHYp7Jw==}engines: {node: ^14.18.0 || >=16.0.0}@@ -6558,6 +6589,10 @@ packages:resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}engines: {node: '>=0.6'}+ resolution: {integrity: sha512-kh9LVIWH5CnL63Ipf0jhlBIy0UsrMj/NJDfpsy1SqOXlLKEVyXXYrnFxFT1yOOYVGBSApeVnjPw/sBz5BfEjAQ==}+ engines: {node: '>=14.16'}+resolution: {integrity: sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w==}@@ -6615,6 +6650,10 @@ packages:resolution: {integrity: sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA==}+ resolution: {integrity: sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-R9fBn90VTJrqqLDwyMph+HGne8eqY1iPfYhPzZrvKpIfwkWZbcYlfpsb8B9dTvBfpy1/hqAD7Wi8EKfP9e8zdw==}@@ -7869,6 +7908,8 @@ snapshots:'@babel/helper-string-parser': 7.27.1'@babel/helper-validator-identifier': 7.27.1+ '@borewit/[email protected]': {}+'@capsizecss/[email protected]': {}'@capsizecss/[email protected]':@@ -10326,6 +10367,16 @@ snapshots:'@tanstack/virtual-core': 3.13.12vue: 3.5.19([email protected])+ '@tokenizer/[email protected]':+ dependencies:+ debug: 4.4.1+ fflate: 0.8.2+ token-types: 6.1.1+ transitivePeerDependencies:+ - supports-color++ '@tokenizer/[email protected]': {}+'@trysound/[email protected]':optional: true@@ -12232,10 +12283,21 @@ snapshots:node-domexception: 1.0.0web-streams-polyfill: 3.3.3+ [email protected]: {}+dependencies:flat-cache: 4.0.1+ dependencies:+ '@tokenizer/inflate': 0.2.7+ strtok3: 10.3.4+ token-types: 6.1.1+ uint8array-extras: 1.5.0+ transitivePeerDependencies:+ - supports-color+@@ -14406,6 +14468,10 @@ snapshots:+ dependencies:+ '@tokenizer/token': 0.3.0+@@ -14451,6 +14517,8 @@ snapshots:picocolors: 1.1.1sax: 1.4.1+ [email protected]: {}+dependencies:'@pkgr/core': 0.2.9@@ -14563,6 +14631,12 @@ snapshots:+ dependencies:+ '@borewit/text-codec': 0.1.1+ '@tokenizer/token': 0.3.0+ ieee754: 1.2.1+@@ -14599,6 +14673,8 @@ snapshots:+ [email protected]: {}+diff --git a/types/index.d.ts b/types/index.d.tsdeleted file mode 100644index e69de29b..00000000