import { useParams } from "next/navigation"; const TEMPLATE_PATTERNS: { key: string; prefix: string; param: string }[] = [ { key: "/products/:handle", prefix: "/products/", param: "handle" }, { key: "/collections/:handle", prefix: "/collections/", param: "handle" }, ]; export type ResolvedRoute = { key: string; path: string; params: Record; }; const resolveRoute = (segments: string[] = []): ResolvedRoute => { const path = segments.length === 0 ? "/" : `/${segments.join("/")}`; for (const { key, prefix, param } of TEMPLATE_PATTERNS) { if (path.startsWith(prefix) && path.length > prefix.length) { return { key, path, params: { [param]: path.slice(prefix.length) } }; } } return { key: path, path, params: {} }; }; /** * Reads the current route's `handle` param from the catch-all slug segments. * Use in client components rendered under `app/[[...slug]]` (and its editor * counterpart) where the handle is no longer exposed as a direct route param. */ export const useRouteHandle = (): string | undefined => { const params = useParams(); const segments = Array.isArray(params?.slug) ? (params.slug as string[]) : []; return resolveRoute(segments).params.handle; }; export default resolveRoute;