Skip to content

Commit

Permalink
fix(scroll): reactjs#5995 keep computed height to avoid page jump
Browse files Browse the repository at this point in the history
  • Loading branch information
san.s committed Sep 6, 2024
1 parent 391dadb commit 172e900
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/components/MDX/Sandpack/Preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export function Preview({
const {sandpack, listen} = useSandpack();
const [bundlerIsReady, setBundlerIsReady] = useState(false);
const [showLoading, setShowLoading] = useState(false);
const [iframeHeightIsReady, setIframeHeightIsReady] = useState(false);
const [iframeComputedHeight, setComputedAutoHeight] = useState<number | null>(
null
);
Expand Down Expand Up @@ -105,6 +106,7 @@ export function Preview({
const unsubscribe = listen((message) => {
if (message.type === 'resize') {
setComputedAutoHeight(message.height);
setIframeHeightIsReady(true);
} else if (message.type === 'start') {
if (message.firstLoad) {
setBundlerIsReady(false);
Expand All @@ -128,7 +130,6 @@ export function Preview({
return () => {
clearTimeout(timeout);
setBundlerIsReady(false);
setComputedAutoHeight(null);
unsubscribe();
};
},
Expand All @@ -150,7 +151,7 @@ export function Preview({
// - It should work on mobile.
// The best way to test it is to actually go through some challenges.

const hideContent = error || !iframeComputedHeight || !bundlerIsReady;
const hideContent = error || !iframeHeightIsReady || !bundlerIsReady;

const iframeWrapperPosition = (): CSSProperties => {
if (hideContent) {
Expand All @@ -173,7 +174,10 @@ export function Preview({
// Note we don't want this in the expanded state
// because it breaks position: sticky (and isn't needed anyway).
!isExpanded && (error || bundlerIsReady) ? 'overflow-auto' : null
)}>
)}
style={{
minHeight: iframeComputedHeight || '15px',
}}>
<div style={iframeWrapperPosition()}>
<iframe
ref={iframeRef}
Expand All @@ -185,7 +189,7 @@ export function Preview({
// if you make a compiler error and then fix it with code
// that expands the content. You want to measure that.
hideContent
? 'absolute opacity-0 pointer-events-none duration-75'
? 'opacity-0 pointer-events-none duration-75'
: 'opacity-100 duration-150'
)}
title="Sandbox Preview"
Expand All @@ -210,7 +214,7 @@ export function Preview({

<LoadingOverlay
clientId={clientId}
dependenciesLoading={!bundlerIsReady && iframeComputedHeight === null}
dependenciesLoading={!bundlerIsReady && !iframeHeightIsReady}
forceLoading={showLoading}
/>
</div>
Expand Down

0 comments on commit 172e900

Please sign in to comment.