Skip to content

Commit 62bba0a

Browse files
committed
feat: only load visible elements on gallery
1 parent 5a36c89 commit 62bba0a

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

packages/core/src/utils/rxjs.ts

+17
Original file line numberDiff line numberDiff line change
@@ -114,3 +114,20 @@ export const observeMutation = (
114114
return () => observer.disconnect()
115115
})
116116
}
117+
118+
export function observeIntersection(
119+
element: HTMLElement,
120+
options?: IntersectionObserverInit,
121+
): Observable<IntersectionObserverEntry[]> {
122+
return new Observable<IntersectionObserverEntry[]>((observer) => {
123+
const intersectionObserver = new IntersectionObserver((entries) => {
124+
observer.next(entries)
125+
}, options)
126+
127+
intersectionObserver.observe(element)
128+
129+
return () => {
130+
intersectionObserver.disconnect()
131+
}
132+
})
133+
}

packages/react-reader/src/gallery/GalleryDialog.tsx

+15-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { Box, Button } from "@chakra-ui/react"
2-
import type { SpineItem } from "@prose-reader/core"
2+
import { type SpineItem, observeIntersection } from "@prose-reader/core"
33
import { memo } from "react"
44
import { useObserve, useSubscribe } from "reactjrx"
5+
import { NEVER, finalize, switchMap } from "rxjs"
56
import { useMeasure } from "../common/useMeasure"
67
import {
78
DialogActionTrigger,
@@ -23,8 +24,19 @@ const GalleryItem = memo(({ item }: { item: SpineItem }) => {
2324
useAttachSnapshot(element, item, measures)
2425

2526
useSubscribe(
26-
() => reader?.spine.spineItemsLoader.forceOpen([item]),
27-
[item, reader],
27+
() =>
28+
(!element ? NEVER : observeIntersection(element as HTMLElement, {})).pipe(
29+
switchMap((entries) => {
30+
if (entries.some((e) => e.isIntersecting)) {
31+
const unlock = reader?.spine.spineItemsLoader.forceOpen([item])
32+
33+
return NEVER.pipe(finalize(() => unlock?.()))
34+
}
35+
36+
return NEVER
37+
}),
38+
),
39+
[item, reader, element],
2840
)
2941

3042
return (

0 commit comments

Comments
 (0)