63 lines
1.4 KiB
TypeScript
63 lines
1.4 KiB
TypeScript
import { useParams } from "@tanstack/react-router";
|
|
import * as z from "zod";
|
|
import type { RelationshipType, DocumentId } from "./types";
|
|
|
|
const documentParams = z
|
|
.templateLiteral([
|
|
z.string(),
|
|
z.optional(z.literal("/")),
|
|
z.optional(z.string()),
|
|
])
|
|
.pipe(
|
|
z.transform((path: string) => {
|
|
if (path === "") {
|
|
return {
|
|
relationshipType: null,
|
|
childDocId: null,
|
|
};
|
|
}
|
|
const [relationshipType, childDocId] = path.split("/");
|
|
return {
|
|
relationshipType: (relationshipType ?? null) as RelationshipType | null,
|
|
childDocId: (childDocId ?? null) as DocumentId | null,
|
|
};
|
|
}),
|
|
);
|
|
|
|
export function useDocumentPath():
|
|
| {
|
|
documentId: DocumentId;
|
|
relationshipType: RelationshipType | null;
|
|
childDocId: DocumentId | null;
|
|
}
|
|
| undefined {
|
|
const params = useParams({
|
|
from: "/_app/_authenticated/document/$documentId/$",
|
|
shouldThrow: false,
|
|
});
|
|
|
|
if (params) {
|
|
const { relationshipType, childDocId } = documentParams.parse(
|
|
params._splat,
|
|
);
|
|
return {
|
|
documentId: params.documentId as DocumentId,
|
|
relationshipType,
|
|
childDocId,
|
|
};
|
|
}
|
|
|
|
return undefined;
|
|
}
|
|
|
|
export function makeDocumentPath(
|
|
documentId: DocumentId,
|
|
relationshipType?: RelationshipType | null,
|
|
childDocId?: DocumentId | null,
|
|
) {
|
|
return (
|
|
"/document/" +
|
|
[documentId, relationshipType, childDocId].filter((x) => x).join("/")
|
|
);
|
|
}
|