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(albums): add albums management features and API endpoints
Timothy Yindafc24ec7aa1
diff --git a/app/layouts/dashboard.vue b/app/layouts/dashboard.vueindex 93a52a82..a3b3d5c7 100644--- a/app/layouts/dashboard.vue+++ b/app/layouts/dashboard.vue@@ -13,6 +13,11 @@ const items = ref<NavigationMenuItem[]>([icon: 'tabler:photo-cog',to: '/dashboard/photos',},+ {+ label: $t('title.albums'),+ icon: 'tabler:album',+ to: '/dashboard/albums',+ },{label: $t('title.locations'),icon: 'tabler:map-pin-cog',diff --git a/app/pages/albums/[albumId].vue b/app/pages/albums/[albumId].vueindex 2afb2426..0d88693c 100644--- a/app/pages/albums/[albumId].vue+++ b/app/pages/albums/[albumId].vue@@ -1,13 +1,326 @@<script lang="ts" setup>+import { motion } from 'motion-v'+const route = useRoute()+const router = useRouter()+const dayjs = useDayjs()++const albumId = computed(() => {+ const id = route.params.albumId as string+ return parseInt(id, 10)+})++const {+ data: album,+ error,+ pending,+} = await useFetch(() => `/api/albums/${albumId.value}`, {+ watch: [albumId],+})++if (error.value) {+ throw createError({+ statusCode: 404,+ statusMessage: 'Album not found',+ })+}++const albumData = computed(() => album.value)++const albumStats = computed(() => {+ if (!albumData.value) return null++ const photos = albumData.value.photos || []+ const totalPhotos = photos.length+ const photosWithDates = photos.filter((p: any) => p.dateTaken).length+ const photosWithExif = photos.filter((p: any) => p.exif).length++ const allDates = photos+ .map((p: any) => p?.dateTaken)+ .filter((date: any): date is string => Boolean(date))+ .map((date: string) => dayjs(date))+ .sort((a, b) => (a.isBefore(b) ? -1 : 1))++ const dateRange =+ allDates.length > 0+ ? {+ start: allDates[0],+ end: allDates[allDates.length - 1],+ }+ : null++ return {+ total: totalPhotos,+ withDates: photosWithDates,+ withExif: photosWithExif,+ dateRange,+ }+})++// 计算日期范围文本+const dateRangeText = computed(() => {+ const range = albumStats.value?.dateRange+ if (!range || !range.start || !range.end) return null++ if (range.start.isSame(range.end, 'day')) {+ return range.start.format('ll')+ } else if (range.start.isSame(range.end, 'month')) {+ return range.start.format('MMM YYYY')+ } else if (range.start.isSame(range.end, 'year')) {+ return `${range.start.format('MMM')} - ${range.end.format('MMM YYYY')}`+ } else {+ return `${range.start.format('ll')} - ${range.end.format('ll')}`+ }+})++// 用于 MasonryWall 的照片数据+const masonryItems = computed(() => {+ return (+ albumData.value?.photos?.map((photo: any, index: number) => ({+ id: photo.id,+ photo,+ originalIndex: index,+ })) ?? []+ )+})++const isMobile = useMediaQuery('(max-width: 768px)')+const columnWidth = computed(() => (isMobile.value ? 280 : 280))+const maxColumns = computed(() => (isMobile.value ? 2 : 8))+const minColumns = computed(() => (isMobile.value ? 2 : 2))++const MASONRY_GAP = 4++const handleOpenViewer = (index: number) => {+ const photos = albumData.value?.photos+ if (photos && photos[index]) {+ const { openViewer } = useViewerState()+ const albumRoute = `/albums/${albumId.value}`+ openViewer(0, albumRoute)+ router.push(`/${photos[index].id}`)+ }+}++const coverPhoto = computed(() => {+ const album = albumData.value+ if (!album?.photos) return null++ // coverPhotoId first+ if (album.coverPhotoId) {+ const cover = album.photos.find((p: any) => p.id === album.coverPhotoId)+ if (cover) return cover+ }++ // otherwise first photo+ return album.photos[0] || null+})++const goBackToAlbums = () => {+ router.push('/albums')+}++onBeforeMount(() => {+ useHead({+ title: albumData.value ? albumData.value.title : 'Album Not Found',+ })+})</script><template>- <div>- <h1>Album Details</h1>+ <div class="relative w-full">+ <div+ v-if="pending"+ class="flex flex-col items-center justify-center min-h-[50vh] gap-4"+ >+ <UIcon+ name="tabler:loader"+ class="animate-spin size-8 text-primary-600"+ />+ <p class="text-sm text-neutral-600 dark:text-neutral-400">+ {{ $t('ui.loading') }}+ </p>+ </div>++ <template v-else-if="albumData">+ <!-- Backdrop layer -->+ <div+ v-if="coverPhoto"+ class="absolute inset-0 h-[500px] overflow-hidden -z-10"+ >+ <img+ :src="coverPhoto.thumbnailUrl || ''"+ :alt="albumData.title"+ class="w-full h-full object-cover blur-xl opacity-40 dark:opacity-20 scale-110"+ />+ <div+ class="absolute inset-0 bg-gradient-to-b from-transparent via-white/50 to-white dark:via-neutral-900/50 dark:to-neutral-900"+ />+ </div>++ <!-- Back Button -->+ <div class="relative container mx-auto px-4 sm:px-6 lg:px-8 pt-4 z-10">+ <UButton+ variant="ghost"+ color="neutral"+ icon="tabler:arrow-left"+ size="sm"+ @click="goBackToAlbums"+ />+ </div>++ <!-- Album Information -->+ <div class="relative container mx-auto px-4 sm:px-6 lg:px-8 py-8 z-10">+ <AnimatePresence>+ <motion.div+ class="flex flex-col gap-6"+ :initial="{ opacity: 0, y: 10 }"+ :animate="{ opacity: 1, y: 0 }"+ :transition="{ duration: 0.4 }"+ >+ <!-- title -->+ <div>+ <h1+ class="text-3xl sm:text-4xl font-bold text-neutral-900 dark:text-white tracking-tight"+ >+ {{ albumData.title }}+ </h1>+ </div>++ <!-- metadata -->+ <div class="flex flex-col gap-4">+ <!-- description -->+ <p+ class="text-base text-neutral-600 dark:text-neutral-300 leading-relaxed max-w-2xl"+ >+ {{ albumData.description || $t('album.noDescription') }}+ </p>++ <!-- metadata row -->+ <div class="flex flex-wrap items-center gap-4 text-sm">+ <!-- Photos -->+ <div class="flex items-center gap-1">+ <Icon+ name="tabler:photo"+ class="size-4 -mt-0.5 text-neutral-400 dark:text-neutral-500"+ />+ <span class="text-neutral-700 dark:text-neutral-200">+ <span class="text-neutral-900 dark:text-white">+ {{ albumStats?.total || 0 }}+ </span>+ <span class="text-neutral-500 dark:text-neutral-400 ml-1">+ {{ $t('album.metadata.photos') }}+ </span>+ </span>+ </div>++ <!-- Date Range -->+ <div+ v-if="dateRangeText"+ class="flex items-center gap-1"+ >+ <Icon+ name="tabler:calendar"+ class="size-4 -mt-0.5 text-neutral-400 dark:text-neutral-500"+ />+ <span class="text-neutral-700 dark:text-neutral-200">+ {{ dateRangeText }}+ </span>+ </div>++ <!-- Created -->+ <div+ class="flex items-center gap-1"+ :title="`Created: ${$dayjs(albumData.createdAt).format('YYYY-MM-DD HH:mm:ss')}`"+ >+ <Icon+ name="tabler:clock-plus"+ class="size-4 -mt-0.5 text-neutral-400 dark:text-neutral-500"+ />+ <span class="text-neutral-700 dark:text-neutral-200">+ {{ $t('album.metadata.created') }} {{ $dayjs(albumData.createdAt).fromNow() }}+ </span>+ </div>+ </div>+ </div>+ </motion.div>+ </AnimatePresence>+ </div>++ <!-- Photos Waterfall or Empty State -->+ <div class="container mx-auto px-4 sm:px-6 lg:px-8 py-12">+ <motion.div+ :initial="{ opacity: 0 }"+ :animate="{ opacity: 1 }"+ :transition="{ delay: 0.2, duration: 0.4 }"+ >+ <div+ v-if="albumStats?.total === 0"+ class="flex flex-col items-center justify-center gap-6 px-4"+ >+ <div class="flex flex-col items-center gap-4">+ <Icon+ name="tabler:library-photo"+ class="size-20 text-neutral-300 dark:text-neutral-600"+ />+ <div class="text-center">+ <p class="text-xl font-normal text-neutral-800 dark:text-neutral-200 mb-2">+ {{ $t('album.emptyAlbumTitle') }}+ </p>+ </div>+ </div>+ </div>++ <MasonryWall+ v-else+ :items="masonryItems"+ :column-width="columnWidth"+ :gap="MASONRY_GAP"+ :min-columns="minColumns"+ :max-columns="maxColumns"+ :ssr-columns="2"+ :key-mapper="+ (_item, _column, _row, index) =>+ masonryItems[index]?.originalIndex ?? index+ "+ >+ <template #default="{ item }">+ <MasonryItem+ v-if="item.photo && typeof item.originalIndex === 'number'"+ :key="item.photo.id"+ :photo="item.photo"+ :index="item.originalIndex"+ :has-animated="false"+ :first-screen-items="50"+ @open-viewer="handleOpenViewer($event)"+ />+ </template>+ </MasonryWall>+ </motion.div>+ </div>+ </template>++ <template v-else>+ <div class="flex flex-col items-center justify-center min-h-[50vh] gap-6">+ <div class="flex flex-col items-center gap-4">+ <Icon+ name="tabler:alert-circle"+ class="size-20 text-red-400"+ />+ <div class="text-center">+ <p class="text-2xl font-semibold text-neutral-800 dark:text-neutral-200 mb-2">+ {{ $t('album.failedToLoadTitle') }}+ </p>+ <p class="text-base text-neutral-600 dark:text-neutral-400 max-w-md">+ {{ $t('album.failedToLoadDescription') }}+ </p>+ </div>+ </div>+ <UButton @click="goBackToAlbums">+ {{ $t('album.backToAlbums') }}+ </UButton>+ </div>+ </template></div></template>-<style scoped>--</style>+<style scoped></style>diff --git a/app/pages/albums/index.vue b/app/pages/albums/index.vueindex 4593f687..eb7339bf 100644--- a/app/pages/albums/index.vue+++ b/app/pages/albums/index.vue@@ -3,7 +3,14 @@ import { motion } from 'motion-v'const config = useRuntimeConfig()const { photos } = usePhotos()-const { data: albums } = useAsyncData(() => $fetch('/api/albums'))+const { data: albums } = useAsyncData(+ 'albums',+ // @ts-nocheck+ () => $fetch('/api/albums'),+ {+ watch: [],+ },+)// randomly pick 30 photos for waterfallconst waterfallPhotos = computed(() =>@@ -51,29 +58,31 @@ const getPhotoById = (photoId: string) => {}const getAlbumDisplayPhotos = (album: any) => {- if (!album.photos || album.photos.length === 0) return []+ if (!album.photoIds || album.photoIds.length === 0) return []const displayPhotos = []// 第一张:优先使用封面照片if (album.coverPhotoId) {- const coverPhoto =- getPhotoById(album.coverPhotoId) ||- album.photos.find((p: any) => p.id === album.coverPhotoId)+ const coverPhoto = getPhotoById(album.coverPhotoId)if (coverPhoto) {displayPhotos.push(coverPhoto)}}// 如果没有封面照片或封面照片不存在,使用第一张- if (displayPhotos.length === 0 && album.photos[0]) {- displayPhotos.push(album.photos[0])+ if (displayPhotos.length === 0 && album.photoIds[0]) {+ const firstPhoto = getPhotoById(album.photoIds[0])+ if (firstPhoto) {+ displayPhotos.push(firstPhoto)+ }}// 添加其他照片(最多3张)- for (const photo of album.photos) {+ for (const photoId of album.photoIds) {if (displayPhotos.length >= 3) break- if (!displayPhotos.find((p) => p.id === photo.id)) {+ const photo = getPhotoById(photoId)+ if (photo && !displayPhotos.find((p) => p.id === photo.id)) {displayPhotos.push(photo)}}@@ -98,7 +107,7 @@ const getPhotoTransform = (index: number, isHover: boolean) => {}}-const hoveredAlbum = ref<string | null>(null)+const hoveredAlbum = ref<number | null>(null)</script><template>@@ -134,16 +143,18 @@ const hoveredAlbum = ref<string | null>(null):key="`${photo.id}-${groupIndex}-${photoIndex}`"class="w-full overflow-hidden">- <ThumbImage- class="w-full h-auto object-cover saturate-50"- :lazy="false"- :src="photo.thumbnailUrl!"- :thumbhash="photo.thumbnailHash"- :alt="photo.exif?.ImageDescription || 'Photo'"- :style="{- aspectRatio: photo.aspectRatio || 1,- }"- />+ <ClientOnly>+ <ThumbImage+ class="w-full h-auto object-cover saturate-50"+ :lazy="false"+ :src="photo.thumbnailUrl!"+ :thumbhash="photo.thumbnailHash"+ :alt="photo.exif?.ImageDescription || 'Photo'"+ :style="{+ aspectRatio: photo.aspectRatio || 1,+ }"+ />+ </ClientOnly></div></template></div>@@ -162,7 +173,7 @@ const hoveredAlbum = ref<string | null>(null)variant="ghost"color="neutral"icon="tabler:arrow-left"- label="Back to Home"+ :label="$t('ui.action.home.tooltip')"size="sm"to="/"/>@@ -174,7 +185,7 @@ const hoveredAlbum = ref<string | null>(null)<h1class="font-black text-6xl sm:text-7xl drop-shadow-2xl bg-clip-text bg-gradient-to-br from-neutral-800 to-neutral-400 dark:from-white dark:to-neutral-500 text-transparent">- {{ 'Albums'.toUpperCase() }}+ {{ $t('title.albums').toUpperCase() }}</h1><pclass="mt-2 text-lg text-neutral-600 dark:text-neutral-400 font-medium font-[Pacifico]"@@ -197,7 +208,7 @@ const hoveredAlbum = ref<string | null>(null)@mouseleave="hoveredAlbum = null"><!-- Stacked Photos Card -->- <div class="relative h-48 mb-4">+ <div class="relative h-48 mb-4 group"><!-- Photo Stack (3 layers) --><motion.divv-for="(photo, index) in getAlbumDisplayPhotos(album)"@@ -228,7 +239,7 @@ const hoveredAlbum = ref<string | null>(null)><ThumbImageclass="w-full h-full object-cover"- :src="photo.thumbnailUrl"+ :src="photo.thumbnailUrl!":thumbhash="photo.thumbnailHash":alt="album.title":style="{@@ -247,12 +258,23 @@ const hoveredAlbum = ref<string | null>(null)<!-- Empty state --><div- v-if="!album.photos || album.photos.length === 0"- class="absolute inset-0 rounded-xl shadow-lg bg-neutral-200 dark:bg-neutral-700 flex items-center justify-center"+ v-if="!album.photoIds || album.photoIds.length === 0"+ class="absolute inset-0 rounded-xl shadow-lg bg-gradient-to-br from-neutral-100 to-neutral-50 dark:from-neutral-700 dark:to-neutral-800 flex flex-col items-center justify-center gap-3 border border-neutral-200 dark:border-neutral-600 group-hover:shadow-xl dark:group-hover:shadow-neutral-900/50 transition-shadow">- <span class="text-neutral-500 dark:text-neutral-400">- No Image- </span>+ <Icon+ name="tabler:library-photo"+ class="size-10 text-neutral-400 dark:text-neutral-500"+ />+ <div class="text-center">+ <p+ class="text-sm font-medium text-neutral-700 dark:text-neutral-300"+ >+ {{ $t('ui.album.noImage') }}+ </p>+ <!-- <p class="text-xs text-neutral-500 dark:text-neutral-400 mt-1">+ {{ $t('ui.album.emptyAlbumTip') }}+ </p> -->+ </div></div></div>@@ -283,7 +305,7 @@ const hoveredAlbum = ref<string | null>(null)<pclass="text-sm text-neutral-600 dark:text-neutral-400 line-clamp-2">- {{ album.description || 'No description' }}+ {{ album.description || $t('ui.album.noDescription') }}</p></div></div>diff --git a/app/pages/dashboard/albums.vue b/app/pages/dashboard/albums.vuenew file mode 100644index 00000000..1caffa76--- /dev/null+++ b/app/pages/dashboard/albums.vue@@ -0,0 +1,961 @@+<script lang="ts" setup>+import type { Album, Photo } from '~~/server/utils/db'+import type { FormSubmitEvent, FormError } from '@nuxt/ui'++definePageMeta({+ layout: 'dashboard',+})++useHead({+ title: $t('title.albums'),+})++interface AlbumItem extends Album {+ photoCount?: number+ photoIds?: string[]+ coverPhoto?: Photo | null+}++interface AlbumFormState {+ title: string+ description: string+}++const albums = ref<AlbumItem[]>([])+const isLoadingAlbums = ref(false)+const allPhotos = ref<Photo[]>([])+const isLoadingPhotos = ref(false)++const isAlbumSlideoverOpen = ref(false)+const isDeleteConfirmOpen = ref(false)+const isPhotoSelectorOpen = ref(false)++const currentAlbum = ref<AlbumItem | null>(null)++const formData = reactive<AlbumFormState>({+ title: '',+ description: '',+})++const formRef = ref()+const isSubmittingForm = ref(false)++const selectedPhotoIds = ref<string[]>([])+const coverPhotoId = ref('')+const photoSelectorSearchQuery = ref('')++const validateForm = (state: any): FormError[] => {+ const errors: FormError[] = []+ if (!state.title?.trim()) {+ errors.push({+ name: 'title',+ message: $t('dashboard.albums.form.titleRequired'),+ })+ }+ return errors+}++const loadAlbums = async () => {+ isLoadingAlbums.value = true+ try {+ const response = await $fetch('/api/albums')+ albums.value = (response as any[]).map((album) => ({+ ...album,+ photoCount: album.photoIds?.length || 0,+ }))++ for (const album of albums.value) {+ if (album.coverPhotoId && allPhotos.value.length > 0) {+ const coverPhoto = allPhotos.value.find(+ (p) => p.id === album.coverPhotoId,+ )+ if (coverPhoto) {+ album.coverPhoto = coverPhoto+ }+ }+ }+ } catch (error) {+ console.error('Failed to load albums:', error)+ useToast().add({+ title: $t('dashboard.albums.messages.loadError'),+ color: 'error',+ })+ } finally {+ isLoadingAlbums.value = false+ }+}++const loadPhotos = async () => {+ isLoadingPhotos.value = true+ try {+ const { photos } = usePhotos()+ allPhotos.value = photos.value+ } catch (error) {+ console.error('Failed to load photos:', error)+ } finally {+ isLoadingPhotos.value = false+ }+}++const openCreateSlideover = () => {+ currentAlbum.value = null+ formData.title = ''+ formData.description = ''+ selectedPhotoIds.value = []+ coverPhotoId.value = ''+ formRef.value?.clear()+ isAlbumSlideoverOpen.value = true+}++const openEditSlideover = async (album: AlbumItem) => {+ currentAlbum.value = album+ try {+ const albumDetail = (await $fetch(`/api/albums/${album.id}`)) as any+ formData.title = album.title+ formData.description = album.description || ''+ selectedPhotoIds.value = (albumDetail.photos || []).map((p: Photo) => p.id)+ coverPhotoId.value = album.coverPhotoId || ''+ formRef.value?.clear()+ } catch (error) {+ console.error('Failed to load album details:', error)+ useToast().add({+ title: $t('dashboard.albums.messages.loadDetailError'),+ color: 'error',+ })+ }+ isAlbumSlideoverOpen.value = true+}++const openDeleteConfirm = (album: AlbumItem) => {+ currentAlbum.value = album+ isDeleteConfirmOpen.value = true+}++const onFormSubmit = async (event: FormSubmitEvent<AlbumFormState>) => {+ isSubmittingForm.value = true+ try {+ if (currentAlbum.value) {+ await $fetch(`/api/albums/${currentAlbum.value.id}`, {+ method: 'PUT',+ body: {+ title: event.data.title,+ description: event.data.description || undefined,+ coverPhotoId: coverPhotoId.value || undefined,+ photoIds: selectedPhotoIds.value,+ },+ })++ useToast().add({+ title: $t('dashboard.albums.messages.updateSuccess'),+ color: 'success',+ })++ isAlbumSlideoverOpen.value = false+ } else {+ await $fetch('/api/albums', {+ method: 'POST',+ body: {+ title: event.data.title,+ description: event.data.description || undefined,+ coverPhotoId: coverPhotoId.value || undefined,+ photoIds: selectedPhotoIds.value,+ },+ })++ useToast().add({+ title: $t('dashboard.albums.messages.createSuccess'),+ color: 'success',+ })++ isAlbumSlideoverOpen.value = false+ }++ await loadAlbums()+ } catch (error) {+ console.error('Failed to save album:', error)+ useToast().add({+ title: currentAlbum.value+ ? $t('dashboard.albums.messages.updateError')+ : $t('dashboard.albums.messages.createError'),+ color: 'error',+ })+ } finally {+ isSubmittingForm.value = false+ }+}++const deleteAlbum = async () => {+ if (!currentAlbum.value) return++ try {+ await $fetch(`/api/albums/${currentAlbum.value.id}`, {+ method: 'DELETE',+ })++ useToast().add({+ title: $t('dashboard.albums.messages.deleteSuccess'),+ color: 'success',+ })++ isDeleteConfirmOpen.value = false+ await loadAlbums()+ } catch (error) {+ console.error('Failed to delete album:', error)+ useToast().add({+ title: $t('dashboard.albums.messages.deleteError'),+ color: 'error',+ })+ }+}++const togglePhotoSelection = (photoId: string) => {+ const index = selectedPhotoIds.value.indexOf(photoId)+ if (index > -1) {+ selectedPhotoIds.value.splice(index, 1)+ if (coverPhotoId.value === photoId) {+ coverPhotoId.value = ''+ }+ } else {+ selectedPhotoIds.value.push(photoId)+ }+}++const setCoverPhoto = (photoId: string) => {+ if (!selectedPhotoIds.value.includes(photoId)) {+ selectedPhotoIds.value.push(photoId)+ }+ coverPhotoId.value = photoId+}++const areAllPhotosSelected = computed(() => {+ return (+ allPhotos.value.length > 0 &&+ selectedPhotoIds.value.length === allPhotos.value.length+ )+})++const areSomePhotosSelected = computed(() => {+ return (+ selectedPhotoIds.value.length > 0 &&+ selectedPhotoIds.value.length < allPhotos.value.length+ )+})++const toggleAllPhotos = () => {+ if (areAllPhotosSelected.value) {+ selectedPhotoIds.value = []+ } else {+ selectedPhotoIds.value = allPhotos.value.map((p) => p.id)+ }+}++const filteredPhotos = computed(() => {+ const query = photoSelectorSearchQuery.value.toLowerCase()+ if (!query) return allPhotos.value++ return allPhotos.value.filter(+ (photo) =>+ (photo.title?.toLowerCase() || '').includes(query) ||+ (photo.description?.toLowerCase() || '').includes(query),+ )+})++onMounted(async () => {+ await Promise.all([loadPhotos(), loadAlbums()])+})++const dayjs = useDayjs()++const slideoverTitle = computed(() => {+ return currentAlbum.value+ ? $t('dashboard.albums.slideover.edit.title')+ : $t('dashboard.albums.slideover.create.title')+})++const slideoverDescription = computed(() => {+ return currentAlbum.value+ ? $t('dashboard.albums.slideover.edit.description')+ : $t('dashboard.albums.slideover.create.description')+})++const submitButtonLabel = computed(() => {+ return currentAlbum.value+ ? $t('dashboard.albums.slideover.submitEdit')+ : $t('dashboard.albums.slideover.submitCreate')+})++const columns: any[] = [+ {+ id: 'coverPhoto',+ accessorKey: 'coverPhoto',+ header: $t('dashboard.albums.table.columns.cover'),+ },+ {+ id: 'title',+ accessorKey: 'title',+ header: $t('dashboard.albums.table.columns.title'),+ },+ {+ id: 'description',+ accessorKey: 'description',+ header: $t('dashboard.albums.table.columns.description'),+ },+ {+ id: 'photoCount',+ accessorKey: 'photoCount',+ header: $t('dashboard.albums.table.columns.photoCount'),+ },+ {+ id: 'createdAt',+ accessorKey: 'createdAt',+ header: $t('dashboard.albums.table.columns.createdAt'),+ },+ {+ id: 'actions',+ header: $t('dashboard.albums.table.columns.actions'),+ },+]+</script>++<template>+ <div class="flex flex-col gap-6 h-full p-4">+ <div class="flex items-center justify-between">+ <div>+ <h1 class="text-2xl font-bold">{{ $t('dashboard.albums.title') }}</h1>+ <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">+ {{ $t('dashboard.albums.subtitle') }}+ </p>+ </div>+ <UButton+ icon="tabler:plus"+ @click="openCreateSlideover"+ >+ {{ $t('dashboard.albums.createButton') }}+ </UButton>+ </div>++ <div+ v-if="albums.length > 0"+ class="bg-white dark:bg-neutral-900 rounded-lg border border-gray-200 dark:border-neutral-800"+ >+ <UTable+ :data="albums"+ :columns="columns"+ >+ <template #coverPhoto-cell="{ row }">+ <div+ class="w-16 h-12 rounded-lg overflow-hidden bg-gray-100 dark:bg-neutral-800 flex-shrink-0"+ >+ <img+ v-if="(row.original as unknown as AlbumItem).coverPhoto"+ :src="+ (row.original as unknown as AlbumItem).coverPhoto+ ?.thumbnailUrl || ''+ "+ :alt="(row.original as unknown as AlbumItem).title"+ class="w-full h-full object-cover"+ />+ <div+ v-else+ class="w-full h-full flex items-center justify-center text-gray-400 dark:text-gray-600"+ >+ <Icon+ name="tabler:image"+ size="20"+ />+ </div>+ </div>+ </template>++ <template #title-cell="{ row }">+ <NuxtLink+ :to="`/albums/${(row.original as unknown as AlbumItem).id}`"+ target="_blank"+ class="font-medium text-primary-600 dark:text-primary-400 hover:underline cursor-pointer inline-flex items-center gap-2"+ >+ {{ (row.original as unknown as AlbumItem).title }}+ <Icon+ name="tabler:external-link"+ size="16"+ class="flex-shrink-0 opacity-60 hover:opacity-100 transition-opacity"+ />+ </NuxtLink>+ </template>++ <template #description-cell="{ row }">+ <div+ v-if="(row.original as unknown as AlbumItem).description"+ class="text-sm text-gray-600 dark:text-gray-400 line-clamp-1"+ >+ {{ (row.original as unknown as AlbumItem).description }}+ </div>+ <div+ v-else+ class="text-sm text-gray-400 dark:text-gray-600"+ >+ -+ </div>+ </template>++ <template #photoCount-cell="{ row }">+ <UBadge+ variant="soft"+ color="neutral"+ >+ {{ (row.original as unknown as AlbumItem).photoCount || 0 }} 张+ </UBadge>+ </template>++ <template #createdAt-cell="{ row }">+ <div class="text-sm text-gray-600 dark:text-gray-400">+ {{+ dayjs((row.original as unknown as AlbumItem).createdAt).format(+ 'YYYY-MM-DD',+ )+ }}+ </div>+ </template>++ <template #actions-cell="{ row }">+ <div class="flex gap-1">+ <UButton+ variant="ghost"+ color="primary"+ size="xs"+ icon="tabler:edit"+ @click="openEditSlideover(row.original as unknown as AlbumItem)"+ />+ <UButton+ variant="ghost"+ color="error"+ size="xs"+ icon="tabler:trash"+ @click="openDeleteConfirm(row.original as unknown as AlbumItem)"+ />+ </div>+ </template>+ </UTable>+ </div>++ <div+ v-else-if="!isLoadingAlbums"+ class="flex flex-col items-center justify-center py-12 text-center"+ >+ <Icon+ name="tabler:album"+ size="48"+ class="text-gray-400 dark:text-gray-600 mb-4"+ />+ <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-300">+ {{ $t('dashboard.albums.noAlbums') }}+ </h3>+ <p class="text-sm text-gray-500 dark:text-gray-400 mt-2 mb-4">+ {{ $t('dashboard.albums.noAlbumsTip') }}+ </p>+ <UButton+ icon="tabler:plus"+ @click="openCreateSlideover"+ >+ {{ $t('dashboard.albums.createButton') }}+ </UButton>+ </div>+ <div+ v-else+ class="flex items-center justify-center py-12"+ >+ <Icon+ name="tabler:loader"+ size="32"+ class="animate-spin text-primary-500"+ />+ </div>++ <USlideover+ v-model:open="isAlbumSlideoverOpen"+ :title="slideoverTitle"+ :description="slideoverDescription"+ :ui="{ footer: 'justify-end', body: 'p-0 sm:p-0 space-y-4' }"+ >+ <template #body>+ <div+ v-if="coverPhotoId"+ class="relative w-full aspect-video bg-gray-100 dark:bg-neutral-800 overflow-hidden"+ >+ <ThumbImage+ :src="+ allPhotos.find((p) => p.id === coverPhotoId)?.thumbnailUrl || ''+ "+ :alt="coverPhotoId"+ class="absolute inset-0 w-full h-full object-cover"+ />+ <button+ class="absolute inset-0 bg-black/50 opacity-0 hover:opacity-100 transition-opacity flex items-center justify-center"+ @click="coverPhotoId = ''"+ >+ <Icon+ name="tabler:x"+ class="text-white"+ />+ </button>+ </div>+ <button+ v-else+ class="w-full h-48 bg-gray-100 dark:bg-neutral-800 flex flex-col items-center justify-center text-gray-500 hover:text-gray-600 dark:hover:text-gray-400 hover:bg-gray-200 dark:hover:bg-neutral-700 transition-colors cursor-pointer"+ @click="isPhotoSelectorOpen = true"+ >+ <Icon+ name="tabler:photo"+ size="40"+ class="mb-2"+ />+ <p class="text-sm font-medium">+ {{ $t('dashboard.albums.form.addCoverPhoto') }}+ </p>+ </button>+ <div class="space-y-4 px-4">+ <UForm+ ref="formRef"+ :state="formData"+ :validate="validateForm"+ class="space-y-4"+ @submit="onFormSubmit"+ >+ <UFormField+ :label="$t('dashboard.albums.form.title')"+ name="title"+ required+ >+ <UInput+ v-model="formData.title"+ class="w-full"+ :placeholder="$t('dashboard.albums.form.titlePlaceholder')"+ />+ </UFormField>++ <UFormField+ :label="$t('dashboard.albums.form.description')"+ name="description"+ >+ <UTextarea+ v-model="formData.description"+ class="w-full"+ :placeholder="+ $t('dashboard.albums.form.descriptionPlaceholder')+ "+ :rows="3"+ />+ </UFormField>+ </UForm>++ <!-- 照片选择部分 -->+ <div class="space-y-3">+ <UButton+ variant="outline"+ color="primary"+ icon="tabler:photo-plus"+ size="lg"+ class="w-full"+ @click="isPhotoSelectorOpen = true"+ >+ {{+ selectedPhotoIds.length > 0+ ? $t('dashboard.albums.form.editPhotos')+ : $t('dashboard.albums.form.selectPhotos')+ }}+ </UButton>++ <div+ v-if="selectedPhotoIds.length > 0"+ class="space-y-2"+ >+ <div class="flex items-center justify-between">+ <label+ class="text-sm font-medium text-gray-700 dark:text-gray-300"+ >{{+ $t('dashboard.albums.form.selectedCount', {+ count: selectedPhotoIds.length,+ })+ }}</label+ >+ <UButton+ variant="ghost"+ color="neutral"+ size="xs"+ icon="tabler:trash"+ @click="selectedPhotoIds = []"+ >+ {{ $t('dashboard.albums.form.clearAll') }}+ </UButton>+ </div>++ <div+ class="grid grid-cols-4 gap-2 p-3 bg-gray-50 dark:bg-neutral-800/50 rounded-lg border border-gray-200 dark:border-neutral-700"+ >+ <div+ v-for="photoId in selectedPhotoIds"+ :key="photoId"+ class="relative group aspect-square rounded-lg overflow-hidden bg-gray-200 dark:bg-neutral-700"+ >+ <img+ :src="+ allPhotos.find((p) => p.id === photoId)?.thumbnailUrl ||+ ''+ "+ :alt="photoId"+ class="w-full h-full object-cover"+ />++ <div+ v-if="coverPhotoId === photoId"+ class="absolute top-1 left-1 bg-primary-500 text-white px-1.5 py-0.5 rounded text-xs font-medium"+ >+ {{ $t('dashboard.albums.modal.setCover') }}+ </div>++ <button+ class="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"+ @click="togglePhotoSelection(photoId)"+ >+ <Icon+ name="tabler:x"+ class="text-white"+ />+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>+ </template>++ <template #footer="{ close }">+ <UButton+ variant="ghost"+ color="neutral"+ @click="close"+ >+ {{ $t('dashboard.albums.slideover.cancel') }}+ </UButton>+ <UButton+ icon="tabler:check"+ :loading="isSubmittingForm"+ @click="formRef?.submit()"+ >+ {{ submitButtonLabel }}+ </UButton>+ </template>+ </USlideover>++ <UModal+ v-model:open="isPhotoSelectorOpen"+ :ui="{ content: 'w-full max-w-6xl overflow-hidden' }"+ >+ <template #content>+ <div class="flex flex-col h-[85vh] max-h-[85vh]">+ <div+ class="flex-shrink-0 border-b border-gray-200 dark:border-neutral-700 p-3 sm:p-4 md:p-6"+ >+ <div class="flex items-center justify-between mb-3 sm:mb-4">+ <div>+ <h2 class="text-lg sm:text-xl font-bold">+ {{ $t('dashboard.albums.modal.selectPhotos') }}+ </h2>+ <p+ class="text-xs sm:text-sm text-gray-500 dark:text-gray-400 mt-1"+ >+ {{+ $t('dashboard.albums.modal.totalPhotos', {+ count: allPhotos.length,+ })+ }}+ ·+ {{+ $t('dashboard.albums.modal.selectedPhotos', {+ count: selectedPhotoIds.length,+ })+ }}+ </p>+ </div>+ <UButton+ variant="ghost"+ color="neutral"+ size="md"+ icon="tabler:x"+ @click="isPhotoSelectorOpen = false"+ />+ </div>++ <div+ class="flex flex-col sm:flex-row gap-2 items-stretch sm:items-center"+ >+ <UInput+ v-model="photoSelectorSearchQuery"+ icon="tabler:search"+ :placeholder="$t('dashboard.albums.modal.searchPlaceholder')"+ class="flex-1 text-sm"+ />+ <div+ class="hidden sm:flex items-center gap-2 px-3 py-2 bg-gray-100 dark:bg-neutral-800 rounded-lg whitespace-nowrap"+ >+ <UCheckbox+ :model-value="areAllPhotosSelected"+ :indeterminate="areSomePhotosSelected"+ @update:model-value="toggleAllPhotos"+ />+ <span class="text-sm font-medium">{{+ $t('dashboard.albums.modal.selectAll')+ }}</span>+ </div>+ <UButton+ v-show="!areAllPhotosSelected && allPhotos.length > 0"+ class="sm:hidden"+ size="sm"+ color="neutral"+ variant="soft"+ @click="toggleAllPhotos"+ >+ {{ $t('dashboard.albums.modal.selectAll') }}+ </UButton>+ </div>++ <div+ v-if="photoSelectorSearchQuery"+ class="text-xs text-gray-500 dark:text-gray-400 mt-2"+ >+ {{+ $t('dashboard.albums.modal.searchResults', {+ current: filteredPhotos.length,+ total: allPhotos.length,+ })+ }}+ </div>+ </div>++ <div class="flex-1 overflow-y-auto p-2 sm:p-3 md:p-6">+ <div+ v-if="filteredPhotos.length > 0"+ class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-2 sm:gap-3"+ >+ <div+ v-for="photo in filteredPhotos"+ :key="photo.id"+ class="relative group cursor-pointer"+ @click="togglePhotoSelection(photo.id)"+ >+ <div+ class="relative aspect-square rounded-lg overflow-hidden bg-gray-200 dark:bg-neutral-700 border-2 sm:border-3 transition-all"+ :class="{+ 'border-primary-500 shadow-lg ring-2 ring-primary-300 dark:ring-primary-700':+ selectedPhotoIds.includes(photo.id),+ 'border-gray-300 dark:border-neutral-600 hover:border-gray-400 dark:hover:border-neutral-500':+ !selectedPhotoIds.includes(photo.id),+ }"+ >+ <ThumbImage+ :src="photo.thumbnailUrl || ''"+ :alt="photo.title || 'Photo'"+ class="w-full h-full object-cover"+ />++ <div+ v-if="selectedPhotoIds.includes(photo.id)"+ class="absolute top-1 left-1 sm:top-2 sm:left-2 flex items-center justify-center w-5 h-5 sm:w-6 sm:h-6 rounded-full bg-primary-500 border-2 border-white shadow-md"+ >+ <Icon+ name="tabler:check"+ size="12"+ class="text-white sm:hidden"+ />+ <Icon+ name="tabler:check"+ size="14"+ class="text-white hidden sm:block"+ />+ </div>++ <UBadge+ v-if="coverPhotoId === photo.id"+ class="absolute top-1 right-1 sm:top-2 sm:right-2"+ variant="solid"+ color="warning"+ size="sm"+ >+ <Icon+ name="tabler:star-filled"+ class="inline mr-0.5"+ size="14"+ />+ {{ $t('dashboard.albums.modal.setCover') }}+ </UBadge>+ <UButton+ v-if="coverPhotoId !== photo.id"+ class="absolute bottom-1 right-1 sm:bottom-2 sm:right-2 opacity-0 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity"+ variant="solid"+ color="warning"+ size="xs"+ @click.stop="setCoverPhoto(photo.id)"+ >+ <Icon+ name="tabler:star"+ class="inline"+ size="12"+ />+ <span class="hidden sm:inline ml-1">{{+ $t('dashboard.albums.modal.setCover')+ }}</span>+ </UButton>++ <button+ v-if="coverPhotoId !== photo.id"+ class="sm:hidden absolute bottom-0 right-0 left-0 bg-gradient-to-t from-black/80 to-transparent p-1 text-white flex items-center justify-center text-xs gap-1 rounded-b-lg"+ @click.stop="setCoverPhoto(photo.id)"+ >+ <Icon+ name="tabler:star"+ size="14"+ />+ <span>{{ $t('dashboard.albums.modal.setCover') }}</span>+ </button>+ </div>+ </div>+ </div>++ <div+ v-else+ class="flex flex-col items-center justify-center h-64 text-gray-500"+ >+ <Icon+ name="tabler:image-off"+ size="48"+ class="mb-3 opacity-50"+ />+ <p class="font-medium">+ {{+ photoSelectorSearchQuery+ ? $t('dashboard.albums.modal.noResults')+ : $t('dashboard.albums.modal.noPhotos')+ }}+ </p>+ <p+ v-if="photoSelectorSearchQuery"+ class="text-sm mt-1"+ >+ {{ $t('dashboard.albums.modal.tryOtherKeywords') }}+ </p>+ </div>+ </div>++ <div+ class="flex-shrink-0 border-t border-gray-200 dark:border-neutral-700 bg-gray-50 dark:bg-neutral-900/50 p-3 sm:p-4 md:p-6"+ >+ <div+ class="flex flex-col sm:flex-row gap-3 sm:gap-4 items-center justify-between"+ >+ <div+ class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-4 text-xs sm:text-sm w-full sm:w-auto"+ >+ <div>+ <span class="font-medium">{{+ $t('dashboard.albums.modal.selectedInfo')+ }}</span>+ <span+ class="text-primary-600 dark:text-primary-400 font-bold"+ >+ {{ selectedPhotoIds.length }}+ </span>+ <span class="text-gray-600 dark:text-gray-400"+ >/ {{ allPhotos.length }}</span+ >+ </div>+ <div+ v-if="coverPhotoId"+ class="text-amber-600 dark:text-amber-400 flex items-center gap-1"+ >+ <Icon+ name="tabler:star-filled"+ size="16"+ />+ {{ $t('dashboard.albums.modal.coverSetInfo') }}+ </div>+ </div>++ <div class="flex gap-2 w-full sm:w-auto">+ <UButton+ variant="outline"+ color="neutral"+ class="flex-1 sm:flex-none"+ size="sm"+ @click="isPhotoSelectorOpen = false"+ >+ {{ $t('dashboard.albums.slideover.cancel') }}+ </UButton>+ <UButton+ icon="tabler:check"+ color="primary"+ class="flex-1 sm:flex-none"+ size="sm"+ :disabled="selectedPhotoIds.length === 0"+ @click="isPhotoSelectorOpen = false"+ >+ {{+ $t('dashboard.albums.modal.confirm', {+ count: selectedPhotoIds.length,+ })+ }}+ </UButton>+ </div>+ </div>+ </div>+ </div>+ </template>+ </UModal>++ <UModal v-model:open="isDeleteConfirmOpen">+ <template #content>+ <div class="p-6 space-y-4">+ <div class="flex items-center gap-3">+ <div+ class="flex-shrink-0 w-10 h-10 bg-error-100 dark:bg-error-900/30 rounded-full flex items-center justify-center"+ >+ <Icon+ name="tabler:alert-circle"+ class="text-error-500"+ />+ </div>+ <div>+ <h3 class="text-lg font-semibold">+ {{ $t('dashboard.albums.delete.title') }}+ </h3>+ <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">+ {{+ $t('dashboard.albums.delete.message', {+ title: currentAlbum?.title,+ })+ }}+ </p>+ </div>+ </div>++ <div class="flex justify-end gap-2 pt-4">+ <UButton+ variant="ghost"+ color="neutral"+ @click="isDeleteConfirmOpen = false"+ >+ {{ $t('dashboard.albums.delete.cancel') }}+ </UButton>+ <UButton+ color="error"+ icon="tabler:trash"+ @click="deleteAlbum"+ >+ {{ $t('dashboard.albums.delete.confirm') }}+ </UButton>+ </div>+ </div>+ </template>+ </UModal>+ </div>+</template>++<style scoped></style>diff --git a/i18n/locales/en.json b/i18n/locales/en.jsonindex c8909d34..40a114c8 100644--- a/i18n/locales/en.json+++ b/i18n/locales/en.json@@ -50,6 +50,9 @@"globe": {"tooltip": "Globe"},+ "home": {+ "tooltip": "Back to Home"+ },"share": {"tooltip": "Share Photo","title": "Share Photo",@@ -105,7 +108,31 @@"noPhotosTip": "Nno photos yet, upload some now!"},"livePhoto": "Live Photo",- "indexPanelCountCity":"and more other cities"+ "indexPanelCountCity":"and more other cities",+ "album": {+ "noImage": "Empty Album",+ "emptyAlbumTip": "Add photos to get started",+ "noDescription": "No description"+ }+ },+ "album": {+ "notFound": "Album not found",+ "noDateInfo": "No date info",+ "noPhotosTip": "No photos in this album yet",+ "emptyAlbumTitle": "This Album Is Empty",+ "emptyAlbumDescription": "More wonderful moments will be presented here.",+ "failedToLoadTitle": "Failed to Load Album",+ "failedToLoadDescription": "An error occurred while loading this album.",+ "failedToLoad": "Failed to load album",+ "backToAlbums": "Back to Albums",+ "noDescription": "No description provided",+ "photo": "no photos | one photo | {count} photos",+ "createdAt": "Created {time}",+ "metadata": {+ "photos": "Photos",+ "dateRange": "Date Range",+ "created": "Created"+ }},"map": {"cluster": {@@ -321,7 +348,8 @@"locations": "Locations","globe": "Photo Globe","queue": "Queue Management",- "logs": "System Logs"+ "logs": "System Logs",+ "albums": "Albums"},"auth": {"form": {@@ -432,6 +460,81 @@}},"dashboard": {+ "albums": {+ "title": "Album Management",+ "subtitle": "Create and manage your photo albums",+ "createButton": "Create Album",+ "noAlbums": "No albums yet",+ "noAlbumsTip": "Create your first album to organize your photos",+ "form": {+ "title": "Title",+ "titlePlaceholder": "Enter album title",+ "titleRequired": "Please enter album title",+ "description": "Description",+ "descriptionPlaceholder": "Enter album description (optional)",+ "coverPhoto": "Album Cover",+ "addCoverPhoto": "Add cover photo",+ "selectPhotos": "Select Photos",+ "editPhotos": "Edit photo selection",+ "selectedCount": "Selected {count} photos",+ "clearAll": "Clear all"+ },+ "table": {+ "columns": {+ "cover": "Cover",+ "title": "Title",+ "description": "Description",+ "photoCount": "Photos",+ "createdAt": "Created at",+ "actions": "Actions"+ }+ },+ "modal": {+ "selectPhotos": "Select Photos",+ "totalPhotos": "Total {count} photos",+ "selectedPhotos": "Selected {count} photos",+ "searchPlaceholder": "Search photos...",+ "searchResults": "Results: {current} / {total}",+ "selectAll": "Select All",+ "setCover": "Set as cover",+ "noPhotos": "No photos",+ "noResults": "No matching photos found",+ "tryOtherKeywords": "Try other keywords",+ "confirm": "Confirm ({count})",+ "selectedInfo": "Selected:",+ "coverSetInfo": "Cover set"+ },+ "slideover": {+ "create": {+ "title": "Create Album",+ "description": "Create a new album to organize your photos"+ },+ "edit": {+ "title": "Edit Album",+ "description": "Modify album information and photos"+ },+ "submitCreate": "Create",+ "submitEdit": "Save",+ "cancel": "Cancel"+ },+ "delete": {+ "title": "Delete Album",+ "message": "Are you sure you want to delete the album \"{title}\"? Deleting the album will not delete the photos inside, only the album itself.",+ "cancel": "Cancel",+ "confirm": "Confirm Delete"+ },+ "messages": {+ "createSuccess": "Album created successfully",+ "updateSuccess": "Album updated successfully",+ "deleteSuccess": "Album deleted successfully",+ "createError": "Failed to create album",+ "updateError": "Failed to update album",+ "deleteError": "Failed to delete album",+ "loadError": "Failed to load albums",+ "loadDetailError": "Failed to load album details",+ "loadPhotosError": "Failed to load photos"+ }+ },"overview": {"title": "Overview","indicator": {diff --git a/i18n/locales/ja.json b/i18n/locales/ja.jsonindex 515dd27e..c62e2cf6 100644--- a/i18n/locales/ja.json+++ b/i18n/locales/ja.json@@ -50,6 +50,9 @@"globe": {"tooltip": "グローブ"},+ "home": {+ "tooltip": "ホームに戻る"+ },"share": {"tooltip": "写真を共有","title": "写真を共有",@@ -104,7 +107,31 @@"totalPhotosWithRange": "{range}、@:plural.photo 合計","noPhotosTip": "まだ写真はありません。アップロードしてください!"},- "livePhoto": "Live Photo"+ "livePhoto": "Live Photo",+ "album": {+ "noImage": "空のアルバム",+ "emptyAlbumTip": "写真を追加して開始しましょう",+ "noDescription": "説明がありません"+ }+ },+ "album": {+ "notFound": "アルバムが見つかりません",+ "noDateInfo": "日付情報なし",+ "noPhotosTip": "このアルバムにはまだ写真がありません",+ "emptyAlbumTitle": "アルバムが空です",+ "emptyAlbumDescription": "素敵な瞬間がここに表示されます。",+ "failedToLoadTitle": "アルバムの読み込みに失敗しました",+ "failedToLoadDescription": "このアルバムを読み込む際に問題が発生しました。",+ "failedToLoad": "アルバムの読み込みに失敗しました",+ "backToAlbums": "アルバムに戻る",+ "noDescription": "説明がありません",+ "photo": "写真がありません | 写真 {count} 枚",+ "createdAt": "{time} に作成されました",+ "metadata": {+ "photos": "写真",+ "dateRange": "日付範囲",+ "created": "作成"+ }},"map": {"cluster": {@@ -320,7 +347,8 @@"locations": "場所","globe": "写真グローブ","queue": "キュー管理",- "logs": "システムログ"+ "logs": "システムログ",+ "albums": "アルバム"},"auth": {"form": {@@ -375,6 +403,81 @@}},"dashboard": {+ "albums": {+ "title": "アルバム管理",+ "subtitle": "写真アルバムを作成・管理する",+ "createButton": "アルバムを作成",+ "noAlbums": "アルバムがまだありません",+ "noAlbumsTip": "最初のアルバムを作成して、写真を整理してください",+ "form": {+ "title": "タイトル",+ "titlePlaceholder": "アルバムのタイトルを入力",+ "titleRequired": "アルバムのタイトルを入力してください",+ "description": "説明",+ "descriptionPlaceholder": "アルバムの説明を入力(オプション)",+ "coverPhoto": "アルバムカバー",+ "addCoverPhoto": "カバー写真を追加",+ "selectPhotos": "写真を選択",+ "editPhotos": "写真の選択を編集",+ "selectedCount": "{count}枚の写真を選択しました",+ "clearAll": "すべてクリア"+ },+ "table": {+ "columns": {+ "cover": "カバー",+ "title": "タイトル",+ "description": "説明",+ "photoCount": "写真数",+ "createdAt": "作成時刻",+ "actions": "操作"+ }+ },+ "modal": {+ "selectPhotos": "写真を選択",+ "totalPhotos": "全{count}枚",+ "selectedPhotos": "{count}枚選択中",+ "searchPlaceholder": "写真を検索...",+ "searchResults": "結果:{current} / {total}",+ "selectAll": "すべて選択",+ "setCover": "カバーに設定",+ "noPhotos": "写真がありません",+ "noResults": "一致する写真が見つかりません",+ "tryOtherKeywords": "他のキーワードで検索してみてください",+ "confirm": "確認 ({count})",+ "selectedInfo": "選択済み:",+ "coverSetInfo": "カバーが設定されました"+ },+ "slideover": {+ "create": {+ "title": "アルバムを作成",+ "description": "写真を整理するための新しいアルバムを作成します"+ },+ "edit": {+ "title": "アルバムを編集",+ "description": "アルバムの情報と写真を変更"+ },+ "submitCreate": "作成",+ "submitEdit": "保存",+ "cancel": "キャンセル"+ },+ "delete": {+ "title": "アルバムを削除",+ "message": "アルバム\"{title}\"を削除してもよろしいですか?アルバムを削除しても、その中の写真は削除されず、アルバム自体のみが削除されます。",+ "cancel": "キャンセル",+ "confirm": "削除を確認"+ },+ "messages": {+ "createSuccess": "アルバムが正常に作成されました",+ "updateSuccess": "アルバムが正常に更新されました",+ "deleteSuccess": "アルバムが正常に削除されました",+ "createError": "アルバムの作成に失敗しました",+ "updateError": "アルバムの更新に失敗しました",+ "deleteError": "アルバムの削除に失敗しました",+ "loadError": "アルバムの読み込みに失敗しました",+ "loadDetailError": "アルバムの詳細の読み込みに失敗しました",+ "loadPhotosError": "写真の読み込みに失敗しました"+ }+ },"overview": {"title": "概要","indicator": {diff --git a/i18n/locales/zh-Hans.json b/i18n/locales/zh-Hans.jsonindex 0afbd79d..577e826a 100644--- a/i18n/locales/zh-Hans.json+++ b/i18n/locales/zh-Hans.json@@ -54,6 +54,9 @@"globe": {"tooltip": "地球仪"},+ "home": {+ "tooltip": "返回首页"+ },"share": {"tooltip": "分享照片","title": "分享照片",@@ -108,7 +111,31 @@"totalPhotosWithRange": "{range}, 共 @:plural.photo","noPhotosTip": "还没有照片,快去上传一些吧!"},- "indexPanelCountCity":"等 {count} 个城市"+ "indexPanelCountCity":"等 {count} 个城市",+ "album": {+ "noImage": "空相簿",+ "emptyAlbumTip": "添加照片开始吧",+ "noDescription": "无描述"+ }+ },+ "album": {+ "notFound": "相簿未找到",+ "noDateInfo": "无日期信息",+ "noPhotosTip": "该相簿中还没有照片",+ "emptyAlbumTitle": "相簿是空的",+ "emptyAlbumDescription": "更多精彩,将会呈现于此。",+ "failedToLoadTitle": "加载相簿失败",+ "failedToLoadDescription": "加载此相簿时出现问题。",+ "failedToLoad": "加载相簿失败",+ "backToAlbums": "返回相簿",+ "noDescription": "无描述",+ "photo": "无照片 | 一张照片 | {count} 张照片",+ "createdAt": "创建于 {time}",+ "metadata": {+ "photos": "照片",+ "dateRange": "日期范围",+ "created": "创建"+ }},"minimap": {"loading": "加载小地图..."@@ -321,7 +348,8 @@"photos": "照片库","globe": "照片地球仪","queue": "队列管理",- "logs": "系统日志"+ "logs": "系统日志",+ "albums": "相簿"},"auth": {"form": {@@ -432,6 +460,81 @@}},"dashboard": {+ "albums": {+ "title": "相簿管理",+ "subtitle": "创建和管理您的照片相簿",+ "createButton": "创建相簿",+ "noAlbums": "还没有相簿",+ "noAlbumsTip": "创建您的第一个相簿来组织您的照片",+ "form": {+ "title": "标题",+ "titlePlaceholder": "输入相簿标题",+ "titleRequired": "请输入相簿标题",+ "description": "描述",+ "descriptionPlaceholder": "输入相簿描述(可选)",+ "coverPhoto": "相簿封面",+ "addCoverPhoto": "添加封面照片",+ "selectPhotos": "选择照片",+ "editPhotos": "修改照片选择",+ "selectedCount": "已选择 {count} 张照片",+ "clearAll": "全部清除"+ },+ "table": {+ "columns": {+ "cover": "封面",+ "title": "标题",+ "description": "描述",+ "photoCount": "照片数",+ "createdAt": "创建时间",+ "actions": "操作"+ }+ },+ "modal": {+ "selectPhotos": "选择照片",+ "totalPhotos": "共 {count} 张",+ "selectedPhotos": "已选 {count} 张",+ "searchPlaceholder": "搜索照片...",+ "searchResults": "结果:{current} / {total}",+ "selectAll": "全选",+ "setCover": "设为封面",+ "noPhotos": "暂无照片",+ "noResults": "未找到匹配的照片",+ "tryOtherKeywords": "尝试使用其他关键词搜索",+ "confirm": "确认 ({count})",+ "selectedInfo": "已选择:",+ "coverSetInfo": "已设置封面"+ },+ "slideover": {+ "create": {+ "title": "创建相簿",+ "description": "创建一个新的相簿来组织您的照片"+ },+ "edit": {+ "title": "编辑相簿",+ "description": "修改相簿的信息和照片"+ },+ "submitCreate": "创建",+ "submitEdit": "保存",+ "cancel": "取消"+ },+ "delete": {+ "title": "删除相簿",+ "message": "确定要删除相簿\"{title}\"吗?删除相簿不会删除其中的照片,仅删除相簿本身。",+ "cancel": "取消",+ "confirm": "确认删除"+ },+ "messages": {+ "createSuccess": "相簿创建成功",+ "updateSuccess": "相簿更新成功",+ "deleteSuccess": "相簿删除成功",+ "createError": "创建相簿失败",+ "updateError": "更新相簿失败",+ "deleteError": "删除相簿失败",+ "loadError": "加载相簿失败",+ "loadDetailError": "加载相簿详情失败",+ "loadPhotosError": "加载照片失败"+ }+ },"overview": {"title": "仪表板概览","indicator": {diff --git a/i18n/locales/zh-Hant-HK.json b/i18n/locales/zh-Hant-HK.jsonindex eca75e89..60911b63 100644--- a/i18n/locales/zh-Hant-HK.json+++ b/i18n/locales/zh-Hant-HK.json@@ -54,6 +54,9 @@"globe": {"tooltip": "地球儀"},+ "home": {+ "tooltip": "返回首頁"+ },"share": {"tooltip": "分享相片","title": "分享相片",@@ -107,6 +110,30 @@"stats": {"totalPhotosWithRange": "{range},共 @:plural.photo","noPhotosTip": "還沒有照片,快去上傳一些吧!"+ },+ "album": {+ "noImage": "空相簿",+ "emptyAlbumTip": "新增相片開始啦",+ "noDescription": "無描述"+ }+ },+ "album": {+ "notFound": "搵唔到相簿",+ "noDateInfo": "無日期資料",+ "noPhotosTip": "呢個相簿仲冇相片",+ "emptyAlbumTitle": "相簿係空的",+ "emptyAlbumDescription": "更多精彩,將會喺呢度上映。",+ "failedToLoadTitle": "載入相簿失敗",+ "failedToLoadDescription": "載入呢個相簿嗰陣出咗問題。",+ "failedToLoad": "載入相簿失敗",+ "backToAlbums": "返回相簿",+ "noDescription": "無描述",+ "photo": "無相片 | 一張相片 | {count} 張相片",+ "createdAt": "建立咗 {time}",+ "metadata": {+ "photos": "相片",+ "dateRange": "日期範圍",+ "created": "建立"}},"minimap": {@@ -320,7 +347,8 @@"gallery": "相片集","globe": "照片地球儀","queue": "佇列管理",- "logs": "系統日誌"+ "logs": "系統日誌",+ "albums": "相簿"},"auth": {"form": {@@ -375,6 +403,81 @@}},"dashboard": {+ "albums": {+ "title": "相簿管理",+ "subtitle": "建立和管理您的照片相簿",+ "createButton": "建立相簿",+ "noAlbums": "還沒有相簿",+ "noAlbumsTip": "建立您的第一個相簿來組織您的照片",+ "form": {+ "title": "標題",+ "titlePlaceholder": "輸入相簿標題",+ "titleRequired": "請輸入相簿標題",+ "description": "描述",+ "descriptionPlaceholder": "輸入相簿描述(可選)",+ "coverPhoto": "相簿封面",+ "addCoverPhoto": "新增封面相片",+ "selectPhotos": "選擇相片",+ "editPhotos": "修改相片選擇",+ "selectedCount": "已選擇 {count} 張相片",+ "clearAll": "全部清除"+ },+ "table": {+ "columns": {+ "cover": "封面",+ "title": "標題",+ "description": "描述",+ "photoCount": "相片數",+ "createdAt": "建立時間",+ "actions": "操作"+ }+ },+ "modal": {+ "selectPhotos": "選擇相片",+ "totalPhotos": "共 {count} 張",+ "selectedPhotos": "已選 {count} 張",+ "searchPlaceholder": "搜尋相片...",+ "searchResults": "結果:{current} / {total}",+ "selectAll": "全選",+ "setCover": "設為封面",+ "noPhotos": "暫無相片",+ "noResults": "未找到相符的相片",+ "tryOtherKeywords": "嘗試使用其他關鍵字搜尋",+ "confirm": "確認 ({count})",+ "selectedInfo": "已選擇:",+ "coverSetInfo": "已設定封面"+ },+ "slideover": {+ "create": {+ "title": "建立相簿",+ "description": "建立一個新的相簿來組織您的照片"+ },+ "edit": {+ "title": "編輯相簿",+ "description": "修改相簿的資訊和相片"+ },+ "submitCreate": "建立",+ "submitEdit": "儲存",+ "cancel": "取消"+ },+ "delete": {+ "title": "刪除相簿",+ "message": "確定要刪除相簿\"{title}\"嗎?刪除相簿不會刪除其中的相片,僅刪除相簿本身。",+ "cancel": "取消",+ "confirm": "確認刪除"+ },+ "messages": {+ "createSuccess": "相簿建立成功",+ "updateSuccess": "相簿更新成功",+ "deleteSuccess": "相簿刪除成功",+ "createError": "建立相簿失敗",+ "updateError": "更新相簿失敗",+ "deleteError": "刪除相簿失敗",+ "loadError": "載入相簿失敗",+ "loadDetailError": "載入相簿詳情失敗",+ "loadPhotosError": "載入相片失敗"+ }+ },"overview": {"title": "儀表板概覽","indicator": {diff --git a/i18n/locales/zh-Hant-TW.json b/i18n/locales/zh-Hant-TW.jsonindex 8f33984a..0dbe9f21 100644--- a/i18n/locales/zh-Hant-TW.json+++ b/i18n/locales/zh-Hant-TW.json@@ -54,6 +54,9 @@"globe": {"tooltip": "地球儀"},+ "home": {+ "tooltip": "返回首頁"+ },"share": {"tooltip": "分享相片","title": "分享相片",@@ -107,6 +110,30 @@"stats": {"totalPhotosWithRange": "{range},共 @:plural.photo","noPhotosTip": "還沒有照片,快去上傳一些吧!"+ },+ "album": {+ "noImage": "空相簿",+ "emptyAlbumTip": "新增相片開始吧",+ "noDescription": "無描述"+ }+ },+ "album": {+ "notFound": "找不到相簿",+ "noDateInfo": "無日期資訊",+ "noPhotosTip": "該相簿中還沒有相片",+ "emptyAlbumTitle": "相簿是空的",+ "emptyAlbumDescription": "更多精彩,將會呈現於此。",+ "failedToLoadTitle": "載入相簿失敗",+ "failedToLoadDescription": "載入此相簿時出現問題。",+ "failedToLoad": "載入相簿失敗",+ "backToAlbums": "返回相簿",+ "noDescription": "無描述",+ "photo": "無相片 | 一張相片 | {count} 張相片",+ "createdAt": "建立於 {time}",+ "metadata": {+ "photos": "相片",+ "dateRange": "日期範圍",+ "created": "建立"}},"minimap": {@@ -320,7 +347,8 @@"gallery": "相片集","globe": "照片地球儀","queue": "佇列管理",- "logs": "系統日誌"+ "logs": "系統日誌",+ "albums": "相簿"},"auth": {"form": {@@ -375,8 +403,83 @@}},"dashboard": {+ "albums": {+ "title": "相簿管理",+ "subtitle": "建立和管理您的照片相簿",+ "createButton": "建立相簿",+ "noAlbums": "還沒有相簿",+ "noAlbumsTip": "建立您的第一個相簿來組織您的照片",+ "form": {+ "title": "標題",+ "titlePlaceholder": "輸入相簿標題",+ "titleRequired": "請輸入相簿標題",+ "description": "描述",+ "descriptionPlaceholder": "輸入相簿描述(選填)",+ "coverPhoto": "相簿封面",+ "addCoverPhoto": "新增封面照片",+ "selectPhotos": "選擇照片",+ "editPhotos": "修改照片選擇",+ "selectedCount": "已選擇 {count} 張照片",+ "clearAll": "全部清除"+ },+ "table": {+ "columns": {+ "cover": "封面",+ "title": "標題",+ "description": "描述",+ "photoCount": "照片數",+ "createdAt": "建立時間",+ "actions": "操作"+ }+ },+ "modal": {+ "selectPhotos": "選擇照片",+ "totalPhotos": "共 {count} 張",+ "selectedPhotos": "已選 {count} 張",+ "searchPlaceholder": "搜尋照片...",+ "searchResults": "結果:{current} / {total}",+ "selectAll": "全選",+ "setCover": "設為封面",+ "noPhotos": "暫無照片",+ "noResults": "未找到相符的照片",+ "tryOtherKeywords": "嘗試使用其他關鍵字搜尋",+ "confirm": "確認 ({count})",+ "selectedInfo": "已選擇:",+ "coverSetInfo": "已設定封面"+ },+ "slideover": {+ "create": {+ "title": "建立相簿",+ "description": "建立一個新的相簿來組織您的照片"+ },+ "edit": {+ "title": "編輯相簿",+ "description": "修改相簿的資訊和照片"+ },+ "submitCreate": "建立",+ "submitEdit": "儲存",+ "cancel": "取消"+ },+ "delete": {+ "title": "刪除相簿",+ "message": "確定要刪除相簿\"{title}\"嗎?刪除相簿不會刪除其中的照片,僅刪除相簿本身。",+ "cancel": "取消",+ "confirm": "確認刪除"+ },+ "messages": {+ "createSuccess": "相簿建立成功",+ "updateSuccess": "相簿更新成功",+ "deleteSuccess": "相簿刪除成功",+ "createError": "建立相簿失敗",+ "updateError": "更新相簿失敗",+ "deleteError": "刪除相簿失敗",+ "loadError": "載入相簿失敗",+ "loadDetailError": "載入相簿詳情失敗",+ "loadPhotosError": "載入照片失敗"+ }+ },"overview": {- "title": "儀表板概覽",+ "title": "儀表板總覽","indicator": {"totalPhotos": "照片總數","thisMonth": "本月新增",diff --git a/server/api/albums/[albumId].delete.ts b/server/api/albums/[albumId].delete.tsnew file mode 100644index 00000000..44a159b8--- /dev/null+++ b/server/api/albums/[albumId].delete.ts@@ -0,0 +1,44 @@+import { z } from 'zod'++export default eventHandler(async (event) => {+ await requireUserSession(event)++ const { albumId } = await getValidatedRouterParams(+ event,+ z.object({+ albumId: z+ .string()+ .regex(/^\d+$/)+ .transform((val) => parseInt(val, 10)),+ }).parse,+ )++ const db = useDB()++ // 检查相簌是否存在+ const album = await db+ .select()+ .from(tables.albums)+ .where(eq(tables.albums.id, albumId))+ .get()++ if (!album) {+ throw createError({+ statusCode: 404,+ statusMessage: 'Album not found',+ })+ }++ // 使用事务删除相簌及其关联的照片关系+ db.transaction((tx) => {+ // 删除相簌-照片关系+ tx.delete(tables.albumPhotos)+ .where(eq(tables.albumPhotos.albumId, albumId))+ .run()++ // 删除相簌+ tx.delete(tables.albums).where(eq(tables.albums.id, albumId)).run()+ })++ return { success: true }+})diff --git a/server/api/albums/[albumId].put.ts b/server/api/albums/[albumId].put.tsnew file mode 100644index 00000000..bbdf9d78--- /dev/null+++ b/server/api/albums/[albumId].put.ts@@ -0,0 +1,104 @@+import { z } from 'zod'++export default eventHandler(async (event) => {+ await requireUserSession(event)++ const { albumId } = await getValidatedRouterParams(+ event,+ z.object({+ albumId: z+ .string()+ .regex(/^\d+$/)+ .transform((val) => parseInt(val, 10)),+ }).parse,+ )++ const body = await readValidatedBody(+ event,+ z.object({+ title: z.string().min(1).max(255).optional(),+ description: z.string().max(1000).optional(),+ coverPhotoId: z.string().optional(),+ photoIds: z.array(z.string()).optional(),+ }).parse,+ )++ const db = useDB()++ // 检查相簿是否存在+ const album = await db+ .select()+ .from(tables.albums)+ .where(eq(tables.albums.id, albumId))+ .get()++ if (!album) {+ throw createError({+ statusCode: 404,+ statusMessage: 'Album not found',+ })+ }++ // 使用事务更新相簿+ const updatedAlbum = db.transaction((tx) => {+ // 更新基本信息+ const updateData: Record<string, any> = {+ updatedAt: new Date(),+ }++ if (body.title !== undefined) {+ updateData.title = body.title+ }++ if (body.description !== undefined) {+ updateData.description = body.description || null+ }++ if (body.coverPhotoId !== undefined) {+ updateData.coverPhotoId = body.coverPhotoId || null+ }++ tx.update(tables.albums)+ .set(updateData)+ .where(eq(tables.albums.id, albumId))+ .run()++ // 如果提供了新的照片列表,替换现有照片+ if (body.photoIds !== undefined) {+ // 删除现有的相簌-照片关系+ tx.delete(tables.albumPhotos)+ .where(eq(tables.albumPhotos.albumId, albumId))+ .run()++ // 添加新的相簌-照片关系+ const photoIds = new Set(body.photoIds)++ // 确保 coverPhotoId 在列表中+ if (body.coverPhotoId) {+ photoIds.add(body.coverPhotoId)+ }++ if (photoIds.size > 0) {+ let pos = 1000000+ for (const photoId of photoIds) {+ tx.insert(tables.albumPhotos)+ .values({+ albumId,+ photoId,+ position: (pos += 10),+ })+ .onConflictDoNothing()+ .run()+ }+ }+ }++ return tx+ .select()+ .from(tables.albums)+ .where(eq(tables.albums.id, albumId))+ .get()+ })++ return updatedAlbum+})diff --git a/server/api/albums/[albumId]/index.get.ts b/server/api/albums/[albumId]/index.get.tsindex ce49d7ac..264995b6 100644--- a/server/api/albums/[albumId]/index.get.ts+++ b/server/api/albums/[albumId]/index.get.ts@@ -27,6 +27,7 @@ export default eventHandler(async (event) => {})}+ // 获取相册中的照片const photos = await db// all fields from tables.photos.select({@@ -41,8 +42,17 @@ export default eventHandler(async (event) => {.orderBy(asc(tables.albumPhotos.position)).all()+ // 验证相册数据完整性+ if (!photos || !Array.isArray(photos)) {+ // 空相册也是合法的,只需要返回空数组+ return {+ ...album,+ photos: [],+ }+ }+return {...album,- photos: photos || [],+ photos,}})diff --git a/server/api/albums/[albumId]/photos/[photoId].delete.ts b/server/api/albums/[albumId]/photos/[photoId].delete.tsnew file mode 100644index 00000000..59336a2a--- /dev/null+++ b/server/api/albums/[albumId]/photos/[photoId].delete.ts@@ -0,0 +1,73 @@+import { z } from 'zod'+import { and } from 'drizzle-orm'++export default eventHandler(async (event) => {+ await requireUserSession(event)++ const { albumId } = await getValidatedRouterParams(+ event,+ z.object({+ albumId: z+ .string()+ .regex(/^\d+$/)+ .transform((val) => parseInt(val, 10)),+ }).parse,+ )++ const { photoId } = await getValidatedRouterParams(+ event,+ z.object({+ photoId: z.string(),+ }).parse,+ )++ const db = useDB()++ // 检查相簌-照片关系是否存在+ const relation = await db+ .select()+ .from(tables.albumPhotos)+ .where(+ and(+ eq(tables.albumPhotos.albumId, albumId),+ eq(tables.albumPhotos.photoId, photoId),+ ),+ )+ .get()++ if (!relation) {+ throw createError({+ statusCode: 404,+ statusMessage: 'Photo not found in album',+ })+ }++ // 使用事务删除照片关系,如果该照片是封面则更新为 null+ db.transaction((tx) => {+ // 删除相簌-照片关系+ tx.delete(tables.albumPhotos)+ .where(+ and(+ eq(tables.albumPhotos.albumId, albumId),+ eq(tables.albumPhotos.photoId, photoId),+ ),+ )+ .run()++ // 如果该照片是封面,清除封面+ const album = tx+ .select()+ .from(tables.albums)+ .where(eq(tables.albums.id, albumId))+ .get()++ if (album && album.coverPhotoId === photoId) {+ tx.update(tables.albums)+ .set({ coverPhotoId: null, updatedAt: new Date() })+ .where(eq(tables.albums.id, albumId))+ .run()+ }+ })++ return { success: true }+})diff --git a/server/api/albums/index.get.ts b/server/api/albums/index.get.tsindex d1d7810d..1aa99845 100644--- a/server/api/albums/index.get.ts+++ b/server/api/albums/index.get.ts@@ -1,31 +1,31 @@export default eventHandler(async (_event) => {const db = useDB()- // 获取所有相册+ // 获取所有相册,按创建时间倒序const albums = await db.select().from(tables.albums)- // 为每个相册获取照片- const albumsWithPhotos = await Promise.all(+ // 为每个相册获取照片 ID 列表(避免循环引用)+ const albumsWithPhotoIds = await Promise.all(albums.map(async (album) => {- const photos = await db+ const photoIds = await db.select({- photo: tables.photos,+ photoId: tables.albumPhotos.photoId,position: tables.albumPhotos.position,}).from(tables.albumPhotos)- .innerJoin(- tables.photos,- eq(tables.albumPhotos.photoId, tables.photos.id),- ).where(eq(tables.albumPhotos.albumId, album.id)).orderBy(tables.albumPhotos.position)return {...album,- photos: photos.map((p) => p.photo),+ // 即使是空相册,也返回空数组而不是 undefined+ photoIds: photoIds.length > 0 ? photoIds.map((p) => p.photoId) : [],}}),)- return albumsWithPhotos+ // 按创建时间倒序排列+ return albumsWithPhotoIds.sort(+ (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),+ )})