-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuseCheckAndOpenAccordionPanel.ts
40 lines (34 loc) · 1.15 KB
/
useCheckAndOpenAccordionPanel.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
import { useEffect } from 'react';
import { smoothScrollToTarget } from 'utils/scroll-to';
export const useCheckAndOpenAccordionPanel = (
openPanels: number[],
setOpenPanels: (indexes: number[]) => void,
refs: React.RefObject<HTMLDivElement>[],
expandAll: () => void
) => {
const checkAndOpenPanels = () => {
const targetId = window.location.hash.replace('#', '');
const elementWithId = document.getElementById(targetId);
if (window.location.toString().includes('expandall=true')) {
expandAll();
return;
}
if (!targetId) return;
for (let i = 0; i < refs.length; i++) {
if (refs[i].current?.contains(elementWithId)) {
setOpenPanels([...openPanels, i]);
setTimeout(() => smoothScrollToTarget(targetId), 500);
return;
}
}
};
useEffect(() => {
window.addEventListener('hashchange', checkAndOpenPanels);
return () => {
window.removeEventListener('hashchange', checkAndOpenPanels);
};
}, []);
useEffect(() => {
checkAndOpenPanels();
}, []);
};