Update react editor
This commit is contained in:
37
lib/resolve-route.ts
Normal file
37
lib/resolve-route.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
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<string, string>;
|
||||
};
|
||||
|
||||
const resolveRoute = (slug: string[] = []): ResolvedRoute => {
|
||||
const path = slug.length === 0 ? "/" : `/${slug.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 slug = Array.isArray(params?.slug) ? (params.slug as string[]) : [];
|
||||
return resolveRoute(slug).params.handle;
|
||||
};
|
||||
|
||||
export default resolveRoute;
|
||||
Reference in New Issue
Block a user