Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: load out of viewport sections after TTI #2604

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 50 additions & 10 deletions packages/core/src/components/cms/RenderSections.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,19 @@ import {
useMemo,
} from 'react'

import { useUI } from '@faststore/ui'
import { Section } from '@vtex/client-cms'
import dynamic from 'next/dynamic'
import useTTI from 'src/sdk/performance/useTTI'
import SectionBoundary from './SectionBoundary'
import ViewportObserver from './ViewportObserver'
import COMPONENTS from './global/Components'

import { useUI } from '@faststore/ui'

interface Props {
components?: Record<string, ComponentType<any>>
globalSections?: Array<{ name: string; data: any }>
sections?: Array<{ name: string; data: any }>
isInteractive?: boolean
}

const SECTIONS_OUT_OF_VIEWPORT = ['CartSidebar', 'RegionModal']
Expand Down Expand Up @@ -51,25 +52,47 @@ const useDividedSections = (sections: Section[]) => {
export const LazyLoadingSection = ({
sectionName,
children,
debug = false,
isInteractive = false,
}: {
sectionName: string
children: ReactNode
debug?: boolean
isInteractive?: boolean
}) => {
const { cart: displayCart, modal: displayModal } = useUI()

if (SECTIONS_OUT_OF_VIEWPORT.includes(sectionName)) {
const shouldLoad =
isInteractive ||
(sectionName === 'CartSidebar' && displayCart) ||
(sectionName === 'RegionModal' && displayModal)

if (debug) {
console.log(
`section SECTIONS_OUT_OF_VIEWPORT '${sectionName}' shouldLoad:`,
shouldLoad
)
}

return shouldLoad ? <>{children}</> : null
}

return (
<ViewportObserver sectionName={sectionName}>{children}</ViewportObserver>
<ViewportObserver
sectionName={sectionName}
debug={debug}
isInteractive={isInteractive}
>
{children}
</ViewportObserver>
)
}

const RenderSectionsBase = ({ sections = [], components }: Props) => {
const RenderSectionsBase = ({
sections = [],
components,
isInteractive,
}: Props) => {
return (
<>
{sections.map(({ name, data = {} }, index) => {
Expand All @@ -86,7 +109,10 @@ const RenderSectionsBase = ({ sections = [], components }: Props) => {

return (
<SectionBoundary key={`cms-section-${name}-${index}`} name={name}>
<LazyLoadingSection sectionName={name}>
<LazyLoadingSection
sectionName={name}
isInteractive={isInteractive}
>
<Component {...data} />
</LazyLoadingSection>
</SectionBoundary>
Expand All @@ -106,21 +132,35 @@ function RenderSections({
globalSections ?? sections
)

const { isInteractive } = useTTI()

return (
<>
{firstSections && (
<RenderSectionsBase sections={firstSections} components={components} />
<RenderSectionsBase
sections={firstSections}
components={components}
isInteractive={isInteractive}
/>
)}
{sections && sections.length > 0 && (
<RenderSectionsBase sections={sections} components={components} />
<RenderSectionsBase
sections={sections}
components={components}
isInteractive={isInteractive}
/>
)}
{children}
<LazyLoadingSection sectionName="Toast">
<LazyLoadingSection sectionName="Toast" isInteractive={isInteractive}>
<Toast />
</LazyLoadingSection>

{lastSections && (
<RenderSectionsBase sections={lastSections} components={components} />
<RenderSectionsBase
sections={lastSections}
components={components}
isInteractive={isInteractive}
/>
)}
</>
)
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/components/cms/ViewportObserver.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type ViewportObserverProps = {
* Debug/test purposes: enables visual debugging to identify the visibility of the section.
*/
debug?: boolean
isInteractive?: boolean
} & IntersectionObserverInit

function ViewportObserver({
Expand All @@ -23,6 +24,7 @@ function ViewportObserver({
rootMargin,
children,
debug = false,
isInteractive = false,
}: PropsWithChildren<ViewportObserverProps>) {
const [isVisible, setVisible] = useState(false)
const ref = useRef<HTMLDivElement | null>(null)
Expand Down Expand Up @@ -80,7 +82,7 @@ function ViewportObserver({
></div>
)}

{isVisible && children}
{(isVisible || isInteractive) && children}
</>
)
}
Expand Down
37 changes: 37 additions & 0 deletions packages/core/src/sdk/performance/useTTI.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useEffect, useState } from 'react'

// Time To Interactive - https://web.dev/articles/tti
export default function useTTI() {
const [isInteractive, setIsInteractive] = useState(false)

useEffect(() => {
if ('PerformanceObserver' in window) {
let lastTaskEnd = 0
const TTI_TIMEOUT = 5000 // 5 seconds without long tasks as a criterion for TTI

const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
// console.log('Long task detected:', entry);
lastTaskEnd = entry.startTime + entry.duration
}
})

observer.observe({ type: 'longtask', buffered: true })

// Monitoring when TTI might have been reached
const checkTTI = () => {
const now = performance.now()
if (now - lastTaskEnd >= TTI_TIMEOUT) {
observer.disconnect()
setIsInteractive(true) // Sets the state to true when TTI is estimated
} else {
requestIdleCallback(checkTTI) // Keeps checking while the browser is idle
}
}

requestIdleCallback(checkTTI)
}
}, [])

return { isInteractive }
}
Loading