-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuseCheckAndOpenPanel.ts
49 lines (40 loc) · 1.19 KB
/
useCheckAndOpenPanel.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { useEffect } from 'react';
import { smoothScrollToTarget } from 'utils/scroll-to';
export const useCheckAndOpenPanel = (
isOpen: boolean,
setIsOpen: (isOpen: boolean) => void,
ref: React.RefObject<HTMLDivElement>,
anchorId?: string
) => {
const checkAndOpenPanel = () => {
const targetId = window.location.hash.replace('#', '');
const elementWithId = document.getElementById(targetId);
if (isOpen) {
return;
}
if (window.location.toString().includes('expandall=true')) {
setIsOpen(true);
return;
}
if (!targetId) {
return;
}
if (targetId === anchorId) {
setIsOpen(true);
return;
}
if (ref.current?.contains(elementWithId)) {
setIsOpen(true);
setTimeout(() => smoothScrollToTarget(targetId), 500);
}
};
useEffect(() => {
window.addEventListener('hashchange', checkAndOpenPanel);
return () => {
window.removeEventListener('hashchange', checkAndOpenPanel);
};
}, []);
useEffect(() => {
checkAndOpenPanel();
}, [anchorId]);
};