]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
feat(hydration): allow fine tuning of lazy hydration strategy triggers (#11530)
authorMichael Brevard <yonshi29@gmail.com>
Wed, 7 Aug 2024 04:06:15 +0000 (07:06 +0300)
committerGitHub <noreply@github.com>
Wed, 7 Aug 2024 04:06:15 +0000 (12:06 +0800)
packages/runtime-core/src/hydrationStrategies.ts
packages/vue/__tests__/e2e/hydration-strat-visible.html

index 4f0a2d23e1aca8b343eae3d21cd81b74ef52079b..57b543b46403c7c14c0be9b1c84c331a41e2830f 100644 (file)
@@ -15,35 +15,32 @@ export type HydrationStrategy = (
   forEachElement: (cb: (el: Element) => any) => void,
 ) => (() => void) | void
 
-export type HydrationStrategyFactory<Options = any> = (
+export type HydrationStrategyFactory<Options> = (
   options?: Options,
 ) => HydrationStrategy
 
-export const hydrateOnIdle: HydrationStrategyFactory = () => hydrate => {
-  const id = requestIdleCallback(hydrate)
-  return () => cancelIdleCallback(id)
-}
-
-export const hydrateOnVisible: HydrationStrategyFactory<string | number> =
-  (margin = 0) =>
-  (hydrate, forEach) => {
-    const ob = new IntersectionObserver(
-      entries => {
-        for (const e of entries) {
-          if (!e.isIntersecting) continue
-          ob.disconnect()
-          hydrate()
-          break
-        }
-      },
-      {
-        rootMargin: isString(margin) ? margin : margin + 'px',
-      },
-    )
-    forEach(el => ob.observe(el))
-    return () => ob.disconnect()
+export const hydrateOnIdle: HydrationStrategyFactory<number> =
+  (timeout = 10000) =>
+  hydrate => {
+    const id = requestIdleCallback(hydrate, { timeout })
+    return () => cancelIdleCallback(id)
   }
 
+export const hydrateOnVisible: HydrationStrategyFactory<
+  IntersectionObserverInit
+> = opts => (hydrate, forEach) => {
+  const ob = new IntersectionObserver(entries => {
+    for (const e of entries) {
+      if (!e.isIntersecting) continue
+      ob.disconnect()
+      hydrate()
+      break
+    }
+  }, opts)
+  forEach(el => ob.observe(el))
+  return () => ob.disconnect()
+}
+
 export const hydrateOnMediaQuery: HydrationStrategyFactory<string> =
   query => hydrate => {
     if (query) {
@@ -58,7 +55,7 @@ export const hydrateOnMediaQuery: HydrationStrategyFactory<string> =
   }
 
 export const hydrateOnInteraction: HydrationStrategyFactory<
-  string | string[]
+  keyof HTMLElementEventMap | Array<keyof HTMLElementEventMap>
 > =
   (interactions = []) =>
   (hydrate, forEach) => {
index 863455c845089f445344dca7a7641f1e685af055..6420ca9fe4fff4c49eb9c8ac9fbf4acbcafa324a 100644 (file)
@@ -35,7 +35,7 @@
 
   const AsyncComp = defineAsyncComponent({
     loader: () => Promise.resolve(Comp),
-    hydrate: hydrateOnVisible(rootMargin + 'px')
+    hydrate: hydrateOnVisible({rootMargin: rootMargin + 'px'})
   })
 
   createSSRApp({