Browse Source

Restore scroll after 'show less' (#4056)

* Restore scroll after 'show less'

* Get the whole sandbox into view
main
Dan Abramov 3 years ago
committed by GitHub
parent
commit
075b786344
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 22
      beta/src/components/MDX/Sandpack/CustomPreset.tsx

22
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<HTMLDivElement>(null);
const {sandpack} = useSandpack();
const {code} = useActiveCode();
const [isExpanded, setIsExpanded] = React.useState(false);
@ -43,7 +47,9 @@ export function CustomPreset({
return (
<>
<div className="shadow-lg dark:shadow-lg-dark rounded-lg">
<div
className="shadow-lg dark:shadow-lg-dark rounded-lg"
ref={containerRef}>
<NavigationBar showDownload={isSingleFile} onReset={onReset} />
<SandpackThemeProvider theme={CustomTheme}>
<div
@ -75,7 +81,19 @@ export function CustomPreset({
<button
translate="yes"
className="flex text-base justify-between dark:border-card-dark bg-wash dark:bg-card-dark items-center z-10 rounded-t-none p-1 w-full order-2 xl:order-last border-b-1 relative top-0"
onClick={() => 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',
});
}
}}>
<span className="flex p-2 focus:outline-none text-primary dark:text-primary-dark">
<IconChevron
className="inline mr-1.5 text-xl"

Loading…
Cancel
Save