Skip to content

Commit

Permalink
fix: make sure to unregister all clients when "user-visible" option i…
Browse files Browse the repository at this point in the history
…s out of viewport (#1098)
  • Loading branch information
danilowoz committed Feb 28, 2024
1 parent 060ee9c commit 230960c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
19 changes: 19 additions & 0 deletions sandpack-react/src/Playground.stories.tsx
Expand Up @@ -11,6 +11,25 @@ export const Basic: React.FC = () => {
return (
<div style={{ height: "400vh" }}>
<Sandpack
files={{
"/App.js": `export default function TodoList() {
return (
// This doesn't quite work!
<h1>Hedy Lamarr's Todos</h1>
<img
src="https://i.imgur.com/yXOvdOSs.jpg"
alt="Hedy Lamarr"
class="photo"
>
<ul>
<li>Invent new traffic lights
<li>Rehearse a movie scene
<li>Improve spectrum technology
</ul>
);
}
`,
}}
options={{
initMode: "user-visible",
bundlerURL: "https://786946de.sandpack-bundler-4bw.pages.dev",
Expand Down
12 changes: 11 additions & 1 deletion sandpack-react/src/contexts/utils/useClient.ts
Expand Up @@ -244,6 +244,8 @@ export const useClient: UseClient = (
): void => {
if (entries.some((entry) => entry.isIntersecting)) {
runSandpack();
} else {
unregisterAllClients();
}
};

Expand All @@ -266,7 +268,15 @@ export const useClient: UseClient = (
// If any component registered a lazy anchor ref component, use that for the intersection observer
intersectionObserver.current = new IntersectionObserver((entries) => {
if (entries.some((entry) => entry.isIntersecting)) {
intersectionObserverCallback.current?.(entries);
// Trigger it once
if (
entries.some((entry) => entry.isIntersecting) &&
lazyAnchorRef.current
) {
intersectionObserverCallback.current?.(entries);

intersectionObserver.current?.unobserve(lazyAnchorRef.current);
}
}
}, observerOptions);

Expand Down

0 comments on commit 230960c

Please sign in to comment.