增加更多分辨率图像的拉取

This commit is contained in:
2026-01-27 15:34:38 +08:00
parent 9c2a5d5cd8
commit d757dbd39d
16 changed files with 587 additions and 97 deletions

View File

@@ -1,4 +1,5 @@
import { ref, onMounted } from 'vue'
import { ref, onMounted, watch } from 'vue'
import type { Ref } from 'vue'
import { bingPaperApi } from '@/lib/api-service'
import type { ImageMeta } from '@/lib/api-types'
@@ -36,27 +37,43 @@ export function useTodayImage() {
}
/**
* 获取图片列表(支持分页)
* 获取图片列表(支持分页和月份筛选
*/
export function useImageList(initialLimit = 30) {
export function useImageList(pageSize = 30) {
const images = ref<ImageMeta[]>([])
const loading = ref(false)
const error = ref<Error | null>(null)
const hasMore = ref(true)
const currentPage = ref(1)
const currentMonth = ref<string | undefined>(undefined)
const fetchImages = async (limit = initialLimit) => {
const fetchImages = async (page = 1, month?: string) => {
if (loading.value) return
loading.value = true
error.value = null
try {
const newImages = await bingPaperApi.getImages({ limit })
if (newImages.length < limit) {
hasMore.value = false
const params: any = {
page,
page_size: pageSize
}
if (month) {
params.month = month
}
images.value = [...images.value, ...newImages]
const newImages = await bingPaperApi.getImages(params)
if (page === 1) {
// 首次加载或重新筛选
images.value = newImages
} else {
// 加载更多
images.value = [...images.value, ...newImages]
}
// 判断是否还有更多数据
hasMore.value = newImages.length === pageSize
currentPage.value = page
} catch (e) {
error.value = e as Error
console.error('Failed to fetch images:', e)
@@ -67,12 +84,19 @@ export function useImageList(initialLimit = 30) {
const loadMore = () => {
if (!loading.value && hasMore.value) {
fetchImages()
fetchImages(currentPage.value + 1, currentMonth.value)
}
}
const filterByMonth = (month?: string) => {
currentMonth.value = month
currentPage.value = 1
hasMore.value = true
fetchImages(1, month)
}
onMounted(() => {
fetchImages()
fetchImages(1)
})
return {
@@ -81,10 +105,11 @@ export function useImageList(initialLimit = 30) {
error,
hasMore,
loadMore,
filterByMonth,
refetch: () => {
images.value = []
currentPage.value = 1
hasMore.value = true
fetchImages()
fetchImages(1, currentMonth.value)
}
}
}
@@ -92,7 +117,7 @@ export function useImageList(initialLimit = 30) {
/**
* 获取指定日期的图片
*/
export function useImageByDate(date: string) {
export function useImageByDate(dateRef: Ref<string>) {
const image = ref<ImageMeta | null>(null)
const loading = ref(false)
const error = ref<Error | null>(null)
@@ -101,18 +126,19 @@ export function useImageByDate(date: string) {
loading.value = true
error.value = null
try {
image.value = await bingPaperApi.getImageMetaByDate(date)
image.value = await bingPaperApi.getImageMetaByDate(dateRef.value)
} catch (e) {
error.value = e as Error
console.error(`Failed to fetch image for date ${date}:`, e)
console.error(`Failed to fetch image for date ${dateRef.value}:`, e)
} finally {
loading.value = false
}
}
onMounted(() => {
// 监听日期变化,自动重新获取
watch(dateRef, () => {
fetchImage()
})
}, { immediate: true })
return {
image,

View File

@@ -106,6 +106,9 @@ export class BingPaperApiService {
const searchParams = new URLSearchParams()
if (params?.limit) searchParams.set('limit', params.limit.toString())
if (params?.offset) searchParams.set('offset', params.offset.toString())
if (params?.page) searchParams.set('page', params.page.toString())
if (params?.page_size) searchParams.set('page_size', params.page_size.toString())
if (params?.month) searchParams.set('month', params.month)
const queryString = searchParams.toString()
const endpoint = queryString ? `/images?${queryString}` : '/images'

View File

@@ -161,7 +161,9 @@ export interface ImageMeta {
}
export interface ImageListParams extends PaginationParams {
// 可以扩展更多筛选参数
page?: number // 页码从1开始
page_size?: number // 每页数量
month?: string // 按月份过滤格式YYYY-MM
}
export interface ManualFetchRequest {
@@ -170,5 +172,5 @@ export interface ManualFetchRequest {
// ===== API 端点类型定义 =====
export type ImageVariant = 'UHD' | '1920x1080' | '1366x768'
export type ImageVariant = 'UHD' | '1920x1080' | '1366x768' | '1280x720' | '1024x768' | '800x600' | '800x480' | '640x480' | '640x360' | '480x360' | '400x240' | '320x240'
export type ImageFormat = 'jpg'

View File

@@ -94,7 +94,10 @@
<div class="space-y-2">
<div class="flex gap-4 text-sm">
<code class="text-yellow-400 min-w-24">variant</code>
<span class="text-white/50">分辨率: UHD, 1920x1080, 1366x768 (默认: UHD)</span>
<div class="flex-1">
<span class="text-white/50 block mb-1">分辨率 (默认: UHD)</span>
<span class="text-white/40 text-xs">可选值: UHD, 1920x1080, 1366x768, 1280x720, 1024x768, 800x600, 800x480, 640x480, 640x360, 480x360, 400x240, 320x240</span>
</div>
</div>
<div class="flex gap-4 text-sm">
<code class="text-yellow-400 min-w-24">format</code>
@@ -170,7 +173,10 @@
<div class="space-y-2">
<div class="flex gap-4 text-sm">
<code class="text-yellow-400 min-w-24">variant</code>
<span class="text-white/50">分辨率 (默认: UHD)</span>
<div class="flex-1">
<span class="text-white/50 block mb-1">分辨率 (默认: UHD)</span>
<span class="text-white/40 text-xs">可选值: UHD, 1920x1080, 1366x768, 1280x720, 1024x768, 800x600, 800x480, 640x480, 640x360, 480x360, 400x240, 320x240</span>
</div>
</div>
<div class="flex gap-4 text-sm">
<code class="text-yellow-400 min-w-24">format</code>
@@ -239,7 +245,10 @@
<div class="space-y-2">
<div class="flex gap-4 text-sm">
<code class="text-yellow-400 min-w-24">variant</code>
<span class="text-white/50">分辨率 (默认: UHD)</span>
<div class="flex-1">
<span class="text-white/50 block mb-1">分辨率 (默认: UHD)</span>
<span class="text-white/40 text-xs">可选值: UHD, 1920x1080, 1366x768, 1280x720, 1024x768, 800x600, 800x480, 640x480, 640x360, 480x360, 400x240, 320x240</span>
</div>
</div>
<div class="flex gap-4 text-sm">
<code class="text-yellow-400 min-w-24">format</code>

View File

@@ -62,20 +62,87 @@
<!-- Gallery Section - 历史图片 -->
<section class="py-16 px-4 md:px-8 lg:px-16">
<div class="max-w-7xl mx-auto">
<h2 class="text-3xl md:text-4xl font-bold text-white mb-8">
历史精选
</h2>
<div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
<h2 class="text-3xl md:text-4xl font-bold text-white">
历史精选
</h2>
<!-- 筛选器 -->
<div class="flex flex-wrap items-center gap-3">
<!-- 年份选择 -->
<Select v-model="selectedYear" @update:model-value="onYearChange">
<SelectTrigger class="w-[180px] bg-white/10 backdrop-blur-md text-white border-white/20 hover:bg-white/15 hover:border-white/30 focus:ring-white/50 shadow-lg">
<SelectValue placeholder="选择年份" />
</SelectTrigger>
<SelectContent class="bg-gray-900/95 backdrop-blur-xl border-white/20 text-white">
<SelectItem
v-for="year in availableYears"
:key="year"
:value="String(year)"
class="focus:bg-white/10 focus:text-white cursor-pointer"
>
{{ year }}
</SelectItem>
</SelectContent>
</Select>
<!-- 月份选择 -->
<Select v-model="selectedMonth" @update:model-value="onFilterChange" :disabled="!selectedYear">
<SelectTrigger
class="w-[180px] bg-white/10 backdrop-blur-md text-white border-white/20 hover:bg-white/15 hover:border-white/30 focus:ring-white/50 shadow-lg disabled:opacity-40 disabled:cursor-not-allowed"
>
<SelectValue placeholder="选择月份" />
</SelectTrigger>
<SelectContent class="bg-gray-900/95 backdrop-blur-xl border-white/20 text-white">
<SelectItem
v-for="month in 12"
:key="month"
:value="String(month)"
class="focus:bg-white/10 focus:text-white cursor-pointer"
>
{{ month }}
</SelectItem>
</SelectContent>
</Select>
<!-- 重置按钮 -->
<button
v-if="selectedYear && selectedMonth"
@click="resetFilters"
class="px-4 py-2.5 bg-gradient-to-r from-red-500/20 to-pink-500/20 backdrop-blur-md text-white rounded-lg hover:from-red-500/30 hover:to-pink-500/30 border border-red-400/30 hover:border-red-400/50 transition-all flex items-center gap-2 text-sm font-medium shadow-lg hover:shadow-xl transform hover:scale-105"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
</svg>
清除筛选
</button>
</div>
</div>
<!-- 筛选结果提示 -->
<div v-if="selectedYear && selectedMonth" class="mb-6 flex items-center gap-2 text-white/60 text-sm">
<span>当前显示</span>
<span class="text-white font-medium">
{{ selectedYear }} {{ selectedMonth }}
</span>
<span>的图片 {{ images.length }} </span>
</div>
<!-- 图片网格 -->
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
<div
v-for="(image, index) in images"
:key="image.date || index"
:ref="el => setImageRef(el, index)"
class="group relative aspect-video rounded-xl overflow-hidden cursor-pointer transform transition-all duration-300 hover:scale-105 hover:shadow-2xl"
@click="viewImage(image.date!)"
>
<!-- 图片 -->
<!-- 图片懒加载 -->
<div v-if="!imageVisibility[index]" class="w-full h-full bg-white/5 flex items-center justify-center">
<div class="w-8 h-8 border-2 border-white/20 border-t-white/60 rounded-full animate-spin"></div>
</div>
<img
v-else
:src="getImageUrl(image.date!)"
:alt="image.title || 'Bing Image'"
class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
@@ -83,15 +150,15 @@
/>
<!-- 悬浮信息层 -->
<div class="absolute inset-0 bg-gradient-to-t from-black/90 via-black/50 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300">
<div class="absolute bottom-0 left-0 right-0 p-6 transform translate-y-4 group-hover:translate-y-0 transition-transform duration-300">
<div class="text-xs text-white/70 mb-2">
<div class="absolute inset-0 bg-gradient-to-t from-black/90 via-black/50 to-transparent md:opacity-0 md:group-hover:opacity-100 transition-opacity duration-300">
<div class="absolute bottom-0 left-0 right-0 p-4 md:p-6 transform md:translate-y-4 md:group-hover:translate-y-0 transition-transform duration-300">
<div class="text-xs text-white/70 mb-1">
{{ formatDate(image.date) }}
</div>
<h3 class="text-lg font-semibold text-white mb-2 line-clamp-2">
<h3 class="text-base md:text-lg font-semibold text-white mb-1 md:mb-2 line-clamp-2">
{{ image.title || '未命名' }}
</h3>
<p v-if="image.copyright" class="text-sm text-white/80 line-clamp-2">
<p v-if="image.copyright" class="text-xs md:text-sm text-white/80 line-clamp-2">
{{ image.copyright }}
</p>
</div>
@@ -162,17 +229,182 @@
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useTodayImage, useImageList } from '@/composables/useImages'
import { bingPaperApi } from '@/lib/api-service'
import { useRouter } from 'vue-router'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
const router = useRouter()
// 获取今日图片
const { image: todayImage, loading: todayLoading } = useTodayImage()
// 获取图片列表
const { images, loading, hasMore, loadMore } = useImageList(30)
// 获取图片列表(使用服务端分页和筛选)
const { images, loading, hasMore, loadMore, filterByMonth } = useImageList(30)
// 筛选相关状态
const selectedYear = ref('')
const selectedMonth = ref('')
// 懒加载相关
const imageRefs = ref<(HTMLElement | null)[]>([])
const imageVisibility = ref<boolean[]>([])
let observer: IntersectionObserver | null = null
// 计算可用的年份列表基于当前日期生成从2020年到当前年份
const availableYears = computed(() => {
const currentYear = new Date().getFullYear()
const years: number[] = []
for (let year = currentYear; year >= 2020; year--) {
years.push(year)
}
return years
})
// 年份选择变化时的处理
const onYearChange = () => {
if (!selectedYear.value) {
// 清空年份时,重置所有筛选
selectedMonth.value = ''
filterByMonth(undefined)
imageVisibility.value = []
setTimeout(() => {
setupObserver()
}, 100)
} else if (selectedMonth.value) {
// 如果已经有月份选择,立即触发筛选
onFilterChange()
}
}
// 筛选变化时调用服务端筛选
const onFilterChange = () => {
// 只有同时选择年份和月份时才触发筛选
if (selectedYear.value && selectedMonth.value) {
const yearStr = selectedYear.value
const monthStr = String(selectedMonth.value).padStart(2, '0')
const monthParam = `${yearStr}-${monthStr}`
// 调用服务端筛选
filterByMonth(monthParam)
// 重置懒加载状态
imageVisibility.value = []
setTimeout(() => {
setupObserver()
}, 100)
}
}
// 重置筛选
const resetFilters = () => {
selectedYear.value = ''
selectedMonth.value = ''
// 重置为加载默认数据
filterByMonth(undefined)
// 重置懒加载状态
imageVisibility.value = []
setTimeout(() => {
setupObserver()
}, 100)
}
// 设置图片ref
const setImageRef = (el: any, index: number) => {
if (el && el instanceof HTMLElement) {
imageRefs.value[index] = el
}
}
// 设置 Intersection Observer
const setupObserver = () => {
// 清理旧的 observer
if (observer) {
observer.disconnect()
}
observer = new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const index = imageRefs.value.findIndex(ref => ref === entry.target)
if (index !== -1) {
imageVisibility.value[index] = true
// 加载后取消观察
observer?.unobserve(entry.target)
}
}
})
},
{
root: null,
rootMargin: '200px', // 提前 200px 开始加载
threshold: 0.01
}
)
// 观察所有图片元素
imageRefs.value.forEach((ref, index) => {
if (ref && !imageVisibility.value[index]) {
observer?.observe(ref)
}
})
}
// 初始化懒加载状态
onMounted(() => {
// 初始化时设置
if (images.value.length > 0) {
imageVisibility.value = new Array(images.value.length).fill(false)
setTimeout(() => {
setupObserver()
}, 100)
}
})
// 监听 images 变化,动态更新 imageVisibility
watch(() => images.value.length, (newLength, oldLength) => {
if (newLength > oldLength) {
// 图片列表增长时,扩展 imageVisibility 数组
const newItems = new Array(newLength - oldLength).fill(false)
imageVisibility.value = [...imageVisibility.value, ...newItems]
// 重新设置 observer
setTimeout(() => {
setupObserver()
}, 100)
} else if (newLength < oldLength) {
// 图片列表减少时(如筛选),截断数组
imageVisibility.value = imageVisibility.value.slice(0, newLength)
} else if (newLength === 0) {
// 如果是首次加载
imageVisibility.value = []
}
// 如果从 0 变为有数据,初始化并设置 observer
if (oldLength === 0 && newLength > 0) {
imageVisibility.value = new Array(newLength).fill(false)
setTimeout(() => {
setupObserver()
}, 100)
}
})
// 清理
onUnmounted(() => {
if (observer) {
observer.disconnect()
}
})
// 格式化日期
const formatDate = (dateStr?: string) => {
@@ -190,9 +422,9 @@ const getTodayImageUrl = () => {
return bingPaperApi.getTodayImageUrl('UHD', 'jpg')
}
// 获取图片 URL
// 获取图片 URL(缩略图 - 使用较小分辨率节省流量)
const getImageUrl = (date: string) => {
return bingPaperApi.getImageUrlByDate(date, '1920x1080', 'jpg')
return bingPaperApi.getImageUrlByDate(date, '640x480', 'jpg')
}
// 查看图片详情

View File

@@ -38,14 +38,23 @@
<!-- 信息悬浮层类似 Windows 聚焦 -->
<div
v-if="showInfo"
class="absolute bottom-24 left-8 right-8 md:left-16 md:right-auto md:max-w-md bg-black/60 backdrop-blur-xl rounded-2xl p-6 transform transition-all duration-500 z-10"
:class="{ 'translate-y-0 opacity-100': showInfo, 'translate-y-4 opacity-0': !showInfo }"
ref="infoPanel"
class="fixed w-[90%] max-w-md bg-black/40 backdrop-blur-lg rounded-xl p-4 transform transition-opacity duration-300 z-10 select-none"
:style="{ left: infoPanelPos.x + 'px', top: infoPanelPos.y + 'px' }"
:class="{ 'opacity-100': showInfo, 'opacity-0': !showInfo }"
>
<h2 class="text-2xl font-bold text-white mb-3">
<!-- 拖动手柄 -->
<div
@mousedown="startDrag"
@touchstart="startDrag"
class="absolute top-2 left-1/2 -translate-x-1/2 w-12 h-1 bg-white/30 rounded-full cursor-move hover:bg-white/50 transition-colors touch-none"
></div>
<h2 class="text-lg font-bold text-white mb-2 mt-2">
{{ image.title || '未命名' }}
</h2>
<p v-if="image.copyright" class="text-white/80 text-sm mb-4 leading-relaxed">
<p v-if="image.copyright" class="text-white/80 text-xs mb-3 leading-relaxed">
{{ image.copyright }}
</p>
@@ -54,10 +63,10 @@
v-if="image.copyrightlink"
:href="image.copyrightlink"
target="_blank"
class="inline-flex items-center gap-2 px-4 py-2 bg-white/20 hover:bg-white/30 text-white rounded-lg text-sm font-medium transition-all group"
class="inline-flex items-center gap-2 px-3 py-1.5 bg-white/15 hover:bg-white/25 text-white rounded-lg text-xs font-medium transition-all group"
>
<span>了解更多信息</span>
<svg class="w-4 h-4 transform group-hover:translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<span>了解更多</span>
<svg class="w-3 h-3 transform group-hover:translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7l5 5m0 0l-5 5m5-5H6"></path>
</svg>
</a>
@@ -65,9 +74,9 @@
<!-- 切换信息显示按钮 -->
<button
@click="showInfo = false"
class="absolute top-4 right-4 p-2 hover:bg-white/10 rounded-lg transition-all"
class="absolute top-3 right-3 p-1.5 hover:bg-white/10 rounded-lg transition-all"
>
<svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<svg class="w-4 h-4 text-white/80" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
</svg>
</button>
@@ -132,7 +141,7 @@
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useImageByDate } from '@/composables/useImages'
import { bingPaperApi } from '@/lib/api-service'
@@ -144,13 +153,85 @@ const currentDate = ref(route.params.date as string)
const showInfo = ref(true)
const navigating = ref(false)
// 使用 composable 获取图片数据
const { image, loading, error, refetch } = useImageByDate(currentDate.value)
// 拖动相关状态
const infoPanel = ref<HTMLElement | null>(null)
const infoPanelPos = ref({ x: 0, y: 0 })
const isDragging = ref(false)
const dragStart = ref({ x: 0, y: 0 })
// 监听日期变化
watch(currentDate, () => {
refetch()
})
// 初始化浮窗位置(居中偏下)
const initPanelPosition = () => {
if (typeof window !== 'undefined') {
const windowWidth = window.innerWidth
const windowHeight = window.innerHeight
const panelWidth = Math.min(windowWidth * 0.9, 448) // max-w-md = 448px
infoPanelPos.value = {
x: (windowWidth - panelWidth) / 2,
y: windowHeight - 200 // 距底部200px
}
}
}
// 开始拖动
const startDrag = (e: MouseEvent | TouchEvent) => {
e.preventDefault()
isDragging.value = true
const clientX = e instanceof MouseEvent ? e.clientX : e.touches[0].clientX
const clientY = e instanceof MouseEvent ? e.clientY : e.touches[0].clientY
dragStart.value = {
x: clientX - infoPanelPos.value.x,
y: clientY - infoPanelPos.value.y
}
document.addEventListener('mousemove', onDrag)
document.addEventListener('mouseup', stopDrag)
document.addEventListener('touchmove', onDrag, { passive: false })
document.addEventListener('touchend', stopDrag)
}
// 拖动中
const onDrag = (e: MouseEvent | TouchEvent) => {
if (!isDragging.value) return
if (e instanceof TouchEvent) {
e.preventDefault()
}
const clientX = e instanceof MouseEvent ? e.clientX : e.touches[0].clientX
const clientY = e instanceof MouseEvent ? e.clientY : e.touches[0].clientY
const newX = clientX - dragStart.value.x
const newY = clientY - dragStart.value.y
// 限制在视口内
if (infoPanel.value) {
const rect = infoPanel.value.getBoundingClientRect()
const maxX = window.innerWidth - rect.width
const maxY = window.innerHeight - rect.height
infoPanelPos.value = {
x: Math.max(0, Math.min(newX, maxX)),
y: Math.max(0, Math.min(newY, maxY))
}
}
}
// 停止拖动
const stopDrag = () => {
isDragging.value = false
document.removeEventListener('mousemove', onDrag)
document.removeEventListener('mouseup', stopDrag)
document.removeEventListener('touchmove', onDrag)
document.removeEventListener('touchend', stopDrag)
}
// 使用 composable 获取图片数据(传递 ref自动响应日期变化
const { image, loading, error } = useImageByDate(currentDate)
// 初始化位置
initPanelPosition()
// 格式化日期
const formatDate = (dateStr?: string) => {
@@ -232,6 +313,7 @@ const handleKeydown = (e: KeyboardEvent) => {
// 添加键盘事件监听
if (typeof window !== 'undefined') {
window.addEventListener('keydown', handleKeydown)
window.addEventListener('resize', initPanelPosition)
}
// 清理
@@ -239,6 +321,11 @@ import { onUnmounted } from 'vue'
onUnmounted(() => {
if (typeof window !== 'undefined') {
window.removeEventListener('keydown', handleKeydown)
window.removeEventListener('resize', initPanelPosition)
document.removeEventListener('mousemove', onDrag)
document.removeEventListener('mouseup', stopDrag)
document.removeEventListener('touchmove', onDrag)
document.removeEventListener('touchend', stopDrag)
}
})
</script>