Compare commits
2 Commits
f8130f0ba9
...
eeb2ef04fd
| Author | SHA1 | Date | |
|---|---|---|---|
| eeb2ef04fd | |||
| 32c5c40466 |
110
package-lock.json
generated
110
package-lock.json
generated
@@ -21,6 +21,7 @@
|
||||
"tailwindcss": "^4.0.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/ts-plugin": "^1.10.4",
|
||||
"@testing-library/dom": "^10.4.0",
|
||||
"@testing-library/react": "^16.2.0",
|
||||
"@types/lodash": "^4.17.17",
|
||||
@@ -68,6 +69,52 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/@astrojs/compiler": {
|
||||
"version": "2.12.2",
|
||||
"resolved": "https://registry.npmjs.org/@astrojs/compiler/-/compiler-2.12.2.tgz",
|
||||
"integrity": "sha512-w2zfvhjNCkNMmMMOn5b0J8+OmUaBL1o40ipMvqcG6NRpdC+lKxmTi48DT8Xw0SzJ3AfmeFLB45zXZXtmbsjcgw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@astrojs/ts-plugin": {
|
||||
"version": "1.10.4",
|
||||
"resolved": "https://registry.npmjs.org/@astrojs/ts-plugin/-/ts-plugin-1.10.4.tgz",
|
||||
"integrity": "sha512-rapryQINgv5VLZF884R/wmgX3mM9eH1PC/I3kkPV9rP6lEWrRN1YClF3bGcDHFrf8EtTLc0Wqxne1Uetpevozg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@astrojs/compiler": "^2.10.3",
|
||||
"@astrojs/yaml2ts": "^0.2.2",
|
||||
"@jridgewell/sourcemap-codec": "^1.4.15",
|
||||
"@volar/language-core": "~2.4.7",
|
||||
"@volar/typescript": "~2.4.7",
|
||||
"semver": "^7.3.8",
|
||||
"vscode-languageserver-textdocument": "^1.0.11"
|
||||
}
|
||||
},
|
||||
"node_modules/@astrojs/ts-plugin/node_modules/semver": {
|
||||
"version": "7.7.2",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
|
||||
"integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@astrojs/yaml2ts": {
|
||||
"version": "0.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@astrojs/yaml2ts/-/yaml2ts-0.2.2.tgz",
|
||||
"integrity": "sha512-GOfvSr5Nqy2z5XiwqTouBBpy5FyI6DEe+/g/Mk5am9SjILN1S5fOEvYK0GuWHg98yS/dobP4m8qyqw/URW35fQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"yaml": "^2.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@atlaskit/pragmatic-drag-and-drop": {
|
||||
"version": "1.7.4",
|
||||
"resolved": "https://registry.npmjs.org/@atlaskit/pragmatic-drag-and-drop/-/pragmatic-drag-and-drop-1.7.4.tgz",
|
||||
@@ -2249,6 +2296,35 @@
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/@volar/language-core": {
|
||||
"version": "2.4.16",
|
||||
"resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.16.tgz",
|
||||
"integrity": "sha512-mcoAFkYVQV4iiLYjTlbolbsm9hhDLtz4D4wTG+rwzSCUbEnxEec+KBlneLMlfdVNjkVEh8lUUSsCGNEQR+hFdA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@volar/source-map": "2.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/@volar/source-map": {
|
||||
"version": "2.4.16",
|
||||
"resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-2.4.16.tgz",
|
||||
"integrity": "sha512-4rBiAhOw4MfFTpkvweDnjbDkixpmWNgBws95rpu2oFdMprkTtqFEb8pUOxQ/ruru8/zXSYLwRNXNozznjW9Vtw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@volar/typescript": {
|
||||
"version": "2.4.16",
|
||||
"resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-2.4.16.tgz",
|
||||
"integrity": "sha512-CrRuG20euPerYc4H0kvDWSSLTBo6qgSI1/0BjXL9ogjm5j6l0gIffvNzEvfmVjr8TAuoMPD0NxuEkteIapfZQQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@volar/language-core": "2.4.16",
|
||||
"path-browserify": "^1.0.1",
|
||||
"vscode-uri": "^3.0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/acorn": {
|
||||
"version": "8.14.1",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz",
|
||||
@@ -3405,6 +3481,13 @@
|
||||
"url": "https://github.com/inikulin/parse5?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/path-browserify": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz",
|
||||
"integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pathe": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
|
||||
@@ -4256,6 +4339,20 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vscode-languageserver-textdocument": {
|
||||
"version": "1.0.12",
|
||||
"resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz",
|
||||
"integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vscode-uri": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz",
|
||||
"integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/w3c-xmlserializer": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
|
||||
@@ -4391,6 +4488,19 @@
|
||||
"integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/yaml": {
|
||||
"version": "2.8.0",
|
||||
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.0.tgz",
|
||||
"integrity": "sha512-4lLa/EcQCB0cJkyts+FpIRx5G/llPxfP6VQU5KByHEhLxY3IJCH0f0Hy1MHI8sClTvsIb8qwRJ6R/ZdlDJ/leQ==",
|
||||
"devOptional": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"yaml": "bin.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14.6"
|
||||
}
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "3.25.28",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.28.tgz",
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
"tailwindcss": "^4.0.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/ts-plugin": "^1.10.4",
|
||||
"@testing-library/dom": "^10.4.0",
|
||||
"@testing-library/react": "^16.2.0",
|
||||
"@types/lodash": "^4.17.17",
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useEffect, useState } from "react";
|
||||
import { Loader } from "./Loader";
|
||||
import { DocumentRow } from "./documents/DocumentRow";
|
||||
import { NewRelatedDocumentForm } from "./documents/NewRelatedDocumentForm";
|
||||
import { useDocument } from "@/context/document/DocumentContext";
|
||||
|
||||
interface RelationshipListProps {
|
||||
root: AnyDocument;
|
||||
@@ -26,64 +27,143 @@ export function RelationshipList({
|
||||
root,
|
||||
relationshipType,
|
||||
}: RelationshipListProps) {
|
||||
const [items, setItems] = useState<AnyDocument[]>([]);
|
||||
const [relationshipId, setRelationshipId] = useState<string | null>(null);
|
||||
// const [items, setItems] = useState<AnyDocument[]>([]);
|
||||
// const [relationshipId, setRelationshipId] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const queryClient = useQueryClient();
|
||||
// const queryClient = useQueryClient();
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchItems() {
|
||||
const { relationship } = await queryClient.fetchQuery({
|
||||
queryKey: ["relationship", relationshipType, root.id],
|
||||
staleTime: 5 * 60 * 1000, // 5 mintues
|
||||
queryFn: async () => {
|
||||
setLoading(true);
|
||||
const relationship: Relationship = await pb
|
||||
.collection("relationships")
|
||||
.getFirstListItem(
|
||||
`primary = "${root.id}" && type = "${relationshipType}"`,
|
||||
{
|
||||
expand: "secondary",
|
||||
},
|
||||
);
|
||||
|
||||
setLoading(false);
|
||||
|
||||
return { relationship };
|
||||
},
|
||||
});
|
||||
setRelationshipId(relationship.id);
|
||||
setItems(relationship.expand?.secondary ?? []);
|
||||
}
|
||||
|
||||
fetchItems();
|
||||
}, [root, relationshipType]);
|
||||
// useEffect(() => {
|
||||
// async function fetchItems() {
|
||||
// const { relationship } = await queryClient.fetchQuery({
|
||||
// queryKey: ["relationship", relationshipType, root.id],
|
||||
// staleTime: 5 * 60 * 1000, // 5 mintues
|
||||
// queryFn: async () => {
|
||||
// setLoading(true);
|
||||
// const relationship: Relationship = await pb
|
||||
// .collection("relationships")
|
||||
// .getFirstListItem(
|
||||
// `primary = "${root.id}" && type = "${relationshipType}"`,
|
||||
// {
|
||||
// expand: "secondary",
|
||||
// },
|
||||
// );
|
||||
//
|
||||
// setLoading(false);
|
||||
//
|
||||
// return { relationship };
|
||||
// },
|
||||
// });
|
||||
// setRelationshipId(relationship.id);
|
||||
// setItems(relationship.expand?.secondary ?? []);
|
||||
// }
|
||||
//
|
||||
// fetchItems();
|
||||
// }, [root, relationshipType]);
|
||||
|
||||
// Handles creation of a new document and adds it to the relationship
|
||||
// const handleCreate = async (doc: AnyDocument) => {
|
||||
// setLoading(true);
|
||||
// setError(null);
|
||||
// try {
|
||||
// // Check for existing relationship
|
||||
// if (relationshipId) {
|
||||
// console.debug("Adding to existing relationship", relationshipId);
|
||||
// await pb.collection("relationships").update(relationshipId, {
|
||||
// "+secondary": doc.id,
|
||||
// });
|
||||
// } else {
|
||||
// console.debug("Creating new relationship");
|
||||
// const relationship = await pb.collection("relationships").create({
|
||||
// primary: root.id,
|
||||
// secondary: [doc.id],
|
||||
// type: relationshipType,
|
||||
// });
|
||||
// setRelationshipId(relationship.id);
|
||||
// }
|
||||
// queryClient.invalidateQueries({
|
||||
// queryKey: ["relationship", relationshipType, root.id],
|
||||
// });
|
||||
// setItems((prev) => [doc, ...prev]);
|
||||
// } catch (e: any) {
|
||||
// setError(e?.message || "Failed to add document to relationship.");
|
||||
// } finally {
|
||||
// setLoading(false);
|
||||
// }
|
||||
// };
|
||||
//
|
||||
// const handleRemove = async (documentId: DocumentId) => {
|
||||
// setLoading(true);
|
||||
// setError(null);
|
||||
//
|
||||
// try {
|
||||
// if (relationshipId) {
|
||||
// console.debug("Removing from existing relationship", relationshipId);
|
||||
// await pb.collection("relationships").update(relationshipId, {
|
||||
// "secondary-": documentId,
|
||||
// });
|
||||
// }
|
||||
// queryClient.invalidateQueries({
|
||||
// queryKey: ["relationship", relationshipType, root.id],
|
||||
// });
|
||||
// setItems((prev) => prev.filter((item) => item.id != documentId));
|
||||
// } catch (e: any) {
|
||||
// setError(
|
||||
// e?.message || `Failed to remove document from ${relationshipType}.`,
|
||||
// );
|
||||
// } finally {
|
||||
// setLoading(false);
|
||||
// }
|
||||
// };
|
||||
//
|
||||
// if (loading) {
|
||||
// <Loader />;
|
||||
// }
|
||||
|
||||
const { state, dispatch } = useDocument();
|
||||
|
||||
if (state.status === "loading") {
|
||||
return <Loader />;
|
||||
}
|
||||
|
||||
const relationship = state.relationships[relationshipType];
|
||||
const itemIds = relationship?.secondary ?? [];
|
||||
const items = itemIds.map((id) => state.relatedDocs[id]).filter((d) => !!d);
|
||||
|
||||
const handleCreate = async (doc: AnyDocument) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
// Check for existing relationship
|
||||
if (relationshipId) {
|
||||
console.debug("Adding to existing relationship", relationshipId);
|
||||
await pb.collection("relationships").update(relationshipId, {
|
||||
if (relationship) {
|
||||
console.debug("Adding to existing relationship", relationship.id);
|
||||
const updatedRelationship: Relationship = await pb
|
||||
.collection("relationships")
|
||||
.update(relationship.id, {
|
||||
"+secondary": doc.id,
|
||||
});
|
||||
dispatch({
|
||||
type: "setRelationship",
|
||||
relationship: updatedRelationship,
|
||||
});
|
||||
} else {
|
||||
console.debug("Creating new relationship");
|
||||
const relationship = await pb.collection("relationships").create({
|
||||
const updatedRelationship: Relationship = await pb
|
||||
.collection("relationships")
|
||||
.create({
|
||||
primary: root.id,
|
||||
secondary: [doc.id],
|
||||
type: relationshipType,
|
||||
});
|
||||
setRelationshipId(relationship.id);
|
||||
}
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["relationship", relationshipType, root.id],
|
||||
dispatch({
|
||||
type: "setRelationship",
|
||||
relationship: updatedRelationship,
|
||||
});
|
||||
setItems((prev) => [...prev, doc]);
|
||||
dispatch({
|
||||
type: "setRelatedDocument",
|
||||
doc,
|
||||
});
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to add document to relationship.");
|
||||
} finally {
|
||||
@@ -96,18 +176,18 @@ export function RelationshipList({
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (relationshipId) {
|
||||
console.debug("Removing from existing relationship", relationshipId);
|
||||
await pb.collection("relationships").update(relationshipId, {
|
||||
secondary: items
|
||||
.map((item) => item.id)
|
||||
.filter((id) => id !== documentId),
|
||||
if (relationship) {
|
||||
console.debug("Removing from existing relationship", relationship.id);
|
||||
const updatedRelationship: Relationship = await pb
|
||||
.collection("relationships")
|
||||
.update(relationship.id, {
|
||||
"secondary-": documentId,
|
||||
});
|
||||
dispatch({
|
||||
type: "setRelationship",
|
||||
relationship: updatedRelationship,
|
||||
});
|
||||
}
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["relationship", relationshipType, root.id],
|
||||
});
|
||||
setItems((prev) => prev.filter((item) => item.id != documentId));
|
||||
} catch (e: any) {
|
||||
setError(
|
||||
e?.message || `Failed to remove document from ${relationshipType}.`,
|
||||
@@ -117,10 +197,6 @@ export function RelationshipList({
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
<Loader />;
|
||||
}
|
||||
|
||||
return (
|
||||
<DocumentList
|
||||
title={displayName(relationshipType)}
|
||||
|
||||
55
src/components/documents/DocumentView.tsx
Normal file
55
src/components/documents/DocumentView.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import { RelationshipList } from "@/components/RelationshipList";
|
||||
import { DocumentEditForm } from "@/components/documents/DocumentEditForm";
|
||||
import { useDocument } from "@/context/document/DocumentContext";
|
||||
import { displayName, relationshipsForDocument } from "@/lib/relationships";
|
||||
import { Tab, TabGroup, TabList, TabPanel, TabPanels } from "@headlessui/react";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { Loader } from "../Loader";
|
||||
|
||||
export function DocumentView() {
|
||||
const { state } = useDocument();
|
||||
|
||||
if (state.status === "loading") {
|
||||
return <Loader />;
|
||||
}
|
||||
|
||||
const doc = state.doc;
|
||||
|
||||
const relationshipList = relationshipsForDocument(doc);
|
||||
|
||||
return (
|
||||
<div key={doc.id} className="max-w-xl mx-auto py-2 px-4">
|
||||
<Link
|
||||
to="/document/$documentId/print"
|
||||
params={{ documentId: doc.id }}
|
||||
className="text-slate-400 hover:text-violet-400 text-sm underline underline-offset-2 transition-colors mb-4"
|
||||
>
|
||||
Print
|
||||
</Link>
|
||||
<DocumentEditForm document={doc} />
|
||||
<TabGroup>
|
||||
<TabList className="flex flex-row flex-wrap gap-1 mt-2">
|
||||
{relationshipList.map((relationshipType) => (
|
||||
<Tab
|
||||
key={relationshipType}
|
||||
className="px-3 py-2 rounded bg-slate-800 text-slate-100 border border-slate-700 focus:outline-none focus:ring-2 focus:ring-violet-500 data-selected:bg-violet-900 data-selected:border-violet-700"
|
||||
>
|
||||
{displayName(relationshipType)}
|
||||
</Tab>
|
||||
))}
|
||||
</TabList>
|
||||
<TabPanels>
|
||||
{relationshipList.map((relationshipType) => (
|
||||
<TabPanel key={relationshipType}>
|
||||
<RelationshipList
|
||||
key={relationshipType}
|
||||
root={doc}
|
||||
relationshipType={relationshipType}
|
||||
/>
|
||||
</TabPanel>
|
||||
))}
|
||||
</TabPanels>
|
||||
</TabGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,9 @@ import type { Session } from "@/lib/types";
|
||||
|
||||
export const SessionEditForm = ({ session }: { session: Session }) => {
|
||||
async function saveStrongStart(strongStart: string) {
|
||||
await pb.collection("documents").update(session.id, {
|
||||
const freshRecord: Session = await pb
|
||||
.collection("documents")
|
||||
.update(session.id, {
|
||||
data: {
|
||||
...session.data,
|
||||
strongStart,
|
||||
|
||||
75
src/context/document/DocumentContext.tsx
Normal file
75
src/context/document/DocumentContext.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import { pb } from "@/lib/pocketbase";
|
||||
import { type AnyDocument, type DocumentId } from "@/lib/types";
|
||||
import type { ReactNode } from "react";
|
||||
import { createContext, useContext, useEffect, useReducer } from "react";
|
||||
import type { DocumentAction } from "./actions";
|
||||
import { reducer } from "./reducer";
|
||||
import { loading, type DocumentState } from "./state";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import type { RecordModel } from "pocketbase";
|
||||
|
||||
type DocumentContextValue = {
|
||||
state: DocumentState<AnyDocument>;
|
||||
dispatch: (action: DocumentAction<AnyDocument>) => void;
|
||||
};
|
||||
|
||||
const DocumentContext = createContext<DocumentContextValue | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
/**
|
||||
* Provider for the record cache context. Provides a singleton RecordCache instance to children.
|
||||
*/
|
||||
export function DocumentProvider({
|
||||
documentId,
|
||||
children,
|
||||
}: {
|
||||
documentId: DocumentId;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
const [state, dispatch] = useReducer(reducer, loading());
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchDocumentAndRelations() {
|
||||
const doc: AnyDocument = await queryClient.fetchQuery({
|
||||
queryKey: ["document", documentId],
|
||||
staleTime: 5 * 60 * 1000, // 5 mintues
|
||||
queryFn: () =>
|
||||
pb.collection("documents").getOne(documentId, {
|
||||
expand:
|
||||
"relationships_via_primary,relationships_via_primary.secondary",
|
||||
}),
|
||||
});
|
||||
|
||||
dispatch({
|
||||
type: "ready",
|
||||
doc,
|
||||
relationships: doc.expand?.relationships_via_primary || [],
|
||||
relatedDocuments:
|
||||
doc.expand?.relationships_via_primary.flatMap(
|
||||
(r: RecordModel) => r.expand?.secondary,
|
||||
) || [],
|
||||
});
|
||||
}
|
||||
|
||||
fetchDocumentAndRelations();
|
||||
}, [documentId]);
|
||||
return (
|
||||
<DocumentContext.Provider
|
||||
value={{
|
||||
state,
|
||||
dispatch,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</DocumentContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useDocument(): DocumentContextValue {
|
||||
const ctx = useContext(DocumentContext);
|
||||
if (!ctx)
|
||||
throw new Error("useDocument must be used within a DocumentProvider");
|
||||
return ctx;
|
||||
}
|
||||
24
src/context/document/actions.ts
Normal file
24
src/context/document/actions.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { AnyDocument, Relationship } from "@/lib/types";
|
||||
|
||||
export type DocumentAction<D extends AnyDocument> =
|
||||
| {
|
||||
type: "loading";
|
||||
}
|
||||
| {
|
||||
type: "ready";
|
||||
doc: D;
|
||||
relationships: Relationship[];
|
||||
relatedDocuments: AnyDocument[];
|
||||
}
|
||||
| {
|
||||
type: "update";
|
||||
data: D["data"];
|
||||
}
|
||||
| {
|
||||
type: "setRelationship";
|
||||
relationship: Relationship;
|
||||
}
|
||||
| {
|
||||
type: "setRelatedDocument";
|
||||
doc: AnyDocument;
|
||||
};
|
||||
75
src/context/document/reducer.ts
Normal file
75
src/context/document/reducer.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import _ from "lodash";
|
||||
import type {
|
||||
AnyDocument,
|
||||
DocumentId,
|
||||
Relationship,
|
||||
RelationshipId,
|
||||
RelationshipType,
|
||||
} from "@/lib/types";
|
||||
import type { DocumentAction } from "./actions";
|
||||
import type { DocumentState } from "./state";
|
||||
|
||||
function ifStatus<D extends AnyDocument, S extends DocumentState<D>["status"]>(
|
||||
status: S,
|
||||
state: DocumentState<D>,
|
||||
newState: (state: DocumentState<D> & { status: S }) => DocumentState<D>,
|
||||
) {
|
||||
// TODO: Is there a better way to express the type of type narrowing?
|
||||
return state.status === status
|
||||
? newState(state as DocumentState<D> & { status: S })
|
||||
: state;
|
||||
}
|
||||
|
||||
export function reducer<D extends AnyDocument>(
|
||||
state: DocumentState<D>,
|
||||
action: DocumentAction<D>,
|
||||
): DocumentState<D> {
|
||||
switch (action.type) {
|
||||
case "loading":
|
||||
return {
|
||||
status: "loading",
|
||||
};
|
||||
case "ready":
|
||||
return {
|
||||
status: "ready",
|
||||
doc: action.doc,
|
||||
relationships: _.keyBy(action.relationships, (r) => r.type) as Record<
|
||||
RelationshipType,
|
||||
Relationship
|
||||
>,
|
||||
relatedDocs: _.keyBy(action.relatedDocuments, (r) => r.id) as Record<
|
||||
DocumentId,
|
||||
AnyDocument
|
||||
>,
|
||||
};
|
||||
|
||||
case "update":
|
||||
if (state.status === "ready") {
|
||||
return {
|
||||
...state,
|
||||
doc: {
|
||||
...state.doc,
|
||||
data: action.data,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
return state;
|
||||
}
|
||||
case "setRelationship":
|
||||
return ifStatus("ready", state, (state) => ({
|
||||
...state,
|
||||
relationships: {
|
||||
...state.relationships,
|
||||
[action.relationship.type]: action.relationship,
|
||||
},
|
||||
}));
|
||||
case "setRelatedDocument":
|
||||
return ifStatus("ready", state, (state) => ({
|
||||
...state,
|
||||
relatedDocs: {
|
||||
...state.relatedDocs,
|
||||
[action.doc.id]: action.doc,
|
||||
},
|
||||
}));
|
||||
}
|
||||
}
|
||||
21
src/context/document/state.ts
Normal file
21
src/context/document/state.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type {
|
||||
AnyDocument,
|
||||
DocumentId,
|
||||
Relationship,
|
||||
RelationshipType,
|
||||
} from "@/lib/types";
|
||||
|
||||
export type DocumentState<D extends AnyDocument> =
|
||||
| {
|
||||
status: "loading";
|
||||
}
|
||||
| {
|
||||
status: "ready";
|
||||
doc: D;
|
||||
relationships: Record<RelationshipType, Relationship>;
|
||||
relatedDocs: Record<DocumentId, AnyDocument>;
|
||||
};
|
||||
|
||||
export const loading = <D extends AnyDocument>(): DocumentState<D> => ({
|
||||
status: "loading",
|
||||
});
|
||||
112
src/lib/recordCache.ts
Normal file
112
src/lib/recordCache.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import {
|
||||
type CollectionId,
|
||||
type AnyDocument,
|
||||
CollectionIds,
|
||||
type Relationship,
|
||||
type DocumentId,
|
||||
type RelationshipId,
|
||||
type DbRecord,
|
||||
} from "./types";
|
||||
|
||||
export type CacheKey<C extends CollectionId = CollectionId> = `${C}:${string}`;
|
||||
export type CacheValue<C extends CollectionId = CollectionId> = {
|
||||
record: Promise<DbRecord<C>>;
|
||||
subscriptions: ((record: DbRecord<C> | null) => void)[];
|
||||
};
|
||||
type DocumentKey = CacheKey<typeof CollectionIds.Documents>;
|
||||
type RelationshipKey = CacheKey<typeof CollectionIds.Relationships>;
|
||||
|
||||
export class RecordCache {
|
||||
private cache: Record<`${CollectionId}:${string}`, CacheValue> = {};
|
||||
|
||||
static makeKey<C extends CollectionId>(
|
||||
collectionId: C,
|
||||
id: string,
|
||||
): CacheKey<C> {
|
||||
return `${collectionId}:${id}`;
|
||||
}
|
||||
|
||||
static docKey = (id: DocumentId): DocumentKey =>
|
||||
RecordCache.makeKey(CollectionIds.Documents, id);
|
||||
|
||||
static relationKey = (id: RelationshipId): RelationshipKey =>
|
||||
RecordCache.makeKey(CollectionIds.Relationships, id);
|
||||
|
||||
get = <C extends CollectionId>(
|
||||
key: CacheKey<C>,
|
||||
): Promise<DbRecord<C>> | undefined =>
|
||||
this.cache[key]?.record as Promise<DbRecord<C>> | undefined;
|
||||
|
||||
pending = <C extends CollectionId>(
|
||||
key: CacheKey<C>,
|
||||
record: Promise<DbRecord<C>>,
|
||||
) => {
|
||||
if (this.cache[key] === undefined) {
|
||||
this.cache[key] = {
|
||||
record: record,
|
||||
subscriptions: [],
|
||||
};
|
||||
}
|
||||
const entry = this.cache[key];
|
||||
|
||||
entry.record = record;
|
||||
|
||||
record.then((record) => {
|
||||
for (const subscription of entry.subscriptions) {
|
||||
subscription(record);
|
||||
}
|
||||
for (const doc of record.expand?.secondary ?? []) {
|
||||
this.set(doc);
|
||||
}
|
||||
for (const rel of record.expand?.relationships_via_primary ?? []) {
|
||||
this.set(rel);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
set = <C extends CollectionId>(record: DbRecord<C>) => {
|
||||
const key = RecordCache.makeKey(
|
||||
record.collectionName as CollectionId,
|
||||
record.id,
|
||||
);
|
||||
if (this.cache[key] === undefined) {
|
||||
this.cache[key] = {
|
||||
record: Promise.resolve(record),
|
||||
subscriptions: [],
|
||||
};
|
||||
}
|
||||
const entry = this.cache[key];
|
||||
|
||||
entry.record = Promise.resolve(record);
|
||||
|
||||
for (const subscription of entry.subscriptions) {
|
||||
subscription(record);
|
||||
}
|
||||
|
||||
for (const doc of record.expand?.secondary ?? []) {
|
||||
this.set(doc);
|
||||
}
|
||||
for (const rel of record.expand?.relationships_via_primary ?? []) {
|
||||
this.set(rel);
|
||||
}
|
||||
};
|
||||
|
||||
remove = (key: CacheKey) => {
|
||||
const entry = this.cache[key];
|
||||
delete this.cache[key];
|
||||
for (const subscription of entry.subscriptions) {
|
||||
subscription(null);
|
||||
}
|
||||
};
|
||||
|
||||
getDocument = (id: DocumentId): AnyDocument | undefined =>
|
||||
this.get(RecordCache.docKey(id)) as AnyDocument | undefined;
|
||||
|
||||
getRelationship = (id: RelationshipId): Relationship | undefined =>
|
||||
this.get(RecordCache.relationKey(id)) as Relationship | undefined;
|
||||
|
||||
removeDocument = (id: DocumentId) => this.remove(RecordCache.docKey(id));
|
||||
|
||||
removeRelationship = (id: RelationshipId) =>
|
||||
this.remove(RecordCache.relationKey(id));
|
||||
}
|
||||
@@ -1,13 +1,34 @@
|
||||
import type { RecordModel } from "pocketbase";
|
||||
|
||||
export type Id<T extends string> = string & { __type: T };
|
||||
export const CollectionIds = {
|
||||
Users: "users",
|
||||
Campaigns: "campaigns",
|
||||
Documents: "documents",
|
||||
Relationships: "relationships",
|
||||
} as const;
|
||||
|
||||
export type UserId = Id<"User">;
|
||||
export type CampaignId = Id<"Campaign">;
|
||||
export type DocumentId = Id<"Document">;
|
||||
export type CollectionId = (typeof CollectionIds)[keyof typeof CollectionIds];
|
||||
|
||||
export type Id<T extends CollectionId> = string & { __type: T };
|
||||
|
||||
export type UserId = Id<typeof CollectionIds.Users>;
|
||||
export type CampaignId = Id<typeof CollectionIds.Campaigns>;
|
||||
export type DocumentId = Id<typeof CollectionIds.Documents>;
|
||||
export type RelationshipId = Id<typeof CollectionIds.Relationships>;
|
||||
|
||||
export type ISO8601Date = string & { __type: "iso8601date" };
|
||||
|
||||
export type DbRecord<C extends CollectionId = CollectionId> = {
|
||||
[CollectionIds.Campaigns]: Campaign;
|
||||
[CollectionIds.Documents]: AnyDocument;
|
||||
[CollectionIds.Relationships]: Relationship;
|
||||
[CollectionIds.Users]: RecordModel;
|
||||
}[C];
|
||||
|
||||
/******************************************
|
||||
* Campaigns
|
||||
******************************************/
|
||||
|
||||
export type Campaign = RecordModel & {
|
||||
id: CampaignId;
|
||||
name: string;
|
||||
@@ -32,6 +53,8 @@ export type RelationshipType =
|
||||
(typeof RelationshipType)[keyof typeof RelationshipType];
|
||||
|
||||
export type Relationship = RecordModel & {
|
||||
id: RelationshipId;
|
||||
collectionName: typeof CollectionIds.Relationships;
|
||||
primary: DocumentId;
|
||||
secondary: DocumentId[];
|
||||
type: RelationshipType;
|
||||
@@ -57,6 +80,7 @@ export type DocumentData<Type extends DocumentType, Data> = {
|
||||
|
||||
export type Document<Type extends DocumentType, Data> = RecordModel & {
|
||||
id: DocumentId;
|
||||
collectionName: typeof CollectionIds.Documents;
|
||||
campaign: CampaignId;
|
||||
type: Type;
|
||||
data: Data;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Loader } from "@/components/Loader";
|
||||
import { useAuth } from "@/context/auth/AuthContext";
|
||||
import { Link, Outlet, createFileRoute } from "@tanstack/react-router";
|
||||
import { Suspense } from "react";
|
||||
|
||||
export const Route = createFileRoute("/_app")({
|
||||
component: RouteComponent,
|
||||
@@ -71,7 +73,9 @@ function RouteComponent() {
|
||||
return (
|
||||
<>
|
||||
<AppHeader />
|
||||
<Suspense fallback={<Loader />}>
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,63 +1,21 @@
|
||||
import { RelationshipList } from "@/components/RelationshipList";
|
||||
import { DocumentEditForm } from "@/components/documents/DocumentEditForm";
|
||||
import { pb } from "@/lib/pocketbase";
|
||||
import { displayName, relationshipsForDocument } from "@/lib/relationships";
|
||||
import { RelationshipType, type AnyDocument } from "@/lib/types";
|
||||
import { Tab, TabGroup, TabList, TabPanel, TabPanels } from "@headlessui/react";
|
||||
import { createFileRoute, Link } from "@tanstack/react-router";
|
||||
import { DocumentView } from "@/components/documents/DocumentView";
|
||||
import { DocumentProvider } from "@/context/document/DocumentContext";
|
||||
import type { DocumentId } from "@/lib/types";
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
export const Route = createFileRoute(
|
||||
"/_app/_authenticated/document/$documentId",
|
||||
)({
|
||||
loader: async ({ params }) => {
|
||||
const doc = await pb.collection("documents").getOne(params.documentId);
|
||||
return {
|
||||
document: doc,
|
||||
};
|
||||
},
|
||||
component: RouteComponent,
|
||||
});
|
||||
|
||||
function RouteComponent() {
|
||||
const { document } = Route.useLoaderData() as {
|
||||
document: AnyDocument;
|
||||
};
|
||||
|
||||
const relationshipList = relationshipsForDocument(document);
|
||||
const { documentId } = Route.useParams();
|
||||
console.info("Rendering document route: ", documentId);
|
||||
|
||||
return (
|
||||
<div key={document.id} className="max-w-xl mx-auto py-2 px-4">
|
||||
<Link
|
||||
to="/document/$documentId/print"
|
||||
params={{ documentId: document.id }}
|
||||
className="text-slate-400 hover:text-violet-400 text-sm underline underline-offset-2 transition-colors mb-4"
|
||||
>
|
||||
Print
|
||||
</Link>
|
||||
<DocumentEditForm document={document} />
|
||||
<TabGroup>
|
||||
<TabList className="flex flex-row flex-wrap gap-1 mt-2">
|
||||
{relationshipList.map((relationshipType) => (
|
||||
<Tab
|
||||
key={relationshipType}
|
||||
className="px-3 py-2 rounded bg-slate-800 text-slate-100 border border-slate-700 focus:outline-none focus:ring-2 focus:ring-violet-500 data-selected:bg-violet-900 data-selected:border-violet-700"
|
||||
>
|
||||
{displayName(relationshipType)}
|
||||
</Tab>
|
||||
))}
|
||||
</TabList>
|
||||
<TabPanels>
|
||||
{relationshipList.map((relationshipType) => (
|
||||
<TabPanel key={relationshipType}>
|
||||
<RelationshipList
|
||||
key={relationshipType}
|
||||
root={document}
|
||||
relationshipType={relationshipType}
|
||||
/>
|
||||
</TabPanel>
|
||||
))}
|
||||
</TabPanels>
|
||||
</TabGroup>
|
||||
</div>
|
||||
<DocumentProvider documentId={documentId as DocumentId}>
|
||||
<DocumentView />
|
||||
</DocumentProvider>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user