// Copyright 2026 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.
import { forwardRef, memo, useRef, useState } from '@lynx-js/react'
import type { ForwardedRef, ReactNode } from '@lynx-js/react'
import { useGlobalEventListener } from '@lynx-js/lynx-ui-common'
import './styles.css'
import type { LayoutChangeEvent } from '@lynx-js/types'
import type { LazyComponentProps, LazyComponentRef } from './types'
export type { LazyComponentRef, LazyComponentProps }
type LazyComponentType = (props: LazyComponentProps) => ReactNode
export const LazyComponent = memo(
forwardRef(LazyComponentImpl),
) as LazyComponentType
/**
* @example
* ```javascript
Hello, ReactLynx 3!
* ```
*/
function LazyComponentImpl(
props: LazyComponentProps,
_ref: ForwardedRef,
) {
const {
pid,
scene,
estimatedStyle,
top = '10px',
bottom = '10px',
left = '10px',
right = '10px',
unmountOnExit,
unloadable = false,
children,
} = props
const shouldUnmountOnExit = unmountOnExit ?? unloadable
const [show, setShow] = useState(false)
const cacheSizeRef = useRef<{ width: string, height: string }>(undefined)
useGlobalEventListener(
'exposure',
(events: unknown[]) => {
'background-only'
events.forEach(event => {
if (
!show
// @ts-expect-error exposure-scene and exposure-id is currently not declared in eventProps
&& event['exposure-scene'] === scene
// @ts-expect-error exposure-scene and exposure-id is currently not declared in eventProps
&& event['exposure-id'] === pid
) {
setShow(true)
}
})
},
[show],
)
const onLayoutChange = ({ detail }: LayoutChangeEvent) => {
if (show) {
cacheSizeRef.current = {
width: `${detail.width}px`,
height: `${detail.height}px`,
}
}
}
useGlobalEventListener(
'disexposure',
(events: unknown[]) => {
'background-only'
if (shouldUnmountOnExit) {
events.forEach(event => {
if (
// @ts-expect-error exposure-scene and exposure-id is currently not declared in eventProps
event['exposure-scene'] === scene
// @ts-expect-error exposure-scene and exposure-id is currently not declared in eventProps
&& event['exposure-id'] === pid
) {
setShow(false)
}
})
}
},
[shouldUnmountOnExit],
)
if (shouldUnmountOnExit) {
const { width, height, ...restsStyles } = estimatedStyle
return (
{show && children}
)
} else {
return show ? children : (
)
}
}