Revert "perf: optimize infinite list loading"

This reverts commit 2a6f9e3cc0.
This commit is contained in:
jxxghp
2026-05-15 23:08:56 +08:00
parent 2a6f9e3cc0
commit 7114c63e8f
10 changed files with 358 additions and 296 deletions
+4 -49
View File
@@ -1,15 +1,5 @@
import ColorThief from 'colorthief' import ColorThief from 'colorthief'
const DEFAULT_DOMINANT_COLOR = '#28A9E1'
const DOMINANT_COLOR_CACHE_LIMIT = 100
const colorThief = new ColorThief()
const dominantColorCache = new Map<string, Promise<string>>()
interface DominantColorOptions {
fallback?: string
quality?: number
}
// 将 RGB 转换为十六进制 // 将 RGB 转换为十六进制
function rgbStringToHex(rgbArray: number[]): string { function rgbStringToHex(rgbArray: number[]): string {
if (rgbArray.length !== 3 || rgbArray.some(isNaN)) throw new Error('Invalid RGB string format') if (rgbArray.length !== 3 || rgbArray.some(isNaN)) throw new Error('Invalid RGB string format')
@@ -24,46 +14,11 @@ function rgbStringToHex(rgbArray: number[]): string {
return `#${toHex(r)}${toHex(g)}${toHex(b)}` return `#${toHex(r)}${toHex(g)}${toHex(b)}`
} }
function getImageCacheKey(image: HTMLImageElement) {
return image.currentSrc || image.src || ''
}
function rememberDominantColor(key: string, colorPromise: Promise<string>) {
if (!key) return colorPromise
if (dominantColorCache.size >= DOMINANT_COLOR_CACHE_LIMIT) {
const firstKey = dominantColorCache.keys().next().value
if (firstKey) dominantColorCache.delete(firstKey)
}
dominantColorCache.set(key, colorPromise)
return colorPromise
}
// 提取主要颜色 // 提取主要颜色
export async function getDominantColor( export async function getDominantColor(image: HTMLImageElement): Promise<string> {
image: HTMLImageElement | undefined | null, const colorThief = new ColorThief()
options: DominantColorOptions = {}, const dominantColor = colorThief.getColor(image)
): Promise<string> { return rgbStringToHex(dominantColor)
const fallback = options.fallback ?? DEFAULT_DOMINANT_COLOR
if (!image) return fallback
const cacheKey = getImageCacheKey(image)
const cachedColor = cacheKey ? dominantColorCache.get(cacheKey) : undefined
if (cachedColor) return cachedColor
const colorPromise = Promise.resolve()
.then(() => {
const dominantColor = colorThief.getColor(image, options.quality ?? 20)
return rgbStringToHex(dominantColor)
})
.catch(error => {
console.warn('Failed to extract dominant color:', error)
return fallback
})
return rememberDominantColor(cacheKey, colorPromise)
} }
// 预加载图片 // 预加载图片
@@ -6,7 +6,6 @@ import { useDisplay } from 'vuetify'
import ProgressDialog from './ProgressDialog.vue' import ProgressDialog from './ProgressDialog.vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { mediaTypeDict } from '@/api/constants' import { mediaTypeDict } from '@/api/constants'
import type { InfiniteScrollDone } from '@/composables/usePaginatedInfiniteScroll'
// 国际化 // 国际化
const { t } = useI18n() const { t } = useI18n()
@@ -25,6 +24,9 @@ const emit = defineEmits(['close', 'save'])
// 订阅历史列表 // 订阅历史列表
const historyList = ref<Subscribe[]>([]) const historyList = ref<Subscribe[]>([])
// 当前加载数据
const currData = ref<Subscribe[]>([])
// 当前页 // 当前页
const currentPage = ref(1) const currentPage = ref(1)
@@ -44,7 +46,7 @@ const progressDialog = ref(false)
const progressText = ref('') const progressText = ref('')
// 调用API查询列表 // 调用API查询列表
async function loadHistory({ done }: { done: InfiniteScrollDone }) { async function loadHistory({ done }: { done: any }) {
// 如果正在加载中,直接返回 // 如果正在加载中,直接返回
if (loading.value) { if (loading.value) {
done('ok') done('ok')
@@ -55,7 +57,7 @@ async function loadHistory({ done }: { done: InfiniteScrollDone }) {
try { try {
// 设置加载中 // 设置加载中
loading.value = true loading.value = true
const currentData: Subscribe[] = await api.get(`subscribe/history/${props.type}`, { currData.value = await api.get(`subscribe/history/${props.type}`, {
params: { params: {
page: currentPage.value, page: currentPage.value,
count: pageSize.value, count: pageSize.value,
@@ -63,12 +65,12 @@ async function loadHistory({ done }: { done: InfiniteScrollDone }) {
}) })
// 标计为已请求完成 // 标计为已请求完成
isRefreshed.value = true isRefreshed.value = true
if (currentData.length === 0) { if (currData.value.length === 0) {
// 如果没有数据,跳出 // 如果没有数据,跳出
done('empty') done('empty')
} else { } else {
// 合并数据 // 合并数据
historyList.value.push(...currentData) historyList.value = [...historyList.value, ...currData.value]
// 页码+1 // 页码+1
currentPage.value++ currentPage.value++
// 返回加载成功 // 返回加载成功
@@ -1,87 +0,0 @@
import type { Ref } from 'vue'
import { nextTick } from 'vue'
export type InfiniteScrollStatus = 'ok' | 'empty' | 'loading' | 'error'
export type InfiniteScrollDone = (status: InfiniteScrollStatus) => void
interface InfiniteScrollPage<T> {
isLastPage?: boolean
items: T[]
}
interface LoadPaginatedInfiniteScrollOptions<T> {
advancePage: () => void
appendItems: (items: T[]) => void
done: InfiniteScrollDone
hasScroll?: () => boolean
loadPage: () => Promise<T[] | InfiniteScrollPage<T>>
loading: Ref<boolean>
markLoaded?: () => void
maxAutoLoadPages?: number
}
const DEFAULT_MAX_AUTO_LOAD_PAGES = 6
export function hasDocumentScroll() {
return document.body.scrollHeight - (window.innerHeight || document.documentElement.clientHeight) > 2
}
function normalizePageResult<T>(result: T[] | InfiniteScrollPage<T>): InfiniteScrollPage<T> {
if (Array.isArray(result)) {
return {
isLastPage: result.length === 0,
items: result,
}
}
return result
}
export async function loadPaginatedInfiniteScroll<T>({
advancePage,
appendItems,
done,
hasScroll = hasDocumentScroll,
loadPage,
loading,
markLoaded,
maxAutoLoadPages = DEFAULT_MAX_AUTO_LOAD_PAGES,
}: LoadPaginatedInfiniteScrollOptions<T>) {
if (loading.value) {
done('ok')
return
}
loading.value = true
let status: InfiniteScrollStatus = 'ok'
let loadedPages = 0
try {
do {
const { isLastPage, items } = normalizePageResult(await loadPage())
markLoaded?.()
if (isLastPage) {
status = 'empty'
break
}
if (items.length > 0) {
appendItems(items)
}
advancePage()
loadedPages += 1
await nextTick()
} while (!hasScroll() && loadedPages < maxAutoLoadPages)
} catch (error) {
console.error(error)
status = 'error'
} finally {
loading.value = false
done(status)
}
}
+69 -31
View File
@@ -4,7 +4,6 @@ import type { MediaInfo } from '@/api/types'
import MediaCard from '@/components/cards/MediaCard.vue' import MediaCard from '@/components/cards/MediaCard.vue'
import ProgressiveCardGrid from '@/components/misc/ProgressiveCardGrid.vue' import ProgressiveCardGrid from '@/components/misc/ProgressiveCardGrid.vue'
import NoDataFound from '@/components/NoDataFound.vue' import NoDataFound from '@/components/NoDataFound.vue'
import { loadPaginatedInfiniteScroll, type InfiniteScrollDone } from '@/composables/usePaginatedInfiniteScroll'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
const { t } = useI18n() const { t } = useI18n()
@@ -15,6 +14,11 @@ const props = defineProps({
params: Object as PropType<{ [key: string]: any }>, params: Object as PropType<{ [key: string]: any }>,
}) })
// 判断是否有滚动条
function hasScroll() {
return document.body.scrollHeight - (window.innerHeight || document.documentElement.clientHeight) > 2
}
// 当前页码 // 当前页码
const page = ref(1) const page = ref(1)
@@ -56,7 +60,7 @@ const dedupFields = [
function deduplicate(items: MediaInfo[]): MediaInfo[] { function deduplicate(items: MediaInfo[]): MediaInfo[] {
return items.filter(item => { return items.filter(item => {
const key = getMediaDedupKey(item) const key = dedupFields.map(field => String(item[field])).join('~')
if (seenKeys.has(key)) { if (seenKeys.has(key)) {
return false return false
} }
@@ -66,16 +70,7 @@ function deduplicate(items: MediaInfo[]): MediaInfo[] {
} }
function appendData(items: MediaInfo[]) { function appendData(items: MediaInfo[]) {
dataList.value.push(...items) dataList.value = dataList.value.concat(items)
triggerRef(dataList)
}
function getMediaDedupKey(item: MediaInfo) {
return dedupFields.map(field => String(item[field] ?? '')).join('~')
}
function getMediaItemKey(item: MediaInfo) {
return [getMediaDedupKey(item), item.title ?? ''].join('~')
} }
async function loadPageData() { async function loadPageData() {
@@ -84,30 +79,73 @@ async function loadPageData() {
}) })
return { return {
isLastPage: rawData.length === 0, rawCount: rawData.length,
items: deduplicate(rawData), uniqueData: deduplicate(rawData),
} }
} }
// 获取列表数据 // 获取列表数据
async function fetchData({ done }: { done: InfiniteScrollDone }) { async function fetchData({ done }: { done: any }) {
if (!props.apipath) { try {
done('empty') if (!props.apipath) return
return
}
await loadPaginatedInfiniteScroll({ // 如果正在加载中,直接返回
advancePage: () => { if (loading.value) {
page.value++ done('ok')
}, return
appendItems: appendData, }
done,
loadPage: loadPageData, // 加载到满屏或者加载出错
loading, if (!hasScroll()) {
markLoaded: () => { // 加载多次
while (!hasScroll()) {
// 设置加载中
loading.value = true
// 请求API
const { rawCount, uniqueData } = await loadPageData()
// 取消加载中
loading.value = false
// 标计为已请求完成
isRefreshed.value = true
if (rawCount === 0) {
// 如果没有数据,跳出
done('empty')
return
}
// 合并数据
appendData(uniqueData)
// 页码+1
page.value++
// 返回加载成功
done('ok')
}
} else {
// 加载一次
// 设置加载中
loading.value = true
// 请求API
const { rawCount, uniqueData } = await loadPageData()
// 标计为已请求完成
isRefreshed.value = true isRefreshed.value = true
}, if (rawCount === 0) {
}) // 如果没有数据,跳出
done('empty')
} else {
// 合并数据
appendData(uniqueData)
// 页码+1
page.value++
// 返回加载成功
done('ok')
}
}
// 取消加载中
loading.value = false
} catch (error) {
console.error(error)
// 返回加载失败
done('error')
}
} }
</script> </script>
@@ -120,7 +158,7 @@ async function fetchData({ done }: { done: InfiniteScrollDone }) {
v-if="dataList.length > 0" v-if="dataList.length > 0"
:items="dataList" :items="dataList"
:item-aspect-ratio="1.5" :item-aspect-ratio="1.5"
:get-item-key="getMediaItemKey" :get-item-key="item => item.tmdb_id || item.douban_id || item.bangumi_id || item.media_id || item.title"
tabindex="0" tabindex="0"
> >
<template #default="{ item }"> <template #default="{ item }">
+66 -19
View File
@@ -4,7 +4,6 @@ import type { Person } from '@/api/types'
import PersonCard from '@/components/cards/PersonCard.vue' import PersonCard from '@/components/cards/PersonCard.vue'
import ProgressiveCardGrid from '@/components/misc/ProgressiveCardGrid.vue' import ProgressiveCardGrid from '@/components/misc/ProgressiveCardGrid.vue'
import NoDataFound from '@/components/NoDataFound.vue' import NoDataFound from '@/components/NoDataFound.vue'
import { loadPaginatedInfiniteScroll, type InfiniteScrollDone } from '@/composables/usePaginatedInfiniteScroll'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
const { t } = useI18n() const { t } = useI18n()
@@ -16,6 +15,11 @@ const props = defineProps({
type: String, type: String,
}) })
// 判断是否有滚动条
function hasScroll() {
return document.body.scrollHeight - (window.innerHeight || document.documentElement.clientHeight) > 2
}
// 当前页码 // 当前页码
const page = ref(1) const page = ref(1)
@@ -29,8 +33,7 @@ const isRefreshed = ref(false)
const dataList = shallowRef<Person[]>([]) const dataList = shallowRef<Person[]>([])
function appendData(items: Person[]) { function appendData(items: Person[]) {
dataList.value.push(...items) dataList.value = dataList.value.concat(items)
triggerRef(dataList)
} }
async function loadPageData() { async function loadPageData() {
@@ -50,24 +53,68 @@ function getParams() {
} }
// 获取列表数据 // 获取列表数据
async function fetchData({ done }: { done: InfiniteScrollDone }) { async function fetchData({ done }: { done: any }) {
if (!props.apipath) { try {
done('empty') if (!props.apipath) return
return
}
await loadPaginatedInfiniteScroll({ // 如果正在加载中,直接返回
advancePage: () => { if (loading.value) {
page.value++ done('ok')
}, return
appendItems: appendData, }
done,
loadPage: loadPageData, // 加载到满屏或者加载出错
loading, if (!hasScroll()) {
markLoaded: () => { // 加载多次
while (!hasScroll()) {
// 设置加载中
loading.value = true
// 请求API
const currentData = await loadPageData()
// 取消加载中
loading.value = false
// 标计为已请求完成
isRefreshed.value = true
if (currentData.length === 0) {
// 如果没有数据,跳出
done('empty')
return
} else {
// 合并数据
appendData(currentData)
// 页码+1
page.value++
// 返回加载成功
done('ok')
}
}
} else {
// 加载一次
// 设置加载中
loading.value = true
// 请求API
const currentData = await loadPageData()
// 标计为已请求完成
isRefreshed.value = true isRefreshed.value = true
}, if (currentData.length === 0) {
}) // 如果没有数据,跳出
done('empty')
} else {
// 合并数据
appendData(currentData)
// 页码+1
page.value++
// 返回加载成功
done('ok')
}
// 取消加载中
loading.value = false
}
} catch (error) {
console.error(error)
// 返回加载失败
done('error')
}
} }
</script> </script>
+1 -7
View File
@@ -13,7 +13,6 @@ import PluginMixedSortCard from '@/components/cards/PluginMixedSortCard.vue'
import ProgressiveCardGrid from '@/components/misc/ProgressiveCardGrid.vue' import ProgressiveCardGrid from '@/components/misc/ProgressiveCardGrid.vue'
import { usePWA } from '@/composables/usePWA' import { usePWA } from '@/composables/usePWA'
import { useDynamicHeaderTab } from '@/composables/useDynamicHeaderTab' import { useDynamicHeaderTab } from '@/composables/useDynamicHeaderTab'
import type { InfiniteScrollDone } from '@/composables/usePaginatedInfiniteScroll'
// 国际化 // 国际化
const { t } = useI18n() const { t } = useI18n()
@@ -921,14 +920,9 @@ watch([dataList, installedFilter, hasUpdateFilter, enabledFilter], () => {
}) })
// 插件市场加载更多数据 // 插件市场加载更多数据
function loadMarketMore({ done }: { done: InfiniteScrollDone }) { function loadMarketMore({ done }: { done: any }) {
// 从 dataList 中获取最前面的 20 个元素 // 从 dataList 中获取最前面的 20 个元素
const itemsToMove = sortedUninstalledList.value.splice(0, 20) const itemsToMove = sortedUninstalledList.value.splice(0, 20)
if (itemsToMove.length === 0) {
done('empty')
return
}
displayUninstalledList.value.push(...itemsToMove) displayUninstalledList.value.push(...itemsToMove)
done('ok') done('ok')
} }
+69 -41
View File
@@ -4,7 +4,6 @@ import type { MediaInfo } from '@/api/types'
import MediaCard from '@/components/cards/MediaCard.vue' import MediaCard from '@/components/cards/MediaCard.vue'
import NoDataFound from '@/components/NoDataFound.vue' import NoDataFound from '@/components/NoDataFound.vue'
import ProgressiveCardGrid from '@/components/misc/ProgressiveCardGrid.vue' import ProgressiveCardGrid from '@/components/misc/ProgressiveCardGrid.vue'
import { loadPaginatedInfiniteScroll, type InfiniteScrollDone } from '@/composables/usePaginatedInfiniteScroll'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
// 国际化 // 国际化
@@ -15,6 +14,11 @@ const props = defineProps({
type: String, type: String,
}) })
// 判断是否有滚动条
function hasScroll() {
return document.body.scrollHeight - (window.innerHeight || document.documentElement.clientHeight) > 2
}
// API // API
const apipath = 'subscribe/popular' const apipath = 'subscribe/popular'
@@ -27,8 +31,9 @@ const loading = ref(false)
// 是否加载完成 // 是否加载完成
const isRefreshed = ref(false) const isRefreshed = ref(false)
// 使用 shallowRef 避免长列表中的深层代理开销 // 数据列表
const dataList = shallowRef<MediaInfo[]>([]) const dataList = ref<MediaInfo[]>([])
const currData = ref<MediaInfo[]>([])
// 筛选参数 // 筛选参数
const filterParams = reactive({ const filterParams = reactive({
@@ -131,45 +136,68 @@ function getParams() {
return params return params
} }
function appendData(items: MediaInfo[]) {
dataList.value.push(...items)
triggerRef(dataList)
}
async function loadPageData() {
return api.get(apipath, {
params: getParams(),
}) as Promise<MediaInfo[]>
}
function getMediaItemKey(item: MediaInfo) {
return [
item.source ?? '',
item.type ?? '',
item.season ?? '',
item.tmdb_id ?? '',
item.douban_id ?? '',
item.bangumi_id ?? '',
item.mediaid_prefix ?? '',
item.media_id ?? '',
item.title ?? '',
].join('~')
}
// 获取列表数据 // 获取列表数据
async function fetchData({ done }: { done: InfiniteScrollDone }) { async function fetchData({ done }: { done: any }) {
await loadPaginatedInfiniteScroll({ try {
advancePage: () => { // 如果正在加载中,直接返回
page.value++ if (loading.value) {
}, done('ok')
appendItems: appendData, return
done, }
loadPage: loadPageData,
loading, // 加载到满屏或者加载出错
markLoaded: () => { if (!hasScroll()) {
// 加载多次
while (!hasScroll()) {
// 设置加载中
loading.value = true
// 请求API
currData.value = await api.get(apipath, {
params: getParams(),
})
// 取消加载中
loading.value = false
// 标计为已请求完成
isRefreshed.value = true
if (currData.value.length === 0) {
// 如果没有数据,跳出
done('empty')
return
}
// 合并数据
dataList.value = [...dataList.value, ...currData.value]
// 页码+1
page.value++
// 返回加载成功
done('ok')
}
} else {
// 设置加载中
loading.value = true
// 请求API
currData.value = await api.get(apipath, {
params: getParams(),
})
loading.value = false
// 标计为已请求完成
isRefreshed.value = true isRefreshed.value = true
}, if (currData.value.length === 0) {
}) // 如果没有数据,跳出
done('empty')
} else {
// 合并数据
dataList.value = [...dataList.value, ...currData.value]
// 页码+1
page.value++
// 返回加载成功
done('ok')
}
}
} catch (error) {
console.error(error)
// 返回加载失败
done('error')
}
} }
</script> </script>
@@ -250,7 +278,7 @@ async function fetchData({ done }: { done: InfiniteScrollDone }) {
<ProgressiveCardGrid <ProgressiveCardGrid
v-if="dataList.length > 0" v-if="dataList.length > 0"
:items="dataList" :items="dataList"
:get-item-key="getMediaItemKey" :get-item-key="item => item.tmdb_id || item.douban_id || item.bangumi_id || item.media_id || item.title"
:min-item-width="144" :min-item-width="144"
:estimated-item-height="320" :estimated-item-height="320"
tabindex="0" tabindex="0"
+68 -26
View File
@@ -4,7 +4,6 @@ import type { SubscribeShare } from '@/api/types'
import NoDataFound from '@/components/NoDataFound.vue' import NoDataFound from '@/components/NoDataFound.vue'
import SubscribeShareCard from '@/components/cards/SubscribeShareCard.vue' import SubscribeShareCard from '@/components/cards/SubscribeShareCard.vue'
import ProgressiveCardGrid from '@/components/misc/ProgressiveCardGrid.vue' import ProgressiveCardGrid from '@/components/misc/ProgressiveCardGrid.vue'
import { loadPaginatedInfiniteScroll, type InfiniteScrollDone } from '@/composables/usePaginatedInfiniteScroll'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
// 国际化 // 国际化
@@ -16,6 +15,11 @@ const props = defineProps({
keyword: String, keyword: String,
}) })
// 判断是否有滚动条
function hasScroll() {
return document.body.scrollHeight - (window.innerHeight || document.documentElement.clientHeight) > 2
}
// API // API
const apipath = 'subscribe/shares' const apipath = 'subscribe/shares'
@@ -117,8 +121,9 @@ const loading = ref(false)
// 是否加载完成 // 是否加载完成
const isRefreshed = ref(false) const isRefreshed = ref(false)
// 使用 shallowRef 避免长列表中的深层代理开销 // 数据列表
const dataList = shallowRef<SubscribeShare[]>([]) const dataList = ref<SubscribeShare[]>([])
const currData = ref<SubscribeShare[]>([])
// 拼装参数 // 拼装参数
function getParams() { function getParams() {
@@ -145,31 +150,68 @@ function getParams() {
return params return params
} }
function appendData(items: SubscribeShare[]) {
dataList.value.push(...items)
triggerRef(dataList)
}
async function loadPageData() {
return api.get(apipath, {
params: getParams(),
}) as Promise<SubscribeShare[]>
}
// 获取列表数据 // 获取列表数据
async function fetchData({ done }: { done: InfiniteScrollDone }) { async function fetchData({ done }: { done: any }) {
await loadPaginatedInfiniteScroll({ try {
advancePage: () => { // 如果正在加载中,直接返回
page.value++ if (loading.value) {
}, done('ok')
appendItems: appendData, return
done, }
loadPage: loadPageData,
loading, // 加载到满屏或者加载出错
markLoaded: () => { if (!hasScroll()) {
// 加载多次
while (!hasScroll()) {
// 设置加载中
loading.value = true
// 请求API
currData.value = await api.get(apipath, {
params: getParams(),
})
// 取消加载中
loading.value = false
// 标计为已请求完成
isRefreshed.value = true
if (currData.value.length === 0) {
// 如果没有数据,跳出
done('empty')
return
}
// 合并数据
dataList.value = [...dataList.value, ...currData.value]
// 页码+1
page.value++
// 返回加载成功
done('ok')
}
} else {
// 设置加载中
loading.value = true
// 请求API
currData.value = await api.get(apipath, {
params: getParams(),
})
loading.value = false
// 标计为已请求完成
isRefreshed.value = true isRefreshed.value = true
}, if (currData.value.length === 0) {
}) // 如果没有数据,跳出
done('empty')
} else {
// 合并数据
dataList.value = [...dataList.value, ...currData.value]
// 页码+1
page.value++
// 返回加载成功
done('ok')
}
}
} catch (error) {
console.error(error)
// 返回加载失败
done('error')
}
} }
// 将数据从列表中移除 // 将数据从列表中移除
+6 -5
View File
@@ -4,7 +4,6 @@ import MessageCard from '@/components/cards/MessageCard.vue'
import api from '@/api' import api from '@/api'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { useBackgroundOptimization } from '@/composables/useBackgroundOptimization' import { useBackgroundOptimization } from '@/composables/useBackgroundOptimization'
import type { InfiniteScrollDone } from '@/composables/usePaginatedInfiniteScroll'
// 国际化 // 国际化
const { t } = useI18n() const { t } = useI18n()
@@ -12,6 +11,8 @@ const { useSSE } = useBackgroundOptimization()
// 消息列表 // 消息列表
const messages = ref<Message[]>([]) const messages = ref<Message[]>([])
// 当前页数据
const currData = ref<Message[]>([])
// 已加载消息的签名集合 // 已加载消息的签名集合
// 使用消息内容签名去重,避免仅按秒级时间戳判断时误吞同一秒内的不同消息。 // 使用消息内容签名去重,避免仅按秒级时间戳判断时误吞同一秒内的不同消息。
@@ -213,7 +214,7 @@ const { manager, isConnected } = useSSE(
) )
// 调用API加载存量消息 // 调用API加载存量消息
async function loadMessages({ done }: { done: InfiniteScrollDone }) { async function loadMessages({ done }: { done: any }) {
// 如果正在加载中,直接返回 // 如果正在加载中,直接返回
if (loading.value) { if (loading.value) {
done('ok') done('ok')
@@ -222,7 +223,7 @@ async function loadMessages({ done }: { done: InfiniteScrollDone }) {
try { try {
// 设置加载中 // 设置加载中
loading.value = true loading.value = true
const currentData: Message[] = await api.get('message/web', { currData.value = await api.get('message/web', {
params: { params: {
page: page.value, page: page.value,
size: 20, size: 20,
@@ -230,8 +231,8 @@ async function loadMessages({ done }: { done: InfiniteScrollDone }) {
}) })
// 已加载过 // 已加载过
isLoaded.value = true isLoaded.value = true
if (currentData.length > 0) { if (currData.value.length > 0) {
const hasNewMessage = mergeMessages(currentData) const hasNewMessage = mergeMessages(currData.value)
// 首次加载时滚动到底部 // 首次加载时滚动到底部
if (page.value === 1 && hasNewMessage) { if (page.value === 1 && hasNewMessage) {
+68 -26
View File
@@ -4,7 +4,6 @@ import type { WorkflowShare } from '@/api/types'
import NoDataFound from '@/components/NoDataFound.vue' import NoDataFound from '@/components/NoDataFound.vue'
import WorkflowShareCard from '@/components/cards/WorkflowShareCard.vue' import WorkflowShareCard from '@/components/cards/WorkflowShareCard.vue'
import ProgressiveCardGrid from '@/components/misc/ProgressiveCardGrid.vue' import ProgressiveCardGrid from '@/components/misc/ProgressiveCardGrid.vue'
import { loadPaginatedInfiniteScroll, type InfiniteScrollDone } from '@/composables/usePaginatedInfiniteScroll'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
// 国际化 // 国际化
@@ -19,6 +18,11 @@ const props = defineProps({
// 定义事件 // 定义事件
const emit = defineEmits(['update']) const emit = defineEmits(['update'])
// 判断是否有滚动条
function hasScroll() {
return document.body.scrollHeight - (window.innerHeight || document.documentElement.clientHeight) > 2
}
// API // API
const apipath = 'workflow/shares' const apipath = 'workflow/shares'
@@ -35,8 +39,9 @@ const loading = ref(false)
// 是否加载完成 // 是否加载完成
const isRefreshed = ref(false) const isRefreshed = ref(false)
// 使用 shallowRef 避免长列表中的深层代理开销 // 数据列表
const dataList = shallowRef<WorkflowShare[]>([]) const dataList = ref<WorkflowShare[]>([])
const currData = ref<WorkflowShare[]>([])
// 事件类型列表 // 事件类型列表
const eventTypes = ref<Array<{ title: string; value: string }>>([]) const eventTypes = ref<Array<{ title: string; value: string }>>([])
@@ -71,31 +76,68 @@ function getParams() {
return params return params
} }
function appendData(items: WorkflowShare[]) {
dataList.value.push(...items)
triggerRef(dataList)
}
async function loadPageData() {
return api.get(apipath, {
params: getParams(),
}) as Promise<WorkflowShare[]>
}
// 获取列表数据 // 获取列表数据
async function fetchData({ done }: { done: InfiniteScrollDone }) { async function fetchData({ done }: { done: any }) {
await loadPaginatedInfiniteScroll({ try {
advancePage: () => { // 如果正在加载中,直接返回
page.value++ if (loading.value) {
}, done('ok')
appendItems: appendData, return
done, }
loadPage: loadPageData,
loading, // 加载到满屏或者加载出错
markLoaded: () => { if (!hasScroll()) {
// 加载多次
while (!hasScroll()) {
// 设置加载中
loading.value = true
// 请求API
currData.value = await api.get(apipath, {
params: getParams(),
})
// 取消加载中
loading.value = false
// 标计为已请求完成
isRefreshed.value = true
if (currData.value.length === 0) {
// 如果没有数据,跳出
done('empty')
return
}
// 合并数据
dataList.value = [...dataList.value, ...currData.value]
// 页码+1
page.value++
// 返回加载成功
done('ok')
}
} else {
// 设置加载中
loading.value = true
// 请求API
currData.value = await api.get(apipath, {
params: getParams(),
})
loading.value = false
// 标计为已请求完成
isRefreshed.value = true isRefreshed.value = true
}, if (currData.value.length === 0) {
}) // 如果没有数据,跳出
done('empty')
} else {
// 合并数据
dataList.value = [...dataList.value, ...currData.value]
// 页码+1
page.value++
// 返回加载成功
done('ok')
}
}
} catch (error) {
console.error(error)
// 返回加载失败
done('error')
}
} }
// 将数据从列表中移除 // 将数据从列表中移除