Add nested navigation links (#112)

Co-authored-by: Eduard Gert <eduard@netbird.io>
Co-authored-by: braginini <bangvalo@gmail.com>
This commit is contained in:
Eduard Gert
2023-12-12 17:35:51 +01:00
committed by GitHub
parent 464530a4d8
commit ddc65c7ae0
5 changed files with 280 additions and 94 deletions

View File

@@ -0,0 +1,53 @@
import {createContext, useContext, useEffect, useState} from "react";
import {useRouter} from "next/router";
const NavigationStateContext = createContext([]);
const timeout = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export function NavigationStateProvider({ children,index }) {
const [activeIndex, setActiveIndex] = useState(0);
const router = useRouter();
const setActiveHighlight = async (groupTitle = undefined) => {
await timeout(250);
const links = [];
document.querySelectorAll(`.outer-wrapper-${index} [data-nb-link]`).forEach((link) => {
links.push(link.getAttribute('data-nb-link'));
});
links.shift();
const activeIndex = links.findIndex((link) => link === "1");
const activeGroupIndex = links.findIndex((link) => link === groupTitle);
if(activeGroupIndex !== -1 && activeIndex === -1){
setActiveIndex(activeGroupIndex);
}else if(activeIndex !== -1){
setActiveIndex(activeIndex);
}
return Promise.resolve();
}
useEffect(() => {
setActiveHighlight();
}, [router.pathname]);
return (
<NavigationStateContext.Provider value={[activeIndex, setActiveHighlight]}>
<div className={`outer-wrapper-${index}`}>
{children}
</div>
</NavigationStateContext.Provider>
);
}
export function useNavigationState() {
const context = useContext(NavigationStateContext);
if (context === undefined) {
throw new Error(
'useNavigationState must be used within a NavigationStateProvider'
);
}
return context;
}