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(filters): 添加全局筛选和排序功能
Timothy Yina55e6ea544c1
diff --git a/app/app.config.ts b/app/app.config.tsindex 93095a4a..a9847c6e 100644--- a/app/app.config.ts+++ b/app/app.config.ts@@ -9,5 +9,25 @@ export default defineAppConfig({warning: 'amber',danger: 'rose',},+ popover: {+ slots: {+ content:+ 'bg-white/70 dark:bg-neutral-900/50 backdrop-blur-3xl ring-0 shadow-lg border border-neutral-300/50 dark:border-neutral-500/50 rounded-lg',+ },+ },+ card: {+ slots: {+ header: 'p-2 sm:p-2 pb-0!',+ body: 'p-2 sm:p-2',+ footer: 'p-2 sm:p-2',+ },+ variants: {+ variant: {+ glassmorphism: {+ root: 'shadow-lg divide-y-0 divide-neutral-300/50 dark:divide-neutral-500/50',+ },+ },+ },+ },},-})\ No newline at end of file+})diff --git a/app/app.vue b/app/app.vueindex 2a275875..1f256d23 100644--- a/app/app.vue+++ b/app/app.vue@@ -5,6 +5,17 @@ useHead({const { data } = useFetch('/api/photos')const photos = computed(() => (data.value as Photo[]) || [])++// 在全局级别提供筛选功能的状态管理+provide('photosFiltering', reactive({+ activeFilters: {+ tags: [],+ cameras: [],+ lenses: [],+ cities: [],+ ratings: []+ }+}))</script><template>diff --git a/app/components/masonry/HeaderItem.vue b/app/components/masonry/HeaderItem.vueindex 72bf5289..2cbf0078 100644--- a/app/components/masonry/HeaderItem.vue+++ b/app/components/masonry/HeaderItem.vue@@ -16,6 +16,26 @@ const handleOpenLogin = () => {window.location.href = '/api/auth/github'console.log('Login button clicked')}++// 获取筛选状态+const { hasActiveFilters, selectedCounts } = usePhotoFilters()++// 获取排序状态+const {+ currentSortLabel,+ currentSortIcon,+ currentSortOption,+ availableSorts,+ setSortOption,+} = usePhotoSort()++// 计算总的筛选项数量+const totalSelectedFilters = computed(() => {+ return Object.values(selectedCounts.value).reduce(+ (total, count) => total + count,+ 0,+ )+})</script><template>@@ -31,7 +51,7 @@ const handleOpenLogin = () => {<divclass="absolute inset-0 -z-10 bg-white/50 dark:bg-neutral-900/50"></div>- <div class="flex flex-col items-center py-6 gap-2">+ <div class="flex flex-col items-center py-6 pb-3 gap-2"><AuthState><template #default="{ loggedIn, clear }"><div class="flex flex-col items-center gap-2">@@ -64,39 +84,115 @@ const handleOpenLogin = () => {{{ stats?.total }} 张照片</p><p class="font-[Pacifico]">Mems rest within the lens.</p>- <UButton- variant="ghost"- color="neutral"- icon="tabler:map-pin-2"- label="探索地图"- size="sm"- to="/explore"- /></div><div- v-if="loggedIn"- class="text-center mt-3"+ class="flex items-center gap-0 p-1 bg-white/30 dark:bg-neutral-900/50 rounded-full">- <div class="flex items-center gap-2">+ <UTooltip text="探索地图">+ <UButton+ variant="soft"+ color="neutral"+ class="bg-transparent rounded-full cursor-pointer"+ icon="tabler:map-pin-2"+ size="sm"+ to="/explore"+ />+ </UTooltip>+ <UPopover>+ <UTooltip text="筛选照片">+ <UChip+ inset+ size="sm"+ color="info"+ :show="totalSelectedFilters > 0"+ >+ <UButton+ variant="soft"+ :color="hasActiveFilters ? 'info' : 'neutral'"+ class="bg-transparent rounded-full cursor-pointer relative"+ icon="tabler:filter"+ size="sm"+ />+ </UChip>+ </UTooltip>++ <template #content>+ <UCard variant="glassmorphism">+ <OverlayFilterPanel />+ </UCard>+ </template>+ </UPopover>+ <UPopover>+ <UTooltip text="照片排序">+ <UButton+ variant="soft"+ :color="+ currentSortOption?.key === 'dateTaken-desc'+ ? 'neutral'+ : 'info'+ "+ class="bg-transparent rounded-full cursor-pointer"+ :icon="currentSortIcon"+ size="sm"+ />+ </UTooltip>++ <template #content>+ <UCard+ variant="glassmorphism"+ class="w-3xs"+ >+ <template #header>+ <h3 class="font-bold text-sm p-1">排序方式</h3>+ </template>++ <div class="space-y-1">+ <UButton+ v-for="sort in availableSorts"+ :key="sort.key"+ :variant="+ currentSortLabel === sort.label ? 'soft' : 'ghost'+ "+ :color="+ currentSortLabel === sort.label ? 'info' : 'neutral'+ "+ :icon="sort.icon"+ size="sm"+ block+ class="justify-start"+ @click="setSortOption(sort.key)"+ >+ {{ sort.label }}+ </UButton>+ </div>+ </UCard>+ </template>+ </UPopover>+ <UTooltip+ v-if="loggedIn"+ text="仪表盘"+ ><UButtonsize="sm"color="info"variant="soft"+ class="bg-transparent rounded-full cursor-pointer"icon="tabler:dashboard"to="/dashboard"- >- 仪表盘- </UButton>+ />+ </UTooltip>+ <UTooltip+ v-if="loggedIn"+ text="登出"+ ><UButtonsize="sm"color="error"variant="soft"+ class="bg-transparent rounded-full cursor-pointer"icon="tabler:logout"@click="clear"- >- 登出- </UButton>- </div>+ /></UTooltip></div></template></AuthState>diff --git a/app/components/masonry/Root.vue b/app/components/masonry/Root.vueindex 3d93c5ce..34f10e93 100644--- a/app/components/masonry/Root.vue+++ b/app/components/masonry/Root.vue@@ -11,6 +11,15 @@ const props = withDefaults(defineProps<Props>(), {const dayjs = useDayjs()const router = useRouter()+// 使用筛选和排序功能+const { filteredPhotos, hasActiveFilters } = usePhotoFilters()+const { sortedPhotos } = usePhotoSort()++// 使用筛选后的照片(已包含排序),或者使用排序后的原始照片+const displayPhotos = computed(() => {+ return hasActiveFilters.value ? filteredPhotos.value : sortedPhotos.value+})+// Constantsconst FIRST_SCREEN_ITEMS_COUNT = 30const COLUMN_GAP = 4@@ -51,13 +60,13 @@ const columnCount = computed(() => {})const photoStats = computed(() => {- const totalPhotos = props.photos?.length || 0- const photosWithDates = props.photos?.filter((p) => p.dateTaken).length || 0- const photosWithTitles = props.photos?.filter((p) => p.title).length || 0- const photosWithExif = props.photos?.filter((p) => p.exif).length || 0+ const totalPhotos = displayPhotos.value?.length || 0+ const photosWithDates = displayPhotos.value?.filter((p) => p.dateTaken).length || 0+ const photosWithTitles = displayPhotos.value?.filter((p) => p.title).length || 0+ const photosWithExif = displayPhotos.value?.filter((p) => p.exif).length || 0// Get date range of all photos- const allDates = props.photos+ const allDates = displayPhotos.value?.map((p) => p?.dateTaken).filter((date): date is string => Boolean(date)).map((date) => dayjs(date).format('YYYY年MM月DD日'))@@ -111,7 +120,7 @@ const handleVisibilityChange = ({const processVisibleLivePhotos = async () => {const visiblePhotosArray = Array.from(visiblePhotos.value)const livePhotosToProcess = visiblePhotosArray- .map(index => props.photos[index])+ .map(index => displayPhotos.value[index]).filter((photo): photo is Photo =>photo != null &&photo.isLivePhoto === 1 &&@@ -146,14 +155,14 @@ const updateDateRange = () => {// Calculate visible datesconst visibleDates = visiblePhotosArray- .map((index) => props.photos[index]?.dateTaken)+ .map((index) => displayPhotos.value[index]?.dateTaken).filter((date): date is string => Boolean(date)).map((date) => dayjs(date)).sort((a, b) => (a.isBefore(b) ? -1 : 1))// Calculate visible citiesconst cities = visiblePhotosArray- .map((index) => props.photos[index]?.city)+ .map((index) => displayPhotos.value[index]?.city).filter((city): city is string => Boolean(city))const uniqueCities = [...new Set(cities)]@@ -232,7 +241,7 @@ onMounted(() => {})const handleOpenViewer = (index: number) => {- router.push(`/${props.photos[index]?.id}`)+ router.push(`/${displayPhotos.value[index]?.id}`)}</script>@@ -279,7 +288,7 @@ const handleOpenViewer = (index: number) => {<!-- Photo Items --><MasonryItem- v-for="(photo, index) in photos"+ v-for="(photo, index) in displayPhotos":key="photo.id || index":photo="photo":index="index"diff --git a/app/components/overlay/FilterPanel.vue b/app/components/overlay/FilterPanel.vuenew file mode 100644index 00000000..d9191a9d--- /dev/null+++ b/app/components/overlay/FilterPanel.vue@@ -0,0 +1,254 @@+<script lang="ts" setup>+import type { TabsItem } from '@nuxt/ui'++const {+ availableFilters,+ selectedCounts,+ toggleFilter,+ isFilterSelected,+ clearAllFilters,+ hasActiveFilters,+} = usePhotoFilters()++const currentTab = ref('labels')++const tabItems = computed<TabsItem[]>(() => [+ {+ label: '标签',+ value: 'labels',+ badge: selectedCounts.value.tags || undefined,+ icon: 'tabler:tags',+ slot: 'tags',+ },+ {+ label: '相机',+ value: 'cameras',+ badge: selectedCounts.value.cameras || undefined,+ icon: 'tabler:camera',+ slot: 'cameras',+ },+ {+ label: '镜头',+ value: 'lenses',+ badge: selectedCounts.value.lenses || undefined,+ icon: 'tabler:aperture',+ slot: 'lenses',+ },+ {+ label: '城市',+ value: 'cities',+ badge: selectedCounts.value.cities || undefined,+ icon: 'tabler:map-pin',+ slot: 'cities',+ },+ {+ label: '评分',+ value: 'ratings',+ badge: selectedCounts.value.ratings || undefined,+ icon: 'tabler:star',+ slot: 'ratings',+ },+])++const handleToggleFilter = (type: string, value: string | number) => {+ toggleFilter(type as any, value)+}+</script>++<template>+ <div class="space-y-3 w-[calc(100vw-34px)] sm:w-96">+ <div class="flex items-center justify-between">+ <h3 class="text-sm font-bold text-neutral-900 dark:text-white p-2 pb-0">+ 筛选照片+ </h3>+ <UButton+ v-if="hasActiveFilters"+ size="sm"+ variant="ghost"+ color="neutral"+ icon="tabler:filter-x"+ @click="clearAllFilters"+ >+ 清除全部+ </UButton>+ </div>+ <!-- 标签页 -->+ <UTabs+ v-model="currentTab"+ color="neutral"+ size="xs"+ :items="tabItems"+ :ui="{+ list: 'bg-white/30 dark:bg-neutral-800/50',+ indicator: 'bg-white/80',+ trigger:+ 'data-[state=inactive]:text-muted data-[state=active]:text-default dark:data-[state=active]:text-inverted',+ trailingBadge:+ 'ring-0 rounded-full py-0 bg-info-100/80 dark:bg-info-900/80 text-info-500 dark:text-info-400 border border-info-300/50 dark:border-info-700/50',+ trailingBadgeSize: 'sm',+ }"+ >+ <!-- 标签面板 -->+ <template #tags>+ <div class="space-y-0.5 max-h-64 overflow-y-auto">+ <div+ v-for="tag in availableFilters.tags"+ :key="tag.label"+ class="flex items-center justify-between cursor-pointer select-none hover:bg-neutral-400/30 dark:hover:bg-info-800/30 rounded-lg px-2 py-2"+ :class="+ isFilterSelected('tags', tag.label)+ ? 'bg-neutral-400/30 dark:bg-info-800/30'+ : ''+ "+ @click="handleToggleFilter('tags', tag.label)"+ >+ <span class="text-sm text-default font-medium truncate">+ {{ tag.label }}+ </span>+ <Icon+ v-if="isFilterSelected('tags', tag.label)"+ name="tabler:check"+ class="size-4 text-green-500"+ />+ </div>+ <div+ v-if="availableFilters.tags.length === 0"+ class="text-center text-sm text-neutral-500 dark:text-neutral-400 py-4"+ >+ 没有标签+ </div>+ </div>+ </template>++ <!-- 相机面板 -->+ <template #cameras>+ <div class="space-y-0.5 max-h-64 overflow-y-auto">+ <div+ v-for="camera in availableFilters.cameras"+ :key="camera.label"+ class="flex items-center justify-between cursor-pointer select-none hover:bg-neutral-400/30 dark:hover:bg-info-800/30 rounded-lg px-2 py-2"+ :class="+ isFilterSelected('cameras', camera.label)+ ? 'bg-neutral-400/30 dark:bg-info-800/30'+ : ''+ "+ @click="handleToggleFilter('cameras', camera.label)"+ >+ <span class="text-sm text-default font-medium truncate">+ {{ camera.label }}+ </span>+ <Icon+ v-if="isFilterSelected('cameras', camera.label)"+ name="tabler:check"+ class="size-4 text-green-500"+ />+ </div>+ <div+ v-if="availableFilters.cameras.length === 0"+ class="text-center text-sm text-neutral-500 dark:text-neutral-400 py-4"+ >+ 没有相机信息+ </div>+ </div>+ </template>++ <!-- 镜头面板 -->+ <template #lenses>+ <div class="space-y-0.5 max-h-64 overflow-y-auto">+ <div+ v-for="lens in availableFilters.lenses"+ :key="lens.label"+ class="flex items-center justify-between cursor-pointer select-none hover:bg-neutral-400/30 dark:hover:bg-info-800/30 rounded-lg px-2 py-2"+ :class="+ isFilterSelected('lenses', lens.label)+ ? 'bg-neutral-400/30 dark:bg-info-800/30'+ : ''+ "+ @click="handleToggleFilter('lenses', lens.label)"+ >+ <span class="text-sm text-default font-medium truncate">+ {{ lens.label }}+ </span>+ <Icon+ v-if="isFilterSelected('lenses', lens.label)"+ name="tabler:check"+ class="size-4 text-green-500"+ />+ </div>+ <div+ v-if="availableFilters.lenses.length === 0"+ class="text-center text-sm text-neutral-500 dark:text-neutral-400 py-4"+ >+ 没有镜头信息+ </div>+ </div>+ </template>++ <!-- 城市面板 -->+ <template #cities>+ <div class="space-y-0.5 max-h-64 overflow-y-auto">+ <div+ v-for="city in availableFilters.cities"+ :key="city.label"+ class="flex items-center justify-between cursor-pointer select-none hover:bg-neutral-400/30 dark:hover:bg-info-800/30 rounded-lg px-2 py-2"+ :class="+ isFilterSelected('cities', city.label)+ ? 'bg-neutral-400/30 dark:bg-info-800/30'+ : ''+ "+ @click="handleToggleFilter('cities', city.label)"+ >+ <span class="text-sm text-default font-medium truncate">+ {{ city.label }}+ </span>+ <Icon+ v-if="isFilterSelected('cities', city.label)"+ name="tabler:check"+ class="size-4 text-green-500"+ />+ </div>+ <div+ v-if="availableFilters.cities.length === 0"+ class="text-center text-sm text-neutral-500 dark:text-neutral-400 py-4"+ >+ 没有城市信息+ </div>+ </div>+ </template>++ <!-- 评分面板 -->+ <template #ratings>+ <div class="space-y-0.5 max-h-64 overflow-y-auto">+ <div+ v-for="rating in availableFilters.ratings"+ :key="rating.label"+ class="flex items-center justify-between cursor-pointer select-none hover:bg-neutral-400/30 dark:hover:bg-info-800/30 rounded-lg px-2 py-2"+ :class="+ isFilterSelected('ratings', rating.label)+ ? 'bg-neutral-400/30 dark:bg-info-800/30'+ : ''+ "+ @click="handleToggleFilter('ratings', rating.label)"+ >+ <span class="text-sm text-default font-medium truncate">+ {{ rating.label }} 星+ </span>+ <Icon+ v-if="isFilterSelected('ratings', rating.label)"+ name="tabler:check"+ class="size-4 text-green-500"+ />+ </div>+ <div+ v-if="availableFilters.ratings.length === 0"+ class="text-center text-sm text-neutral-500 dark:text-neutral-400 py-4"+ >+ 暂无评分信息+ </div>+ </div>+ </template>+ </UTabs>+ </div>+</template>++<style scoped></style>diff --git a/app/composables/usePhotoFilters.ts b/app/composables/usePhotoFilters.tsnew file mode 100644index 00000000..54140b02--- /dev/null+++ b/app/composables/usePhotoFilters.ts@@ -0,0 +1,218 @@+interface FilterOptions {+ tags: string[]+ cameras: string[]+ lenses: string[]+ cities: string[]+ ratings: number[]+}++interface FilterStats {+ tags: Map<string, number>+ cameras: Map<string, number>+ lenses: Map<string, number>+ cities: Map<string, number>+ ratings: Map<number, number>+}++// 全局筛选状态管理+const globalFilters = ref<FilterOptions>({+ tags: [],+ cameras: [],+ lenses: [],+ cities: [],+ ratings: []+})++export function usePhotoFilters() {+ const { photos } = usePhotos()+ const { sortedPhotos } = usePhotoSort()++ // 使用全局筛选状态+ const activeFilters = globalFilters++ // 计算可用的筛选选项及其数量+ const filterStats = computed((): FilterStats => {+ const stats: FilterStats = {+ tags: new Map(),+ cameras: new Map(),+ lenses: new Map(),+ cities: new Map(),+ ratings: new Map()+ }++ photos.value.forEach(photo => {+ // 标签统计+ if (photo.tags && Array.isArray(photo.tags)) {+ photo.tags.forEach(tag => {+ stats.tags.set(tag, (stats.tags.get(tag) || 0) + 1)+ })+ }++ // 相机统计 (从 EXIF 获取)+ if (photo.exif?.Make && photo.exif?.Model) {+ const camera = `${photo.exif.Make} ${photo.exif.Model}`+ stats.cameras.set(camera, (stats.cameras.get(camera) || 0) + 1)+ }++ // 镜头统计 (从 EXIF 获取)+ if (photo.exif?.LensMake && photo.exif?.LensModel) {+ const lens = `${photo.exif.LensMake} ${photo.exif.LensModel}`+ stats.lenses.set(lens, (stats.lenses.get(lens) || 0) + 1)+ } else if (photo.exif?.LensModel) {+ const lens = photo.exif.LensModel+ stats.lenses.set(lens, (stats.lenses.get(lens) || 0) + 1)+ }++ // 城市统计+ if (photo.city) {+ stats.cities.set(photo.city, (stats.cities.get(photo.city) || 0) + 1)+ }++ // 评分统计 (从 EXIF Rating 获取)+ if (photo.exif?.Rating && photo.exif.Rating > 0) {+ const rating = photo.exif.Rating+ stats.ratings.set(rating, (stats.ratings.get(rating) || 0) + 1)+ }+ })++ return stats+ })++ // 获取排序后的筛选选项+ const availableFilters = computed(() => {+ return {+ tags: Array.from(filterStats.value.tags.entries())+ .sort((a, b) => b[1] - a[1]) // 按数量降序排列+ .map(([tag, count]) => ({ label: tag, count })),++ cameras: Array.from(filterStats.value.cameras.entries())+ .sort((a, b) => a[0].localeCompare(b[0])) // 按名称字母顺序排列+ .map(([camera, count]) => ({ label: camera, count })),++ lenses: Array.from(filterStats.value.lenses.entries())+ .sort((a, b) => a[0].localeCompare(b[0])) // 按名称字母顺序排列+ .map(([lens, count]) => ({ label: lens, count })),++ cities: Array.from(filterStats.value.cities.entries())+ .sort((a, b) => b[1] - a[1])+ .map(([city, count]) => ({ label: city, count })),++ ratings: Array.from(filterStats.value.ratings.entries())+ .sort((a, b) => b[0] - a[0]) // 按评分降序排列+ .map(([rating, count]) => ({ label: rating, count })),+ }+ })++ // 计算已选择的筛选项数量+ const selectedCounts = computed(() => {+ return {+ tags: activeFilters.value.tags.length,+ cameras: activeFilters.value.cameras.length,+ lenses: activeFilters.value.lenses.length,+ cities: activeFilters.value.cities.length,+ ratings: activeFilters.value.ratings.length+ }+ })++ // 筛选后的照片(应用排序)+ const filteredPhotos = computed(() => {+ // 先获取排序后的照片,再应用筛选+ return sortedPhotos.value.filter(photo => {+ // 标签筛选+ if (activeFilters.value.tags.length > 0) {+ const photoTags = photo.tags || []+ const hasMatchingTag = activeFilters.value.tags.some(tag =>+ photoTags.includes(tag)+ )+ if (!hasMatchingTag) return false+ }++ // 相机筛选+ if (activeFilters.value.cameras.length > 0) {+ const photoCamera = photo.exif?.Make && photo.exif?.Model+ ? `${photo.exif.Make} ${photo.exif.Model}`+ : null+ if (!photoCamera || !activeFilters.value.cameras.includes(photoCamera)) {+ return false+ }+ }++ // 镜头筛选+ if (activeFilters.value.lenses.length > 0) {+ const photoLens = photo.exif?.LensMake && photo.exif?.LensModel+ ? `${photo.exif.LensMake} ${photo.exif.LensModel}`+ : photo.exif?.LensModel || null+ if (!photoLens || !activeFilters.value.lenses.includes(photoLens)) {+ return false+ }+ }++ // 城市筛选+ if (activeFilters.value.cities.length > 0) {+ if (!photo.city || !activeFilters.value.cities.includes(photo.city)) {+ return false+ }+ }++ // 评分筛选+ if (activeFilters.value.ratings.length > 0) {+ const photoRating = photo.exif?.Rating || 0+ if (!activeFilters.value.ratings.includes(photoRating)) {+ return false+ }+ }++ return true+ })+ })++ // 切换筛选项+ const toggleFilter = (type: keyof FilterOptions, value: string | number) => {+ const filters = activeFilters.value[type] as any[]+ const index = filters.indexOf(value)++ if (index === -1) {+ filters.push(value)+ } else {+ filters.splice(index, 1)+ }+ }++ // 清除所有筛选+ const clearAllFilters = () => {+ activeFilters.value = {+ tags: [],+ cameras: [],+ lenses: [],+ cities: [],+ ratings: []+ }+ }++ // 清除指定类型的筛选+ const clearFilterType = (type: keyof FilterOptions) => {+ activeFilters.value[type] = [] as any+ }++ // 检查筛选项是否被选中+ const isFilterSelected = (type: keyof FilterOptions, value: string | number) => {+ return (activeFilters.value[type] as any[]).includes(value)+ }++ // 检查是否有任何筛选项被激活+ const hasActiveFilters = computed(() => {+ return Object.values(activeFilters.value).some(filters => filters.length > 0)+ })++ return {+ activeFilters: readonly(activeFilters),+ availableFilters,+ selectedCounts,+ filteredPhotos,+ hasActiveFilters,+ toggleFilter,+ clearAllFilters,+ clearFilterType,+ isFilterSelected+ }+}diff --git a/app/composables/usePhotoSort.ts b/app/composables/usePhotoSort.tsnew file mode 100644index 00000000..2203d644--- /dev/null+++ b/app/composables/usePhotoSort.ts@@ -0,0 +1,157 @@+interface SortOption {+ key: string+ label: string+ icon?: string+ value: (photo: Photo) => any+ order: 'asc' | 'desc'+}++interface SortState {+ currentSort: string+ availableSorts: SortOption[]+}++// 全局排序状态+const globalSortState = ref<SortState>({+ currentSort: 'dateTaken-desc', // 默认按拍摄时间倒序+ availableSorts: [+ {+ key: 'dateTaken-desc',+ label: '拍摄时间(新到旧)',+ icon: 'tabler:sort-descending',+ value: (photo: Photo) =>+ photo.dateTaken ? new Date(photo.dateTaken).getTime() : 0,+ order: 'desc',+ },+ {+ key: 'dateTaken-asc',+ label: '拍摄时间(旧到新)',+ icon: 'tabler:sort-ascending',+ value: (photo: Photo) =>+ photo.dateTaken ? new Date(photo.dateTaken).getTime() : 0,+ order: 'asc',+ },+ {+ key: 'fileSize-asc',+ label: '文件大小正序',+ icon: 'tabler:sort-ascending-small-big',+ value: (photo: Photo) => photo.fileSize || 0,+ order: 'asc',+ },+ {+ key: 'fileSize-desc',+ label: '文件大小倒序',+ icon: 'tabler:sort-descending-small-big',+ value: (photo: Photo) => photo.fileSize || 0,+ order: 'desc',+ },+ {+ key: 'title-asc',+ label: '标题正序',+ icon: 'tabler:sort-ascending-letters',+ value: (photo: Photo) => (photo.title || photo.id).toLowerCase(),+ order: 'asc',+ },+ {+ key: 'title-desc',+ label: '标题倒序',+ icon: 'tabler:sort-descending-letters',+ value: (photo: Photo) => (photo.title || photo.id).toLowerCase(),+ order: 'desc',+ },+ ],+})++export function usePhotoSort() {+ const { photos } = usePhotos()++ // 当前排序选项+ const currentSortOption = computed(() => {+ return globalSortState.value.availableSorts.find(+ sort => sort.key === globalSortState.value.currentSort+ ) || globalSortState.value.availableSorts[0]+ })++ // 排序后的照片+ const sortedPhotos = computed(() => {+ const option = currentSortOption.value+ if (!option) return photos.value++ const sorted = [...photos.value].sort((a, b) => {+ const valueA = option.value(a)+ const valueB = option.value(b)++ // 处理 null/undefined 值+ if (valueA == null && valueB == null) return 0+ if (valueA == null) return 1+ if (valueB == null) return -1++ // 数值比较+ if (typeof valueA === 'number' && typeof valueB === 'number') {+ return option.order === 'asc' ? valueA - valueB : valueB - valueA+ }++ // 字符串比较+ if (typeof valueA === 'string' && typeof valueB === 'string') {+ const comparison = valueA.localeCompare(valueB)+ return option.order === 'asc' ? comparison : -comparison+ }++ // 其他类型转字符串比较+ const strA = String(valueA)+ const strB = String(valueB)+ const comparison = strA.localeCompare(strB)+ return option.order === 'asc' ? comparison : -comparison+ })++ return sorted+ })++ // 设置排序方式+ const setSortOption = (sortKey: string) => {+ if (globalSortState.value.availableSorts.some(sort => sort.key === sortKey)) {+ globalSortState.value.currentSort = sortKey+ }+ }++ // 切换时间排序(正序/倒序)+ const toggleDateSortOrder = () => {+ const current = globalSortState.value.currentSort+ if (current === 'dateTaken-desc') {+ setSortOption('dateTaken-asc')+ } else {+ setSortOption('dateTaken-desc')+ }+ }++ // 获取可用的排序选项+ const availableSorts = computed(() => globalSortState.value.availableSorts)++ // 获取当前排序的显示标签+ const currentSortLabel = computed(() => currentSortOption.value?.label || '拍摄时间(新到旧)')++ // 获取当前排序的显示图标+ const currentSortIcon = computed(() => currentSortOption.value?.icon || 'tabler:sort-descending')++ // 检查是否为时间排序+ const isDateSort = computed(() => {+ return globalSortState.value.currentSort.startsWith('dateTaken')+ })++ // 检查时间排序是否为倒序+ const isDateSortDesc = computed(() => {+ return globalSortState.value.currentSort === 'dateTaken-desc'+ })++ return {+ sortedPhotos,+ currentSortOption: readonly(currentSortOption),+ currentSortLabel,+ currentSortIcon,+ availableSorts,+ isDateSort,+ isDateSortDesc,+ setSortOption,+ toggleDateSortOrder+ }+}