feat: extract useObserver

This commit is contained in:
Michael Brevard 2024-03-25 15:06:53 +02:00 committed by GitHub
parent 85b4d6932b
commit 624188a7cf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -14,6 +14,7 @@ import { onNuxtReady } from '../composables/ready'
import { navigateTo, useRouter } from '../composables/router'
import { useNuxtApp, useRuntimeConfig } from '../nuxt'
import { cancelIdleCallback, requestIdleCallback } from '../compat/idle-callback'
import { useObserver } from "../utils"
// @ts-expect-error virtual file
import { nuxtLinkDefaults } from '#build/nuxt.config.mjs'
@ -403,49 +404,6 @@ function applyTrailingSlashBehavior (to: string, trailingSlash: NuxtLinkOptions[
}
// --- Prefetching utils ---
type CallbackFn = () => void
type ObserveFn = (element: Element, callback: CallbackFn) => () => void
function useObserver (): { observe: ObserveFn } | undefined {
if (import.meta.server) { return }
const nuxtApp = useNuxtApp()
if (nuxtApp._observer) {
return nuxtApp._observer
}
let observer: IntersectionObserver | null = null
const callbacks = new Map<Element, CallbackFn>()
const observe: ObserveFn = (element, callback) => {
if (!observer) {
observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
const callback = callbacks.get(entry.target)
const isVisible = entry.isIntersecting || entry.intersectionRatio > 0
if (isVisible && callback) { callback() }
}
})
}
callbacks.set(element, callback)
observer.observe(element)
return () => {
callbacks.delete(element)
observer!.unobserve(element)
if (callbacks.size === 0) {
observer!.disconnect()
observer = null
}
}
}
const _observer = nuxtApp._observer = {
observe
}
return _observer
}
function isSlowConnection () {
if (import.meta.server) { return }