Files
twenty/packages/twenty-front/src/hooks/useScrollRestoration.ts
Paul Rastoin 7fd89678b7 [CHORE] Avoid isDefined duplicated reference, move it to twenty-shared (#9967)
# Introduction
Avoid having multiple `isDefined` definition across our pacakges
Also avoid importing `isDefined` from `twenty-ui` which exposes a huge
barrel for a such little util function

## In a nutshell
Removed own `isDefined.ts` definition from `twenty-ui` `twenty-front`
and `twenty-server` to move it to `twenty-shared`.
Updated imports for each packages, and added explicit dependencies to
`twenty-shared` if not already in place

Related PR https://github.com/twentyhq/twenty/pull/9941
2025-02-01 12:10:10 +01:00

38 lines
1.6 KiB
TypeScript

import { useEffect } from 'react';
import { useNavigation } from 'react-router-dom';
import { scrollWrapperInstanceComponentState } from '@/ui/utilities/scroll/states/scrollWrapperInstanceComponentState';
import { scrollWrapperScrollTopComponentState } from '@/ui/utilities/scroll/states/scrollWrapperScrollTopComponentState';
import { useRecoilComponentStateV2 } from '@/ui/utilities/state/component-state/hooks/useRecoilComponentStateV2';
import { useRecoilComponentValueV2 } from '@/ui/utilities/state/component-state/hooks/useRecoilComponentValueV2';
import { isDefined } from 'twenty-shared';
/**
* @deprecated We should now use useScrollToPosition instead
* Note that `location.key` is used in the cache key, not `location.pathname`,
* so the same path navigated to at different points in the history stack will
* not share the same scroll position.
*/
export const useScrollRestoration = (viewportHeight?: number) => {
const { state } = useNavigation();
const [scrollTop, setScrollTop] = useRecoilComponentStateV2(
scrollWrapperScrollTopComponentState,
);
const overlayScrollbars = useRecoilComponentValueV2(
scrollWrapperInstanceComponentState,
);
const scrollWrapper = overlayScrollbars?.elements().viewport;
const skip = isDefined(viewportHeight) && scrollTop > viewportHeight;
useEffect(() => {
if (state === 'loading') {
setScrollTop(scrollWrapper?.scrollTop ?? 0);
} else if (state === 'idle' && isDefined(scrollWrapper) && !skip) {
scrollWrapper.scrollTo({ top: scrollTop });
}
}, [state, scrollWrapper, skip, scrollTop, setScrollTop]);
};