Update react editor
This commit is contained in:
@@ -1,34 +0,0 @@
|
||||
const TEMPLATE_PATTERNS: { key: string; prefix: string; param: string }[] = [
|
||||
{ key: "/products/*", prefix: "/products/", param: "handle" },
|
||||
{ key: "/collections/*", prefix: "/collections/", param: "handle" },
|
||||
];
|
||||
|
||||
export type ResolvedEditorPath = {
|
||||
isEdit: boolean;
|
||||
path: string;
|
||||
templateKey: string | null;
|
||||
params: Record<string, string>;
|
||||
};
|
||||
|
||||
const resolveEditorPath = (editorPath: string[] = []): ResolvedEditorPath => {
|
||||
const isEdit =
|
||||
editorPath.length > 0 && editorPath[editorPath.length - 1] === "edit";
|
||||
|
||||
const segments = isEdit ? editorPath.slice(0, -1) : editorPath;
|
||||
const path = segments.length === 0 ? "/" : `/${segments.join("/")}`;
|
||||
|
||||
for (const { key, prefix, param } of TEMPLATE_PATTERNS) {
|
||||
if (path.startsWith(prefix) && path.length > prefix.length) {
|
||||
return {
|
||||
isEdit,
|
||||
path,
|
||||
templateKey: key,
|
||||
params: { [param]: path.slice(prefix.length) },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { isEdit, path, templateKey: null, params: {} };
|
||||
};
|
||||
|
||||
export default resolveEditorPath;
|
||||
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