From 075b786344223baef9eab20caad42711aed4a138 Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Sat, 6 Nov 2021 14:44:15 +0000 Subject: [PATCH] Restore scroll after 'show less' (#4056) * Restore scroll after 'show less' * Get the whole sandbox into view --- .../components/MDX/Sandpack/CustomPreset.tsx | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/beta/src/components/MDX/Sandpack/CustomPreset.tsx b/beta/src/components/MDX/Sandpack/CustomPreset.tsx index d60e583db..c4b72601f 100644 --- a/beta/src/components/MDX/Sandpack/CustomPreset.tsx +++ b/beta/src/components/MDX/Sandpack/CustomPreset.tsx @@ -3,12 +3,15 @@ */ import React from 'react'; +// @ts-ignore +import {flushSync} from 'react-dom'; import { useSandpack, useActiveCode, SandpackCodeEditor, SandpackThemeProvider, } from '@codesandbox/sandpack-react'; +import scrollIntoView from 'scroll-into-view-if-needed'; import {IconChevron} from 'components/Icon/IconChevron'; import {NavigationBar} from './NavigationBar'; @@ -23,6 +26,7 @@ export function CustomPreset({ onReset: () => void; }) { const lineCountRef = React.useRef<{[key: string]: number}>({}); + const containerRef = React.useRef(null); const {sandpack} = useSandpack(); const {code} = useActiveCode(); const [isExpanded, setIsExpanded] = React.useState(false); @@ -43,7 +47,9 @@ export function CustomPreset({ return ( <> -
+
setIsExpanded((prevExpanded) => !prevExpanded)}> + onClick={() => { + const nextIsExpanded = !isExpanded; + flushSync(() => { + setIsExpanded(nextIsExpanded); + }); + if (!nextIsExpanded && containerRef.current !== null) { + scrollIntoView(containerRef.current, { + scrollMode: 'if-needed', + block: 'nearest', + inline: 'nearest', + }); + } + }}>