Skip to content

Commit

Permalink
feat: create useElementIsVisible (#1152)
Browse files Browse the repository at this point in the history
  • Loading branch information
ggazzo authored Sep 1, 2023
1 parent 51d5bde commit 344deea
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/fuselage-hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ export * from './useStorage';
export * from './useToggle';
export * from './useUniqueId';
export * from './useOutsideClick';
export * from './useElementIsVisible';
51 changes: 51 additions & 0 deletions packages/fuselage-hooks/src/useElementIsVisible.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { useDebouncedState, useSafely } from '@rocket.chat/fuselage-hooks';
import type { RefObject } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';

declare global {
interface Window {
DISABLE_ANIMATION: boolean;
}
}

export const useElementIsVisible = <T extends Element>(): [
ref: RefObject<T>,
isVisible: boolean
] => {
const innerRef = useRef<T>();

const [menuVisibility, setMenuVisibility] = useSafely(
useDebouncedState(false, 100)
);

const [observer] = useState(
() =>
new IntersectionObserver((entries) => {
entries.forEach((entry) => {
setMenuVisibility(entry.isIntersecting);
});
})
);

useEffect(
() => () => {
observer.disconnect();
},
[observer]
);

const ref = useCallback(
(node: T | null) => {
if (node === null) {
setMenuVisibility(false);
return;
}
innerRef.current = node;

observer.observe(innerRef.current);
},
[observer, setMenuVisibility]
) as unknown as RefObject<T>;

return [ref, menuVisibility];
};

0 comments on commit 344deea

Please sign in to comment.