Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perserve Scroll Position in Search Tab #999

Closed
wants to merge 9 commits into from
41 changes: 37 additions & 4 deletions apps/antalmanac/src/components/SharedRoot.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Box, Paper, Tab, Tabs, Typography } from '@material-ui/core';
import { Box, BoxProps, Paper, Tab, Tabs, Typography } from '@material-ui/core';
import { Event, FormatListBulleted, MyLocation, Search } from '@material-ui/icons';
import { GlobalStyles } from '@mui/material';
import { Suspense, lazy, useEffect } from 'react';
import { Suspense, forwardRef, lazy, useEffect, useRef } from 'react';
import { Link, useParams } from 'react-router-dom';

import Calendar from './Calendar/CalendarRoot';
Expand All @@ -26,14 +26,47 @@ const styles = {
},
};

type BoxWithRefProps = BoxProps & {
ref?: React.Ref<HTMLDivElement>;
};

const BoxWithRef = forwardRef<HTMLDivElement, BoxWithRefProps>((props, ref) => {
return <Box ref={ref} {...props} />;
});

BoxWithRef.displayName = 'BoxWithRef';

const Views = ({ activeTab, mobile }: { activeTab: number; mobile: boolean }) => {
const isDark = useThemeStore((store) => store.isDark);
const paneBox = useRef<HTMLDivElement | null>(null);
const currentScrollPosition = useRef(0);
const lastActiveTab = useRef<number | null>(null);
const savedScrollPositions = useRef<Map<number, number>>(new Map());

if (lastActiveTab.current !== activeTab) {
const newScrollPosition = savedScrollPositions.current.get(activeTab) ?? 0;
if (lastActiveTab.current == 1) {
savedScrollPositions.current.set(lastActiveTab.current, currentScrollPosition.current);
}
lastActiveTab.current = activeTab;
currentScrollPosition.current = newScrollPosition;
requestAnimationFrame(() => {
if (paneBox.current) paneBox.current.scrollTop = newScrollPosition;
});
}

return activeTab === 0 ? (
<Calendar isMobile={mobile} />
) : (
<Box height="100%" style={{ margin: '0 4px' }}>
<Box height="calc(100% - 54px)" overflow="auto" style={{ margin: '8px 0px' }} id="course-pane-box">
<BoxWithRef
ref={paneBox}
height="calc(100% - 54px)"
overflow="auto"
style={{ margin: '8px 0px' }}
id="course-pane-box"
onScroll={() => (currentScrollPosition.current = paneBox.current?.scrollTop ?? 0)}
>
{activeTab === 1 && <CoursePane />}
{activeTab === 2 && <AddedCoursePane />}
{activeTab === 3 && (
Expand All @@ -47,7 +80,7 @@ const Views = ({ activeTab, mobile }: { activeTab: number; mobile: boolean }) =>
<UCIMap />
</Suspense>
)}
</Box>
</BoxWithRef>
</Box>
);
};
Expand Down
Loading