Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

feat: 重构瀑布流布局,修复照片排列顺序错误 (Fixes #19)

Timothy Yin8f099c0c6aa8
diff --git a/app/components/masonry/Item.vue b/app/components/masonry/Item.vue
index ff61c098..472320ab 100644
--- a/app/components/masonry/Item.vue
+++ b/app/components/masonry/Item.vue
@@ -9,7 +9,7 @@ const props = withDefaults(
firstScreenItems?: number
}>(),
{
- firstScreenItems: 300,
+ firstScreenItems: 30,
},
)
@@ -62,13 +62,14 @@ const itemVariants = {
:variants="shouldAnimate ? itemVariants : undefined"
:initial="shouldAnimate ? 'hidden' : 'visible'"
:animate="'visible'"
+ class="w-full"
@animation-complete="
() => {
if (shouldAnimate) emit('animationComplete')
}
"
>
- <MasonryPhotoItem
+ <MasonryItemPhoto
:photo="photo"
:index="index"
@visibility-change="emit('visibility-change', $event)"
diff --git a/app/components/masonry/Root.vue b/app/components/masonry/Root.vue
index 9bc87835..11d07d25 100644
--- a/app/components/masonry/Root.vue
+++ b/app/components/masonry/Root.vue
@@ -11,55 +11,77 @@ 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
})
-// Viewer state for scroll sync
const { currentPhotoIndex, isViewerOpen } = storeToRefs(useViewerState())
-// Constants
-const FIRST_SCREEN_ITEMS_COUNT = 42
-const COLUMN_GAP = 4
-const AUTO_COLUMN_WIDTH = 280
-const MAX_COLUMN_COUNT = 8
-const MIN_COLUMN_COUNT = 2
+const FIRST_SCREEN_ITEMS_COUNT = 50
-// Reactive state
const masonryContainer = ref<HTMLElement>()
-const containerWidth = ref(0)
const hasAnimated = ref(false)
const showFloatingActions = ref(false)
const dateRange = ref<string>()
const visiblePhotos = ref(new Set<number>())
-// Composables
const isMobile = useMediaQuery('(max-width: 768px)')
const { batchProcessLivePhotos } = useLivePhotoProcessor()
-// Track processed photos to avoid reprocessing
const processedBatch = ref(new Set<string>())
-// Computed
-const columnCount = computed(() => {
+const columnWidth = computed(() => {
if (props.columns === 'auto') {
- if (!containerWidth.value) return MIN_COLUMN_COUNT
+ return isMobile.value ? 280 : 280
+ }
+ return 280
+})
- const availableWidth = containerWidth.value - (isMobile.value ? 16 : 32)
- const maxColumns = isMobile.value ? 2 : MAX_COLUMN_COUNT
- const calculatedColumns = Math.floor(
- (availableWidth + COLUMN_GAP) / (AUTO_COLUMN_WIDTH + COLUMN_GAP),
- )
+const maxColumns = computed(() => {
+ if (props.columns !== 'auto') {
+ return props.columns
+ }
+ return isMobile.value ? 2 : 8
+})
- return Math.min(Math.max(calculatedColumns, MIN_COLUMN_COUNT), maxColumns)
+const minColumns = computed(() => {
+ if (props.columns !== 'auto') {
+ return props.columns
}
+ return 2
+})
+
+// Prepare items for masonry-wall
+const masonryItems = computed(() => {
+ const items: Array<{
+ id: string
+ type: 'header' | 'photo'
+ photo?: Photo
+ originalIndex?: number
+ }> = []
+
+ // Add header item for non-mobile layout
+ if (!isMobile.value) {
+ items.push({
+ id: 'header',
+ type: 'header',
+ })
+ }
+
+ // Add photo items
+ displayPhotos.value?.forEach((photo, index) => {
+ items.push({
+ id: photo.id,
+ type: 'photo',
+ photo,
+ originalIndex: index,
+ })
+ })
- return props.columns
+ return items
})
const photoStats = computed(() => {
@@ -214,31 +236,12 @@ const updateDateRange = () => {
}
}
-const updateContainerWidth = () => {
- if (masonryContainer.value) {
- containerWidth.value = masonryContainer.value.offsetWidth
- }
-}
-
const handleScroll = () => {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop
showFloatingActions.value = scrollTop > 500
}
-// Lifecycle
onMounted(() => {
- updateContainerWidth()
-
- // Set up resize observer
- const resizeObserver = new ResizeObserver(() => {
- updateContainerWidth()
- })
-
- if (masonryContainer.value) {
- resizeObserver.observe(masonryContainer.value)
- }
-
- // Set up scroll listener
window.addEventListener('scroll', handleScroll, { passive: true })
nextTick(() => {
@@ -249,7 +252,6 @@ onMounted(() => {
// Cleanup
onUnmounted(() => {
- resizeObserver.disconnect()
window.removeEventListener('scroll', handleScroll)
})
})
@@ -258,7 +260,6 @@ const handleOpenViewer = (index: number) => {
router.push(`/${displayPhotos.value[index]?.id}`)
}
-// 滚动到指定照片的位置
const scrollToPhoto = (photoIndex: number) => {
if (!displayPhotos.value[photoIndex]) return
@@ -266,19 +267,17 @@ const scrollToPhoto = (photoIndex: number) => {
const photoElement = document.querySelector(`[data-photo-id="${photoId}"]`)
if (photoElement) {
- // 计算滚动位置,让目标图片居中显示
const elementRect = photoElement.getBoundingClientRect()
const windowHeight = window.innerHeight
const currentScrollY = window.pageYOffset
- // 计算目标滚动位置,让图片在视窗中央
+ // 让图片在视口中央
const targetScrollY =
currentScrollY +
elementRect.top -
windowHeight / 2 +
elementRect.height / 2
- // 平滑滚动到目标位置
window.scrollTo({
top: Math.max(0, targetScrollY),
behavior: 'smooth',
@@ -286,11 +285,8 @@ const scrollToPhoto = (photoIndex: number) => {
}
}
-// 监听照片查看器的索引变化,滚动到对应图片
watch(currentPhotoIndex, (newIndex) => {
- // 只在查看器打开时才滚动
if (isViewerOpen.value && newIndex >= 0) {
- // 延迟一下,确保DOM更新完成
nextTick(() => {
scrollToPhoto(newIndex)
})
@@ -307,12 +303,12 @@ watch(currentPhotoIndex, (newIndex) => {
:is-mobile="isMobile"
/>
- <!-- 移动端时 HeaderItem 显示在瀑布流容器外 -->
+ <!-- 移动端时 ItemHeader 显示在瀑布流容器外 -->
<div
v-if="isMobile"
class="px-1 pt-2 pb-1"
>
- <MasonryHeaderItem
+ <MasonryItemHeader
:stats="photoStats"
:date-range-text
/>
@@ -323,46 +319,45 @@ watch(currentPhotoIndex, (newIndex) => {
class="lg:px-0 lg:pb-0"
:class="isMobile ? 'px-1 pb-1' : 'p-1'"
>
- <!-- Masonry Grid -->
- <div
+ <!-- Masonry Wall -->
+ <MasonryWall
ref="masonryContainer"
- class="masonry-grid"
- :style="{
- columnCount: columnCount,
- columnGap: `${COLUMN_GAP}px`,
- }"
+ :items="masonryItems"
+ :column-width="columnWidth"
+ :gap="4"
+ :min-columns="minColumns"
+ :max-columns="maxColumns"
+ :ssr-columns="2"
+ :key-mapper="
+ (_item, _column, _row, index) =>
+ masonryItems[index]?.originalIndex || index
+ "
>
- <!-- 非移动端时 HeaderItem 显示在瀑布流内 -->
- <MasonryHeaderItem
- v-if="!isMobile"
- :stats="photoStats"
- :date-range-text
- />
-
- <!-- Photo Items -->
- <MasonryItem
- v-for="(photo, index) in displayPhotos"
- :key="photo.id || index"
- :photo="photo"
- :index="index"
- :has-animated
- :first-screen-items="FIRST_SCREEN_ITEMS_COUNT"
- @visibility-change="handleVisibilityChange"
- @open-viewer="handleOpenViewer($event)"
- />
- </div>
+ <template #default="{ item, index }">
+ <!-- 非移动端时 ItemHeader 显示在瀑布流内的第一个位置 -->
+ <MasonryItemHeader
+ v-if="!isMobile && index === 0 && item.type === 'header'"
+ :stats="photoStats"
+ :date-range-text
+ />
+
+ <!-- Photo Items -->
+ <MasonryItem
+ v-else-if="
+ item.type === 'photo' &&
+ item.photo &&
+ typeof item.originalIndex === 'number'
+ "
+ :key="item.photo.id"
+ :photo="item.photo"
+ :index="item.originalIndex"
+ :has-animated
+ :first-screen-items="FIRST_SCREEN_ITEMS_COUNT"
+ @visibility-change="handleVisibilityChange"
+ @open-viewer="handleOpenViewer($event)"
+ />
+ </template>
+ </MasonryWall>
</div>
</div>
</template>
-
-<style scoped>
-.masonry-container {
- position: relative;
- width: 100%;
-}
-
-.masonry-grid {
- width: 100%;
- column-fill: balance;
-}
-</style>
diff --git a/app/components/masonry/HeaderItem.vue b/app/components/masonry/item/Header.vue
similarity index 97%
rename from app/components/masonry/HeaderItem.vue
rename to app/components/masonry/item/Header.vue
index b2e1ee78..e6f65233 100644
--- a/app/components/masonry/HeaderItem.vue
+++ b/app/components/masonry/item/Header.vue
@@ -29,10 +29,8 @@ const handleOpenLogin = () => {
router.push('/signin')
}
-// 获取筛选状态
const { hasActiveFilters, selectedCounts } = usePhotoFilters()
-// 获取排序状态
const {
currentSortLabel,
currentSortIcon,
@@ -41,7 +39,6 @@ const {
setSortOption,
} = usePhotoSort()
-// 计算总的筛选项数量
const totalSelectedFilters = computed(() => {
return Object.values(selectedCounts.value).reduce(
(total, count) => total + count,
@@ -52,7 +49,7 @@ const totalSelectedFilters = computed(() => {
<template>
<div
- class="inline-block w-full align-top break-inside-avoid mb-[4px] relative overflow-hidden"
+ class="w-full relative overflow-hidden"
>
<div
class="absolute inset-0 -z-10 blur-3xl scale-110 bg-cover bg-center opacity-35"
diff --git a/app/components/masonry/PhotoItem.client.vue b/app/components/masonry/item/Photo.vue
similarity index 98%
rename from app/components/masonry/PhotoItem.client.vue
rename to app/components/masonry/item/Photo.vue
index 6d57ef6a..665904f3 100644
--- a/app/components/masonry/PhotoItem.client.vue
+++ b/app/components/masonry/item/Photo.vue
@@ -15,17 +15,12 @@ const emit = defineEmits<{
openViewer: [number]
}>()
-// Constants
-const ITEM_GAP = 4
-
-// Reactive state
const isLoading = ref(true)
const photoRef = ref<HTMLElement>()
const videoRef = useDomRef()
const isVisible = ref(false)
const containerWidth = ref(0)
-// LivePhoto related state
const isHovering = ref(false)
const isVideoPlaying = ref(false)
const isVideoLoaded = ref(false)
@@ -33,21 +28,17 @@ const videoBlob = ref<Blob | null>(null)
const videoBlobUrl = ref<string | null>(null)
const { convertMovToMp4, getProcessingState } = useLivePhotoProcessor()
-// Mobile touch state for LivePhoto
const isTouching = ref(false)
const touchCount = ref(0)
const longPressTimer = ref<NodeJS.Timeout | null>(null)
const initialTouchPos = ref<{ x: number; y: number } | null>(null)
const isMobile = useMediaQuery('(max-width: 768px)')
-// Observers
const resizeObserverRef = ref<ResizeObserver | null>(null)
const intersectionObserverRef = ref<IntersectionObserver | null>(null)
-// LivePhoto processing state
const processingState = getProcessingState(props.photo.id)
-// Computed
const aspectRatio = computed(() => {
// Priority 1: Use aspectRatio from photo data if available
if (props.photo.aspectRatio) {
@@ -427,9 +418,8 @@ onUnmounted(() => {
<template>
<div
ref="photoRef"
- class="inline-block w-full align-top break-inside-avoid transition-all duration-300 cursor-pointer select-none"
+ class="w-full transition-all duration-300 cursor-pointer select-none"
:style="{
- marginBottom: `${ITEM_GAP}px`,
transform: 'translateZ(0)',
}"
@click="handleClick"
diff --git a/app/plugins/vue-masonry-wall.ts b/app/plugins/vue-masonry-wall.ts
new file mode 100644
index 00000000..b594cc4f
--- /dev/null
+++ b/app/plugins/vue-masonry-wall.ts
@@ -0,0 +1,5 @@
+import MasonryWall from '@yeger/vue-masonry-wall'
+
+export default defineNuxtPlugin((nuxtApp) => {
+ nuxtApp.vueApp.use(MasonryWall)
+})
diff --git a/package.json b/package.json
index c431ea1e..eb677e67 100644
--- a/package.json
+++ b/package.json
@@ -38,6 +38,7 @@
"@unhead/vue": "^2.0.5",
"@vingle/bmp-js": "^0.2.5",
"@vueuse/nuxt": "13.8.0",
+ "@yeger/vue-masonry-wall": "^5.1.0",
"better-sqlite3": "^12.2.0",
"cloudflare": "^4.5.0",
"dayjs-nuxt": "2.1.11",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ee1fc72b..b894dfd3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -53,6 +53,9 @@ importers:
'@vueuse/nuxt':
specifier: 13.8.0
+ '@yeger/vue-masonry-wall':
+ specifier: ^5.1.0
better-sqlite3:
specifier: ^12.2.0
version: 12.3.0
@@ -3264,6 +3267,20 @@ packages:
peerDependencies:
vue: ^3.5.0
+ '@yeger/[email protected]':
+ resolution: {integrity: sha512-3nwbTEG1xpo/v3RPo2FAKVUGEPPoc7PZ9SMZUNmeoGuX3Ml72FQDi2OcvDODURQLa2ELK+dJ2HjMKTogA7BWfA==}
+
+ '@yeger/[email protected]':
+ resolution: {integrity: sha512-2tWMPB1oRBoytcqtwFSz0sXLXKBfiW+qBUpesvxLLOz+G2NuppLTH1HTtbkRY4Wy+655JNMErM3627HPoEHtvg==}
+
+ '@yeger/[email protected]':
+ resolution: {integrity: sha512-ksfUpD1NYPgSBrIfekQYOUbesLywStcVZvy3eNTssH+owwD+2w/+rf9c1v8DmtPNQMdpwq19lWCo1qqewuT46g==}
+
+ '@yeger/[email protected]':
+ resolution: {integrity: sha512-oJR9BFet7Cln/XBAVcAbYWsKYRWKqtp+PiJVarZh3YYfTVGICiHMh9SDNBtPIgtMwyuuQi/w+v03O5PN/yfufw==}
+ peerDependencies:
+ vue: ^3.0.0
+
resolution: {integrity: sha512-AO2ac6pjRB3SJmGJo+v5/aK6Omggp6fsLrs6wN9bd35ulu4cCwaAU9+7ZhXjeqHVkaHThLuzH0nZr0YpCDhygg==}
engines: {node: ^18.17.0 || >=20.5.0}
@@ -10933,6 +10950,20 @@ snapshots:
dependencies:
vue: 3.5.21([email protected])
+ '@yeger/[email protected]': {}
+
+ '@yeger/[email protected]': {}
+
+ '@yeger/[email protected]':
+ dependencies:
+ '@yeger/debounce': 2.0.14
+ '@yeger/vue-lib-adapter': 2.0.13
+
+ dependencies:
+ '@yeger/vue-masonry-wall-core': 5.0.17
+ vue: 3.5.21([email protected])
+