Skip to content

Commit

Permalink
feat(hydration): allow fine tuning of lazy hydration strategy triggers (
Browse files Browse the repository at this point in the history
  • Loading branch information
GalacticHypernova authored Aug 7, 2024
1 parent 63689ed commit 261c8b1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 26 deletions.
47 changes: 22 additions & 25 deletions packages/runtime-core/src/hydrationStrategies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -58,7 +55,7 @@ export const hydrateOnMediaQuery: HydrationStrategyFactory<string> =
}

export const hydrateOnInteraction: HydrationStrategyFactory<
string | string[]
keyof HTMLElementEventMap | Array<keyof HTMLElementEventMap>
> =
(interactions = []) =>
(hydrate, forEach) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/vue/__tests__/e2e/hydration-strat-visible.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@

const AsyncComp = defineAsyncComponent({
loader: () => Promise.resolve(Comp),
hydrate: hydrateOnVisible(rootMargin + 'px')
hydrate: hydrateOnVisible({rootMargin: rootMargin + 'px'})
})

createSSRApp({
Expand Down

0 comments on commit 261c8b1

Please sign in to comment.