Compare commits

..

11 Commits

17 changed files with 412 additions and 131 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "moviepilot",
"version": "2.11.3",
"version": "2.11.4",
"private": true,
"type": "module",
"bin": "dist/service.js",

View File

@@ -1,5 +1,15 @@
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 转换为十六进制
function rgbStringToHex(rgbArray: number[]): string {
if (rgbArray.length !== 3 || rgbArray.some(isNaN)) throw new Error('Invalid RGB string format')
@@ -14,11 +24,46 @@ function rgbStringToHex(rgbArray: number[]): string {
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(image: HTMLImageElement): Promise<string> {
const colorThief = new ColorThief()
const dominantColor = colorThief.getColor(image)
return rgbStringToHex(dominantColor)
export async function getDominantColor(
image: HTMLImageElement | undefined | null,
options: DominantColorOptions = {},
): Promise<string> {
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)
}
// 预加载图片

View File

@@ -252,7 +252,7 @@ const dropdownItems = ref([
</div>
</div>
<div class="absolute bottom-0 right-0">
<IconBtn>
<IconBtn @click.stop>
<VIcon size="small" icon="mdi-dots-vertical" />
<VMenu activator="parent" close-on-content-click>
<VList>
@@ -273,7 +273,7 @@ const dropdownItems = ref([
<!-- 安装插件进度框 -->
<ProgressDialog v-if="progressDialog" v-model="progressDialog" :text="progressText" />
<!-- 更新日志 -->
<VDialog v-if="releaseDialog" v-model="releaseDialog" width="600" scrollable>
<VDialog v-if="releaseDialog" v-model="releaseDialog" width="600" max-height="85vh" scrollable>
<VCard :title="t('plugin.updateHistoryTitle', { name: props.plugin?.plugin_name })">
<VDialogCloseBtn @click="releaseDialog = false" />
<VDivider />

View File

@@ -475,7 +475,10 @@ watch(
{{ props.plugin?.plugin_desc }}
</div>
</div>
<div class="relative flex-shrink-0 self-center pb-3" :class="{ 'cursor-move': props.sortable && display.mdAndUp.value }">
<div
class="relative flex-shrink-0 self-center pb-3"
:class="{ 'cursor-move': props.sortable && display.mdAndUp.value }"
>
<VAvatar size="48">
<VImg
ref="imageRef"
@@ -518,7 +521,7 @@ watch(
</span>
</div>
<div v-if="!props.sortable" class="absolute bottom-0 right-0">
<IconBtn>
<IconBtn @click.stop>
<VIcon icon="mdi-dots-vertical" />
<VMenu v-model="menuVisible" activator="parent" close-on-content-click>
<VList>
@@ -569,7 +572,7 @@ watch(
<ProgressDialog v-if="progressDialog" v-model="progressDialog" :text="progressText" />
<!-- 更新日志 -->
<VDialog v-if="releaseDialog" v-model="releaseDialog" width="600" scrollable :fullscreen="!display.mdAndUp.value">
<VDialog v-if="releaseDialog" v-model="releaseDialog" width="600" scrollable max-height="85vh">
<VCard :title="t('plugin.updateHistoryTitle', { name: props.plugin?.plugin_name })">
<VDialogCloseBtn @click="releaseDialog = false" />
<VDivider />
@@ -587,13 +590,13 @@ watch(
</VDialog>
<!-- 实时日志弹窗 -->
<VDialog
v-if="loggingDialog"
v-model="loggingDialog"
scrollable
max-width="72rem"
:fullscreen="!display.mdAndUp.value"
>
<VDialog
v-if="loggingDialog"
v-model="loggingDialog"
scrollable
max-width="72rem"
:fullscreen="!display.mdAndUp.value"
>
<VCard>
<VDialogCloseBtn @click="loggingDialog = false" />
<VCardItem>

View File

@@ -386,7 +386,7 @@ onMounted(() => {
</VBtn>
<!-- 更多选项按钮 -->
<VBtn icon variant="text" class="mt-auto" size="36">
<VBtn icon variant="text" class="mt-auto" size="36" @click.stop>
<VIcon icon="mdi-dots-vertical" size="20" />
<VMenu :activator="'parent'" :close-on-content-click="true" :location="'left'">
<VList>

View File

@@ -372,7 +372,7 @@ function handleCardClick() {
:ripple="!props.batchMode && !props.sortable"
>
<div v-if="!props.sortable" class="me-n3 absolute top-1 right-4">
<IconBtn>
<IconBtn @click.stop>
<VIcon icon="mdi-dots-vertical" color="white" />
<VMenu activator="parent" close-on-content-click>
<VList>

View File

@@ -202,12 +202,7 @@ onMounted(() => {
<dd class="flex text-sm sm:col-span-2 sm:mt-0">
<span class="flex-grow flex flex-row items-center truncate">
<code class="truncate">{{ appVersion }}</code>
<VBtn
size="x-small"
variant="tonal"
class="ms-2"
@click="clearCache"
>
<VBtn size="x-small" variant="tonal" class="ms-2" @click="clearCache">
<template #prepend>
<VIcon icon="mdi-refresh" size="14" />
</template>
@@ -402,7 +397,7 @@ onMounted(() => {
</div>
</VCardText>
</VCard>
<VDialog v-if="releaseDialog" v-model="releaseDialog" width="600" scrollable>
<VDialog v-if="releaseDialog" v-model="releaseDialog" width="600" scrollable max-height="85vh">
<VCard>
<VCardItem>
<VDialogCloseBtn @click="releaseDialog = false" />
@@ -430,8 +425,8 @@ onMounted(() => {
.markdown-body :deep(h1),
.markdown-body :deep(h2),
.markdown-body :deep(h3) {
margin-block: 0.5rem;
font-weight: 600;
margin-block: 0.5rem;
}
.markdown-body :deep(h1) {
@@ -448,8 +443,8 @@ onMounted(() => {
.markdown-body :deep(ul),
.markdown-body :deep(ol) {
padding-inline-start: 1.5rem;
margin-block: 0.5rem;
padding-inline-start: 1.5rem;
}
.markdown-body :deep(li) {
@@ -470,18 +465,20 @@ onMounted(() => {
}
.markdown-body :deep(code) {
padding: 0.15rem 0.4rem;
border-radius: 0.25rem;
background-color: rgba(127, 127, 127, 15%);
font-size: 0.875em;
background-color: rgba(127, 127, 127, 0.15);
padding-block: 0.15rem;
padding-inline: 0.4rem;
}
.markdown-body :deep(pre) {
padding: 0.75rem 1rem;
border-radius: 0.375rem;
background-color: rgba(127, 127, 127, 15%);
margin-block: 0.5rem;
overflow-x: auto;
border-radius: 0.375rem;
background-color: rgba(127, 127, 127, 0.15);
padding-block: 0.75rem;
padding-inline: 1rem;
}
.markdown-body :deep(pre code) {
@@ -490,37 +487,38 @@ onMounted(() => {
}
.markdown-body :deep(blockquote) {
padding-inline-start: 1rem;
border-inline-start: 3px solid rgba(127, 127, 127, 40%);
color: rgba(127, 127, 127, 80%);
margin-block: 0.5rem;
border-inline-start: 3px solid rgba(127, 127, 127, 0.4);
color: rgba(127, 127, 127, 0.8);
padding-inline-start: 1rem;
}
.markdown-body :deep(hr) {
margin-block: 1rem;
border: none;
border-block-start: 1px solid rgba(127, 127, 127, 0.3);
border-block-start: 1px solid rgba(127, 127, 127, 30%);
margin-block: 1rem;
}
.markdown-body :deep(table) {
width: 100%;
margin-block: 0.5rem;
border-collapse: collapse;
inline-size: 100%;
margin-block: 0.5rem;
}
.markdown-body :deep(th),
.markdown-body :deep(td) {
padding: 0.4rem 0.75rem;
border: 1px solid rgba(127, 127, 127, 0.3);
border: 1px solid rgba(127, 127, 127, 30%);
padding-block: 0.4rem;
padding-inline: 0.75rem;
}
.markdown-body :deep(th) {
background-color: rgba(127, 127, 127, 10%);
font-weight: 600;
background-color: rgba(127, 127, 127, 0.1);
}
.markdown-body :deep(img) {
max-width: 100%;
height: auto;
block-size: auto;
max-inline-size: 100%;
}
</style>

View File

@@ -38,6 +38,13 @@ interface VirtualCell {
key: ItemKey
}
interface VirtualRange {
endIndex: number
endRow: number
startIndex: number
startRow: number
}
const containerRef = ref<HTMLElement | null>(null)
const trackRef = ref<HTMLElement | null>(null)
@@ -45,6 +52,8 @@ const layoutWidth = ref(0)
const viewportTop = ref(0)
const viewportBottom = ref(0)
const heightVersion = ref(0)
const frozenVisibleRange = ref<VirtualRange | null>(null)
const isOverlayGrid = ref(false)
const itemHeights = new Map<ItemKey, number>()
const observedElements = new Map<HTMLElement, ItemKey>()
@@ -53,6 +62,7 @@ const itemRefCallbacks = new Map<ItemKey, (element: Element | ComponentPublicIns
let resizeObserver: ResizeObserver | null = null
let itemResizeObserver: ResizeObserver | null = null
let overlayLockObserver: MutationObserver | null = null
let scrollTarget: ScrollTarget | null = null
let layoutFrameId: number | null = null
let scrollFrameId: number | null = null
@@ -149,7 +159,18 @@ const rowMetrics = computed(() => {
const totalHeight = computed(() => rowMetrics.value.totalHeight)
const visibleRange = computed(() => {
const calculatedVisibleRange = computed<VirtualRange>(() => {
if (isOverlayGrid.value) {
const rowCount = Math.max(1, Math.ceil(props.items.length / columnCount.value))
return {
endIndex: props.items.length,
endRow: rowCount - 1,
startIndex: 0,
startRow: 0,
}
}
const { heights, offsets, rowCount } = rowMetrics.value
if (!props.items.length || rowCount === 0) {
@@ -176,6 +197,8 @@ const visibleRange = computed(() => {
}
})
const visibleRange = computed(() => frozenVisibleRange.value ?? calculatedVisibleRange.value)
const visibleCells = computed<VirtualCell[]>(() => {
const cells: VirtualCell[] = []
@@ -190,7 +213,13 @@ const visibleCells = computed<VirtualCell[]>(() => {
return cells
})
const topSpacerHeight = computed(() => rowMetrics.value.offsets[visibleRange.value.startRow] ?? 0)
const topSpacerHeight = computed(() => {
if (isOverlayGrid.value) {
return 0
}
return rowMetrics.value.offsets[visibleRange.value.startRow] ?? 0
})
const visibleBlockHeight = computed(() => {
if (!props.items.length || visibleRange.value.endIndex <= visibleRange.value.startIndex) {
@@ -206,6 +235,10 @@ const visibleBlockHeight = computed(() => {
})
const bottomSpacerHeight = computed(() => {
if (isOverlayGrid.value) {
return 0
}
return Math.max(totalHeight.value - topSpacerHeight.value - visibleBlockHeight.value, 0)
})
@@ -266,6 +299,45 @@ function findLastRowAtOrBeforeOffset(offsets: number[], rowCount: number, offset
return answer
}
function isDocumentOverlayLocked() {
return typeof document !== 'undefined' && document.documentElement.classList.contains('v-overlay-scroll-blocked')
}
function isGridInsideOverlay() {
return Boolean(containerRef.value?.closest('.v-overlay, .v-overlay__content'))
}
function syncOverlayGridState() {
isOverlayGrid.value = isGridInsideOverlay()
}
function shouldPauseVirtualSync() {
return isDocumentOverlayLocked() && !isOverlayGrid.value
}
function freezeVisibleRange() {
if (frozenVisibleRange.value) {
return
}
// 弹窗打开期间固定当前渲染窗口,防止 body 锁滚动造成坐标跳变并卸载触发弹窗的卡片。
frozenVisibleRange.value = { ...calculatedVisibleRange.value }
}
function releaseVisibleRange() {
frozenVisibleRange.value = null
}
function handleOverlayLockChange() {
if (shouldPauseVirtualSync()) {
freezeVisibleRange()
return
}
releaseVisibleRange()
queueLayoutSync()
}
function getElementFromRef(element: Element | ComponentPublicInstance | null): HTMLElement | null {
if (!element || typeof HTMLElement === 'undefined') {
return null
@@ -312,6 +384,11 @@ function ensureItemResizeObserver() {
}
itemResizeObserver = new ResizeObserver(entries => {
if (shouldPauseVirtualSync()) {
freezeVisibleRange()
return
}
let shouldUpdate = false
let scrollAdjustment = 0
const currentViewportTop = viewportTop.value
@@ -506,6 +583,15 @@ function queueLayoutSync() {
layoutFrameId = window.requestAnimationFrame(() => {
layoutFrameId = null
if (shouldPauseVirtualSync()) {
freezeVisibleRange()
return
}
// 弹窗内容已经由 overlay 限定生命周期,直接完整渲染可避免弹窗内交互被虚拟回收打断。
syncOverlayGridState()
releaseVisibleRange()
syncLayoutWidth()
refreshScrollTarget()
syncViewport()
@@ -520,6 +606,13 @@ function queueViewportSync() {
scrollFrameId = window.requestAnimationFrame(() => {
scrollFrameId = null
if (shouldPauseVirtualSync()) {
freezeVisibleRange()
return
}
releaseVisibleRange()
syncViewport()
})
}
@@ -681,6 +774,7 @@ function invalidateMeasurementsForLayoutChange() {
onMounted(() => {
mounted = true
syncOverlayGridState()
scrollTarget = findScrollTarget()
addScrollListener(scrollTarget)
@@ -689,6 +783,14 @@ onMounted(() => {
resizeObserver.observe(trackRef.value)
}
if (typeof MutationObserver !== 'undefined') {
overlayLockObserver = new MutationObserver(handleOverlayLockChange)
overlayLockObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class'],
})
}
window.addEventListener('resize', queueLayoutSync, { passive: true })
queueLayoutSync()
@@ -716,6 +818,8 @@ onUnmounted(() => {
resizeObserver = null
itemResizeObserver?.disconnect()
itemResizeObserver = null
overlayLockObserver?.disconnect()
overlayLockObserver = null
if (layoutFrameId !== null) {
window.cancelAnimationFrame(layoutFrameId)

View File

@@ -9,6 +9,7 @@ type MessageViewExpose = {
pauseSSE?: () => void
resumeSSE?: () => void
refreshLatestMessages?: () => Promise<void> | void
forceScrollToEnd?: () => void
}
// 国际化
@@ -67,15 +68,9 @@ const user_message = ref('')
// 发送按钮是否可用
const sendButtonDisabled = ref(false)
// 消息对话框引用
const messageDialogRef = ref<any>(null)
// 消息视图引用
const messageViewRef = ref<MessageViewExpose | null>(null)
// 滚动容器引用
const messageContentRef = ref<any>()
// 定义捷径列表
const shortcuts = [
{
@@ -148,58 +143,9 @@ function openDialog(dialogRef: any) {
dialogRef.value = true
}
// 打开消息弹窗并清除徽章
async function openMessageDialog() {
// 打开消息弹窗
function openMessageDialog() {
messageDialog.value = true
// 延迟清除徽章,确保对话框已经打开
setTimeout(async () => {
await clearAppBadge()
}, 500)
// 延迟滚动到底部,确保弹窗完全打开
setTimeout(() => {
forceScrollToEnd()
}, 600)
// 等待对话框打开后恢复SSE连接
nextTick(() => {
messageViewRef.value?.resumeSSE?.()
})
}
// 智能滚动到底部(只有用户在底部附近时才滚动)
function scrollMessageToEnd() {
// 使用更长的延迟确保DOM已更新
setTimeout(() => {
try {
// 查找消息弹窗的滚动容器
const cardText = document.querySelector('.v-dialog .v-card-text')
if (cardText) {
const { scrollTop, scrollHeight, clientHeight } = cardText
// 计算距离底部的距离
const distanceFromBottom = scrollHeight - scrollTop - clientHeight
// 如果用户距离底部小于1/3屏幕高度认为用户在底部附近执行自动滚动
if (distanceFromBottom <= clientHeight / 3) {
cardText.scrollTop = cardText.scrollHeight
}
}
} catch (error) {
console.error(error)
}
}, 500) // 增加延迟时间
}
// 强制滚动到底部(用于发送消息后)
function forceScrollToEnd() {
setTimeout(() => {
try {
// 查找消息弹窗的滚动容器
const cardText = document.querySelector('.v-dialog .v-card-text')
if (cardText) {
cardText.scrollTop = cardText.scrollHeight
}
} catch (error) {
console.error(error)
}
}, 500)
}
// 拼接全部日志url
@@ -221,7 +167,7 @@ async function sendMessage() {
// 发送成功后主动同步最新一页消息避免SSE短暂断流时界面停留在旧状态。
// await messageViewRef.value?.refreshLatestMessages?.()
forceScrollToEnd() // 发送消息后强制滚动到底部
messageViewRef.value?.forceScrollToEnd?.()
} catch (error) {
console.error(error)
} finally {
@@ -240,8 +186,20 @@ defineExpose({
})
// 监听消息对话框状态变化
watch(messageDialog, newValue => {
if (!newValue && messageViewRef.value?.pauseSSE) {
watch(messageDialog, async newValue => {
if (newValue) {
await nextTick()
messageViewRef.value?.resumeSSE?.()
messageViewRef.value?.forceScrollToEnd?.()
window.setTimeout(() => {
void clearAppBadge()
}, 500)
return
}
if (messageViewRef.value?.pauseSSE) {
// 对话框关闭时暂停SSE连接
messageViewRef.value.pauseSSE()
}
@@ -496,7 +454,6 @@ onMounted(() => {
max-width="50rem"
scrollable
:fullscreen="!display.mdAndUp.value"
ref="messageDialogRef"
>
<VCard>
<VCardItem>
@@ -507,8 +464,8 @@ onMounted(() => {
<VDialogCloseBtn @click="messageDialog = false" />
</VCardItem>
<VDivider />
<VCardText ref="messageContentRef">
<MessageView ref="messageViewRef" @scroll="scrollMessageToEnd" />
<VCardText>
<MessageView ref="messageViewRef" />
</VCardText>
<VDivider />
<VCardActions class="pa-4">

View File

@@ -39,6 +39,14 @@ interface SearchParams {
sites: string
}
interface LastSearchContextResponse {
success?: boolean
data?: {
params?: Partial<SearchParams>
results?: Context[]
}
}
const resourceSearchParamsStorageKey = 'MP_ResourceSearchParams'
function createSearchParams(query: LocationQuery): SearchParams {
@@ -106,10 +114,55 @@ function rememberSearchParams(params: SearchParams) {
saveStoredSearchParams(nextParams)
}
function applyRememberedSearchParams(params?: Partial<SearchParams> | null, syncActive: boolean = false) {
const nextParams = normalizeSearchParams(params)
if (!hasSearchKeyword(nextParams)) return null
rememberSearchParams(nextParams)
if (syncActive || !hasSearchKeyword(activeSearchParams.value)) {
activeSearchParams.value = { ...nextParams }
}
return nextParams
}
if (hasSearchKeyword(initialSearchParams)) {
rememberSearchParams(initialSearchParams)
}
async function fetchLastSearchContext() {
try {
const result = (await api.get('search/last/context')) as LastSearchContextResponse
applyRememberedSearchParams(result?.data?.params, true)
return Array.isArray(result?.data?.results) ? result.data.results : []
} catch (error) {
console.warn('读取上次搜索上下文失败,回退到仅加载结果:', error)
const results = await api.get('search/last')
return (results as unknown as Context[]) || []
}
}
async function resolveRefreshSearchParams() {
if (hasSearchKeyword(activeSearchParams.value)) {
return { ...activeSearchParams.value }
}
if (lastSearchParams.value && hasSearchKeyword(lastSearchParams.value)) {
return { ...lastSearchParams.value }
}
const storedParams = loadStoredSearchParams()
if (storedParams) {
applyRememberedSearchParams(storedParams, true)
return { ...storedParams }
}
await fetchLastSearchContext()
if (lastSearchParams.value && hasSearchKeyword(lastSearchParams.value)) {
return { ...lastSearchParams.value }
}
return null
}
// 查询TMDBID或标题
const keyword = computed(() => activeSearchParams.value.keyword)
@@ -612,11 +665,9 @@ async function fetchData(options: { force?: boolean; params?: SearchParams } = {
try {
enableFilterAnimation.value = true
if (!hasSearchKeyword(currentSearchParams)) {
// 查询上次搜索结果
const results = await api.get('search/last', {
params: requestToken ? { _ts: requestToken } : undefined,
})
setStreamResults((results as unknown as Context[]) || [])
// 查询上次搜索结果,并同步可重放的搜索参数
const results = await fetchLastSearchContext()
setStreamResults(results || [])
} else {
resetSearchResults()
startLoadingProgress()
@@ -646,11 +697,15 @@ async function fetchData(options: { force?: boolean; params?: SearchParams } = {
// 重新搜索(使用相同参数重新触发搜索)
async function refreshSearch() {
if (isRefreshing.value || progressActive.value) return
const refreshParams = lastSearchParams.value ?? activeSearchParams.value
isRefreshing.value = true
try {
// 重新搜索时退出 AI 视图,其余状态由 fetchData 内部重置
showingAiResults.value = false
const refreshParams = await resolveRefreshSearchParams()
if (!refreshParams) {
console.warn('未找到可用于重新搜索的搜索参数')
return
}
await fetchData({ force: true, params: refreshParams })
} catch (error) {
console.error('重新搜索失败:', error)

View File

@@ -118,6 +118,7 @@ async function fetchData({ done }: { done: any }) {
page.value++
// 返回加载成功
done('ok')
await nextTick()
}
} else {
// 加载一次

View File

@@ -86,6 +86,7 @@ async function fetchData({ done }: { done: any }) {
page.value++
// 返回加载成功
done('ok')
await nextTick()
}
}
} else {

View File

@@ -923,6 +923,11 @@ watch([dataList, installedFilter, hasUpdateFilter, enabledFilter], () => {
function loadMarketMore({ done }: { done: any }) {
// 从 dataList 中获取最前面的 20 个元素
const itemsToMove = sortedUninstalledList.value.splice(0, 20)
if (itemsToMove.length === 0) {
done('empty')
return
}
displayUninstalledList.value.push(...itemsToMove)
done('ok')
}

View File

@@ -170,6 +170,7 @@ async function fetchData({ done }: { done: any }) {
page.value++
// 返回加载成功
done('ok')
await nextTick()
}
} else {
// 设置加载中

View File

@@ -184,6 +184,7 @@ async function fetchData({ done }: { done: any }) {
page.value++
// 返回加载成功
done('ok')
await nextTick()
}
} else {
// 设置加载中

View File

@@ -9,9 +9,6 @@ import { useBackgroundOptimization } from '@/composables/useBackgroundOptimizati
const { t } = useI18n()
const { useSSE } = useBackgroundOptimization()
// 定义事件
const emit = defineEmits(['scroll'])
// 消息列表
const messages = ref<Message[]>([])
// 当前页数据
@@ -33,6 +30,18 @@ const page = ref(1)
// 存量消息最新时间
const lastTime = ref('')
// 消息列表滚动容器
const messageListRef = ref<any>(null)
// 自动滚动状态
const shouldAutoScroll = ref(true)
const isSyncingScroll = ref(false)
const MESSAGE_AUTO_SCROLL_THRESHOLD = 64
let scrollTimer: number | undefined
let scrollReleaseTimer: number | undefined
// 获取消息时间
function getMessageTime(message: Message) {
return message.reg_time || message.date || ''
@@ -66,6 +75,98 @@ function updateLastTime(message: Message) {
}
}
function getScrollContainer() {
const container = messageListRef.value?.$el ?? messageListRef.value
return container instanceof HTMLElement ? container : null
}
function isNearBottom(container: HTMLElement) {
const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight
return distanceFromBottom <= Math.max(MESSAGE_AUTO_SCROLL_THRESHOLD, container.clientHeight / 3)
}
function updateAutoScrollState() {
const container = getScrollContainer()
if (!container || isSyncingScroll.value) {
return
}
shouldAutoScroll.value = isNearBottom(container)
}
function handleScroll() {
updateAutoScrollState()
}
function bindScrollListener() {
const container = getScrollContainer()
if (!container) {
return
}
container.removeEventListener('scroll', handleScroll)
container.addEventListener('scroll', handleScroll, { passive: true })
updateAutoScrollState()
}
function unbindScrollListener() {
getScrollContainer()?.removeEventListener('scroll', handleScroll)
}
function scrollContainerToEnd() {
const container = getScrollContainer()
if (!container) {
return
}
isSyncingScroll.value = true
container.scrollTop = container.scrollHeight
requestAnimationFrame(() => {
const latestContainer = getScrollContainer()
if (!latestContainer) {
isSyncingScroll.value = false
return
}
latestContainer.scrollTop = latestContainer.scrollHeight
shouldAutoScroll.value = true
if (scrollReleaseTimer) {
window.clearTimeout(scrollReleaseTimer)
}
scrollReleaseTimer = window.setTimeout(() => {
isSyncingScroll.value = false
updateAutoScrollState()
}, 80)
})
}
function requestScrollToEnd(force = false) {
if (!force && !shouldAutoScroll.value) {
return
}
if (scrollTimer) {
window.clearTimeout(scrollTimer)
}
scrollTimer = window.setTimeout(() => {
nextTick(() => {
requestAnimationFrame(() => {
scrollContainerToEnd()
})
})
}, force ? 0 : 80)
}
function forceScrollToEnd() {
requestScrollToEnd(true)
}
// 合并消息到当前列表
function mergeMessages(items: Message[]) {
let hasNewMessage = false
@@ -95,9 +196,7 @@ function handleSSEMessage(event: MessageEvent) {
if (message) {
const object = JSON.parse(message)
if (mergeMessages([object])) {
nextTick(() => {
emit('scroll') // 新消息到达时触发智能滚动
})
requestScrollToEnd() // 新消息到达时触发智能滚动
}
}
}
@@ -137,9 +236,7 @@ async function loadMessages({ done }: { done: any }) {
// 首次加载时滚动到底部
if (page.value === 1 && hasNewMessage) {
nextTick(() => {
emit('scroll')
})
requestScrollToEnd(true)
}
// 页码+1
page.value++
@@ -168,9 +265,7 @@ async function refreshLatestMessages() {
})) as Message[]
if (mergeMessages(latestMessages)) {
nextTick(() => {
emit('scroll')
})
requestScrollToEnd()
}
} catch (error) {
console.error('刷新最新消息失败:', error)
@@ -206,7 +301,7 @@ function compareTime(time1: string, time2: string) {
// 图片加载完成时触发智能滚动
function handleImageLoad() {
emit('scroll')
requestScrollToEnd()
}
// 暂停SSE连接
@@ -232,18 +327,32 @@ defineExpose({
pauseSSE,
resumeSSE,
refreshLatestMessages,
forceScrollToEnd,
})
onMounted(() => {
// 组件挂载后触发一次滚动事件
nextTick(() => {
emit('scroll')
bindScrollListener()
requestScrollToEnd(true)
})
})
onBeforeUnmount(() => {
if (scrollTimer) {
window.clearTimeout(scrollTimer)
}
if (scrollReleaseTimer) {
window.clearTimeout(scrollReleaseTimer)
}
unbindScrollListener()
})
</script>
<template>
<VInfiniteScroll
ref="messageListRef"
:mode="!isLoaded ? 'intersect' : 'manual'"
side="start"
:items="messages"

View File

@@ -110,6 +110,7 @@ async function fetchData({ done }: { done: any }) {
page.value++
// 返回加载成功
done('ok')
await nextTick()
}
} else {
// 设置加载中