import * as React from "react"; import * as RouterDom from "react-router-dom"; import type { NavigateOptions, To } from "react-router-dom"; import { useCompany } from "@/context/CompanyContext"; import { applyCompanyPrefix, extractCompanyPrefixFromPath, normalizeCompanyPrefix, } from "@/lib/company-routes"; function resolveTo(to: To, companyPrefix: string | null): To { if (typeof to === "string") { return applyCompanyPrefix(to, companyPrefix); } if (to.pathname && to.pathname.startsWith("/")) { const pathname = applyCompanyPrefix(to.pathname, companyPrefix); if (pathname !== to.pathname) { return { ...to, pathname }; } } return to; } function useActiveCompanyPrefix(): string | null { const { selectedCompany } = useCompany(); const params = RouterDom.useParams<{ companyPrefix?: string }>(); const location = RouterDom.useLocation(); if (params.companyPrefix) { return normalizeCompanyPrefix(params.companyPrefix); } const pathPrefix = extractCompanyPrefixFromPath(location.pathname); if (pathPrefix) return pathPrefix; return selectedCompany ? normalizeCompanyPrefix(selectedCompany.issuePrefix) : null; } export * from "react-router-dom"; export const Link = React.forwardRef>( function CompanyLink({ to, ...props }, ref) { const companyPrefix = useActiveCompanyPrefix(); return ; }, ); export const NavLink = React.forwardRef>( function CompanyNavLink({ to, ...props }, ref) { const companyPrefix = useActiveCompanyPrefix(); return ; }, ); export function Navigate({ to, ...props }: React.ComponentProps) { const companyPrefix = useActiveCompanyPrefix(); return ; } export function useNavigate(): ReturnType { const navigate = RouterDom.useNavigate(); const companyPrefix = useActiveCompanyPrefix(); return React.useCallback( ((to: To | number, options?: NavigateOptions) => { if (typeof to === "number") { navigate(to); return; } navigate(resolveTo(to, companyPrefix), options); }) as ReturnType, [navigate, companyPrefix], ); }