Compare commits
2 Commits
eeb2ef04fd
...
db4ce36c27
| Author | SHA1 | Date | |
|---|---|---|---|
| db4ce36c27 | |||
| f27432ef05 |
@@ -1,4 +1,5 @@
|
|||||||
import { DocumentList } from "@/components/DocumentList";
|
import { DocumentList } from "@/components/DocumentList";
|
||||||
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
import { pb } from "@/lib/pocketbase";
|
import { pb } from "@/lib/pocketbase";
|
||||||
import { displayName } from "@/lib/relationships";
|
import { displayName } from "@/lib/relationships";
|
||||||
import type {
|
import type {
|
||||||
@@ -7,8 +8,7 @@ import type {
|
|||||||
Relationship,
|
Relationship,
|
||||||
RelationshipType,
|
RelationshipType,
|
||||||
} from "@/lib/types";
|
} from "@/lib/types";
|
||||||
import { useQueryClient } from "@tanstack/react-query";
|
import { useState } from "react";
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { Loader } from "./Loader";
|
import { Loader } from "./Loader";
|
||||||
import { DocumentRow } from "./documents/DocumentRow";
|
import { DocumentRow } from "./documents/DocumentRow";
|
||||||
import { NewRelatedDocumentForm } from "./documents/NewRelatedDocumentForm";
|
import { NewRelatedDocumentForm } from "./documents/NewRelatedDocumentForm";
|
||||||
@@ -26,64 +26,50 @@ export function RelationshipList({
|
|||||||
root,
|
root,
|
||||||
relationshipType,
|
relationshipType,
|
||||||
}: RelationshipListProps) {
|
}: RelationshipListProps) {
|
||||||
const [items, setItems] = useState<AnyDocument[]>([]);
|
const [_loading, setLoading] = useState(true);
|
||||||
const [relationshipId, setRelationshipId] = useState<string | null>(null);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const queryClient = useQueryClient();
|
const { state, dispatch } = useDocument();
|
||||||
|
|
||||||
useEffect(() => {
|
if (state.status === "loading") {
|
||||||
async function fetchItems() {
|
return <Loader />;
|
||||||
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();
|
console.info("Rendering relationship list: ", relationshipType);
|
||||||
}, [root, relationshipType]);
|
|
||||||
|
const relationship = state.relationships[relationshipType];
|
||||||
|
const itemIds = relationship?.secondary ?? [];
|
||||||
|
const items = itemIds.map((id) => state.relatedDocs[id]).filter((d) => !!d);
|
||||||
|
|
||||||
// Handles creation of a new document and adds it to the relationship
|
|
||||||
const handleCreate = async (doc: AnyDocument) => {
|
const handleCreate = async (doc: AnyDocument) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
// Check for existing relationship
|
// Check for existing relationship
|
||||||
if (relationshipId) {
|
if (relationship) {
|
||||||
console.debug("Adding to existing relationship", relationshipId);
|
console.debug("Adding to existing relationship", relationship.id);
|
||||||
await pb.collection("relationships").update(relationshipId, {
|
const updatedRelationship: Relationship = await pb
|
||||||
|
.collection("relationships")
|
||||||
|
.update(relationship.id, {
|
||||||
"+secondary": doc.id,
|
"+secondary": doc.id,
|
||||||
});
|
});
|
||||||
|
dispatch({
|
||||||
|
type: "setRelationship",
|
||||||
|
relationship: updatedRelationship,
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
console.debug("Creating new relationship");
|
console.debug("Creating new relationship");
|
||||||
const relationship = await pb.collection("relationships").create({
|
const updatedRelationship: Relationship = await pb
|
||||||
|
.collection("relationships")
|
||||||
|
.create({
|
||||||
primary: root.id,
|
primary: root.id,
|
||||||
secondary: [doc.id],
|
secondary: [doc.id],
|
||||||
type: relationshipType,
|
type: relationshipType,
|
||||||
});
|
});
|
||||||
setRelationshipId(relationship.id);
|
dispatch({
|
||||||
}
|
type: "setRelationship",
|
||||||
queryClient.invalidateQueries({
|
relationship: updatedRelationship,
|
||||||
queryKey: ["relationship", relationshipType, root.id],
|
|
||||||
});
|
});
|
||||||
setItems((prev) => [doc, ...prev]);
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(e?.message || "Failed to add document to relationship.");
|
setError(e?.message || "Failed to add document to relationship.");
|
||||||
} finally {
|
} finally {
|
||||||
@@ -96,16 +82,18 @@ export function RelationshipList({
|
|||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (relationshipId) {
|
if (relationship) {
|
||||||
console.debug("Removing from existing relationship", relationshipId);
|
console.debug("Removing from existing relationship", relationship.id);
|
||||||
await pb.collection("relationships").update(relationshipId, {
|
const updatedRelationship: Relationship = await pb
|
||||||
|
.collection("relationships")
|
||||||
|
.update(relationship.id, {
|
||||||
"secondary-": documentId,
|
"secondary-": documentId,
|
||||||
});
|
});
|
||||||
}
|
dispatch({
|
||||||
queryClient.invalidateQueries({
|
type: "setRelationship",
|
||||||
queryKey: ["relationship", relationshipType, root.id],
|
relationship: updatedRelationship,
|
||||||
});
|
});
|
||||||
setItems((prev) => prev.filter((item) => item.id != documentId));
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(
|
setError(
|
||||||
e?.message || `Failed to remove document from ${relationshipType}.`,
|
e?.message || `Failed to remove document from ${relationshipType}.`,
|
||||||
@@ -115,10 +103,6 @@ export function RelationshipList({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
<Loader />;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DocumentList
|
<DocumentList
|
||||||
title={displayName(relationshipType)}
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,27 +1,31 @@
|
|||||||
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
||||||
import { pb } from "@/lib/pocketbase";
|
import { pb } from "@/lib/pocketbase";
|
||||||
import type { Location } from "@/lib/types";
|
import type { Location } from "@/lib/types";
|
||||||
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders an editable location form
|
* Renders an editable location form
|
||||||
*/
|
*/
|
||||||
export const LocationEditForm = ({ location }: { location: Location }) => {
|
export const LocationEditForm = ({ location }: { location: Location }) => {
|
||||||
|
const { dispatch } = useDocument();
|
||||||
async function saveLocationName(name: string) {
|
async function saveLocationName(name: string) {
|
||||||
await pb.collection("documents").update(location.id, {
|
const updated: Location = await pb.collection("documents").update(location.id, {
|
||||||
data: {
|
data: {
|
||||||
...location.data,
|
...location.data,
|
||||||
name,
|
name,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
dispatch({ type: "setDocument", doc: updated });
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveLocationDescription(description: string) {
|
async function saveLocationDescription(description: string) {
|
||||||
await pb.collection("documents").update(location.id, {
|
const updated: Location = await pb.collection("documents").update(location.id, {
|
||||||
data: {
|
data: {
|
||||||
...location.data,
|
...location.data,
|
||||||
description,
|
description,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
dispatch({ type: "setDocument", doc: updated });
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { pb } from "@/lib/pocketbase";
|
|||||||
import { BaseForm } from "@/components/form/BaseForm";
|
import { BaseForm } from "@/components/form/BaseForm";
|
||||||
import { MultiLineInput } from "@/components/form/MultiLineInput";
|
import { MultiLineInput } from "@/components/form/MultiLineInput";
|
||||||
import { SingleLineInput } from "@/components/form/SingleLineInput";
|
import { SingleLineInput } from "@/components/form/SingleLineInput";
|
||||||
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders a form to add a new location. Calls onCreate with the new location document.
|
* Renders a form to add a new location. Calls onCreate with the new location document.
|
||||||
@@ -15,6 +16,7 @@ export const NewLocationForm = ({
|
|||||||
campaign: CampaignId;
|
campaign: CampaignId;
|
||||||
onCreate: (location: Location) => Promise<void>;
|
onCreate: (location: Location) => Promise<void>;
|
||||||
}) => {
|
}) => {
|
||||||
|
const { dispatch } = useDocument();
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [description, setDescription] = useState("");
|
const [description, setDescription] = useState("");
|
||||||
const [adding, setAdding] = useState(false);
|
const [adding, setAdding] = useState(false);
|
||||||
@@ -36,6 +38,7 @@ export const NewLocationForm = ({
|
|||||||
});
|
});
|
||||||
setName("");
|
setName("");
|
||||||
setDescription("");
|
setDescription("");
|
||||||
|
dispatch({ type: "setDocument", doc: locationDoc});
|
||||||
await onCreate(locationDoc);
|
await onCreate(locationDoc);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(e?.message || "Failed to add location.");
|
setError(e?.message || "Failed to add location.");
|
||||||
|
|||||||
@@ -1,18 +1,21 @@
|
|||||||
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
||||||
import { pb } from "@/lib/pocketbase";
|
import { pb } from "@/lib/pocketbase";
|
||||||
import type { Monster } from "@/lib/types";
|
import type { Monster } from "@/lib/types";
|
||||||
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders an editable monster row
|
* Renders an editable monster row
|
||||||
*/
|
*/
|
||||||
export const MonsterEditForm = ({ monster }: { monster: Monster }) => {
|
export const MonsterEditForm = ({ monster }: { monster: Monster }) => {
|
||||||
|
const { dispatch } = useDocument();
|
||||||
async function saveMonsterName(name: string) {
|
async function saveMonsterName(name: string) {
|
||||||
await pb.collection("documents").update(monster.id, {
|
const updated = await pb.collection("documents").update(monster.id, {
|
||||||
data: {
|
data: {
|
||||||
...monster.data,
|
...monster.data,
|
||||||
name,
|
name,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
dispatch({ type: "setDocument", doc: updated });
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type { CampaignId, Monster } from "@/lib/types";
|
|||||||
import { pb } from "@/lib/pocketbase";
|
import { pb } from "@/lib/pocketbase";
|
||||||
import { BaseForm } from "@/components/form/BaseForm";
|
import { BaseForm } from "@/components/form/BaseForm";
|
||||||
import { SingleLineInput } from "@/components/form/SingleLineInput";
|
import { SingleLineInput } from "@/components/form/SingleLineInput";
|
||||||
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders a form to add a new monster. Calls onCreate with the new monster document.
|
* Renders a form to add a new monster. Calls onCreate with the new monster document.
|
||||||
@@ -14,6 +15,7 @@ export const NewMonsterForm = ({
|
|||||||
campaign: CampaignId;
|
campaign: CampaignId;
|
||||||
onCreate: (monster: Monster) => Promise<void>;
|
onCreate: (monster: Monster) => Promise<void>;
|
||||||
}) => {
|
}) => {
|
||||||
|
const { dispatch } = useDocument();
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [adding, setAdding] = useState(false);
|
const [adding, setAdding] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -32,6 +34,7 @@ export const NewMonsterForm = ({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
setName("");
|
setName("");
|
||||||
|
dispatch({ type: "setDocument", doc: monsterDoc });
|
||||||
await onCreate(monsterDoc);
|
await onCreate(monsterDoc);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(e?.message || "Failed to add monster.");
|
setError(e?.message || "Failed to add monster.");
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { pb } from "@/lib/pocketbase";
|
|||||||
import { BaseForm } from "@/components/form/BaseForm";
|
import { BaseForm } from "@/components/form/BaseForm";
|
||||||
import { SingleLineInput } from "@/components/form/SingleLineInput";
|
import { SingleLineInput } from "@/components/form/SingleLineInput";
|
||||||
import { MultiLineInput } from "@/components/form/MultiLineInput";
|
import { MultiLineInput } from "@/components/form/MultiLineInput";
|
||||||
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders a form to add a new npc. Calls onCreate with the new npc document.
|
* Renders a form to add a new npc. Calls onCreate with the new npc document.
|
||||||
@@ -15,6 +16,7 @@ export const NewNpcForm = ({
|
|||||||
campaign: CampaignId;
|
campaign: CampaignId;
|
||||||
onCreate: (npc: Npc) => Promise<void>;
|
onCreate: (npc: Npc) => Promise<void>;
|
||||||
}) => {
|
}) => {
|
||||||
|
const { dispatch } = useDocument();
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [description, setDescription] = useState("");
|
const [description, setDescription] = useState("");
|
||||||
const [adding, setAdding] = useState(false);
|
const [adding, setAdding] = useState(false);
|
||||||
@@ -36,6 +38,7 @@ export const NewNpcForm = ({
|
|||||||
});
|
});
|
||||||
setName("");
|
setName("");
|
||||||
setDescription("");
|
setDescription("");
|
||||||
|
dispatch({ type: "setDocument", doc: npcDoc });
|
||||||
await onCreate(npcDoc);
|
await onCreate(npcDoc);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(e?.message || "Failed to add npc.");
|
setError(e?.message || "Failed to add npc.");
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
||||||
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
import { pb } from "@/lib/pocketbase";
|
import { pb } from "@/lib/pocketbase";
|
||||||
import type { Npc } from "@/lib/types";
|
import type { Npc } from "@/lib/types";
|
||||||
|
|
||||||
@@ -6,22 +7,25 @@ import type { Npc } from "@/lib/types";
|
|||||||
* Renders an editable npc form
|
* Renders an editable npc form
|
||||||
*/
|
*/
|
||||||
export const NpcEditForm = ({ npc }: { npc: Npc }) => {
|
export const NpcEditForm = ({ npc }: { npc: Npc }) => {
|
||||||
|
const { dispatch } = useDocument();
|
||||||
async function saveNpcName(name: string) {
|
async function saveNpcName(name: string) {
|
||||||
await pb.collection("documents").update(npc.id, {
|
const updated: Npc = await pb.collection("documents").update(npc.id, {
|
||||||
data: {
|
data: {
|
||||||
...npc.data,
|
...npc.data,
|
||||||
name,
|
name,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
dispatch({ type: "setDocument", doc: updated });
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveNpcDescription(description: string) {
|
async function saveNpcDescription(description: string) {
|
||||||
await pb.collection("documents").update(npc.id, {
|
const updated: Npc = await pb.collection("documents").update(npc.id, {
|
||||||
data: {
|
data: {
|
||||||
...npc.data,
|
...npc.data,
|
||||||
description,
|
description,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
dispatch({ type: "setDocument", doc: updated });
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import type { CampaignId, Scene } from "@/lib/types";
|
|||||||
import { pb } from "@/lib/pocketbase";
|
import { pb } from "@/lib/pocketbase";
|
||||||
import { BaseForm } from "@/components/form/BaseForm";
|
import { BaseForm } from "@/components/form/BaseForm";
|
||||||
import { MultiLineInput } from "@/components/form/MultiLineInput";
|
import { MultiLineInput } from "@/components/form/MultiLineInput";
|
||||||
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders a form to add a new scene. Calls onCreate with the new scene document.
|
* Renders a form to add a new scene. Calls onCreate with the new scene document.
|
||||||
@@ -16,6 +17,7 @@ export const NewSceneForm = ({
|
|||||||
campaign: CampaignId;
|
campaign: CampaignId;
|
||||||
onCreate: (scene: Scene) => Promise<void>;
|
onCreate: (scene: Scene) => Promise<void>;
|
||||||
}) => {
|
}) => {
|
||||||
|
const { dispatch } = useDocument();
|
||||||
const [text, setText] = useState("");
|
const [text, setText] = useState("");
|
||||||
const [adding, setAdding] = useState(false);
|
const [adding, setAdding] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -34,6 +36,7 @@ export const NewSceneForm = ({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
setText("");
|
setText("");
|
||||||
|
dispatch({ type: "setDocument", doc: sceneDoc });
|
||||||
await onCreate(sceneDoc);
|
await onCreate(sceneDoc);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(e?.message || "Failed to add scene.");
|
setError(e?.message || "Failed to add scene.");
|
||||||
|
|||||||
@@ -1,24 +1,24 @@
|
|||||||
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
||||||
import { pb } from "@/lib/pocketbase";
|
import { pb } from "@/lib/pocketbase";
|
||||||
import type { Scene } from "@/lib/types";
|
import type { Scene } from "@/lib/types";
|
||||||
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
import { useQueryClient } from "@tanstack/react-query";
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders an editable scene form
|
* Renders an editable scene form
|
||||||
*/
|
*/
|
||||||
export const SceneEditForm = ({ scene }: { scene: Scene }) => {
|
export const SceneEditForm = ({ scene }: { scene: Scene }) => {
|
||||||
|
const { dispatch } = useDocument();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
async function saveScene(text: string) {
|
async function saveScene(text: string) {
|
||||||
await pb.collection("documents").update(scene.id, {
|
const updated: Scene = await pb.collection("documents").update(scene.id, {
|
||||||
data: {
|
data: {
|
||||||
...scene.data,
|
...scene.data,
|
||||||
text,
|
text,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
queryClient.invalidateQueries({
|
dispatch({ type: "setDocument", doc: updated });
|
||||||
queryKey: ["relationship"],
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import type { CampaignId, Secret } from "@/lib/types";
|
|||||||
import { pb } from "@/lib/pocketbase";
|
import { pb } from "@/lib/pocketbase";
|
||||||
import { BaseForm } from "@/components/form/BaseForm";
|
import { BaseForm } from "@/components/form/BaseForm";
|
||||||
import { SingleLineInput } from "@/components/form/SingleLineInput";
|
import { SingleLineInput } from "@/components/form/SingleLineInput";
|
||||||
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders a form to add a new secret. Calls onCreate with the new secret document.
|
* Renders a form to add a new secret. Calls onCreate with the new secret document.
|
||||||
@@ -16,6 +17,7 @@ export const NewSecretForm = ({
|
|||||||
campaign: CampaignId;
|
campaign: CampaignId;
|
||||||
onCreate: (secret: Secret) => Promise<void>;
|
onCreate: (secret: Secret) => Promise<void>;
|
||||||
}) => {
|
}) => {
|
||||||
|
const { dispatch } = useDocument();
|
||||||
const [newSecret, setNewSecret] = useState("");
|
const [newSecret, setNewSecret] = useState("");
|
||||||
const [adding, setAdding] = useState(false);
|
const [adding, setAdding] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -35,6 +37,7 @@ export const NewSecretForm = ({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
setNewSecret("");
|
setNewSecret("");
|
||||||
|
dispatch({ type: "setDocument", doc: secretDoc as Secret});
|
||||||
await onCreate(secretDoc);
|
await onCreate(secretDoc);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(e?.message || "Failed to add secret.");
|
setError(e?.message || "Failed to add secret.");
|
||||||
@@ -45,7 +48,7 @@ export const NewSecretForm = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<BaseForm
|
<BaseForm
|
||||||
title="Create new treasure"
|
title="Create new secret"
|
||||||
isLoading={adding || !newSecret.trim()}
|
isLoading={adding || !newSecret.trim()}
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
error={error}
|
error={error}
|
||||||
@@ -53,7 +56,7 @@ export const NewSecretForm = ({
|
|||||||
<SingleLineInput
|
<SingleLineInput
|
||||||
value={newSecret}
|
value={newSecret}
|
||||||
onChange={setNewSecret}
|
onChange={setNewSecret}
|
||||||
placeholder="Treasure description"
|
placeholder="Secret description"
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,20 +1,16 @@
|
|||||||
// Displays a single secret with discovered checkbox and text.
|
// Displays a single secret with discovered checkbox and text.
|
||||||
import type { Secret, Session } from "@/lib/types";
|
|
||||||
import { pb } from "@/lib/pocketbase";
|
|
||||||
import { useState } from "react";
|
|
||||||
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
||||||
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
|
import { pb } from "@/lib/pocketbase";
|
||||||
|
import type { Secret } from "@/lib/types";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders an editable secret form.
|
* Renders an editable secret form.
|
||||||
* Handles updating the discovered state and discoveredIn relationship.
|
* Handles updating the discovered state and discoveredIn relationship.
|
||||||
*/
|
*/
|
||||||
export const SecretEditForm = ({
|
export const SecretEditForm = ({ secret }: { secret: Secret }) => {
|
||||||
secret,
|
const { dispatch } = useDocument();
|
||||||
session,
|
|
||||||
}: {
|
|
||||||
secret: Secret;
|
|
||||||
session?: Session;
|
|
||||||
}) => {
|
|
||||||
const [checked, setChecked] = useState(
|
const [checked, setChecked] = useState(
|
||||||
!!(secret.data as any)?.secret?.discovered,
|
!!(secret.data as any)?.secret?.discovered,
|
||||||
);
|
);
|
||||||
@@ -25,43 +21,28 @@ export const SecretEditForm = ({
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setChecked(newChecked);
|
setChecked(newChecked);
|
||||||
try {
|
try {
|
||||||
await pb.collection("documents").update(secret.id, {
|
const updated: Secret = await pb
|
||||||
|
.collection("documents")
|
||||||
|
.update(secret.id, {
|
||||||
data: {
|
data: {
|
||||||
...secret.data,
|
...secret.data,
|
||||||
discovered: newChecked,
|
discovered: newChecked,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (session || !newChecked) {
|
dispatch({ type: "setDocument", doc: updated });
|
||||||
// If the session exists or the element is being unchecked, remove any
|
|
||||||
// existing discoveredIn relationship
|
|
||||||
const rels = await pb.collection("relationships").getList(1, 1, {
|
|
||||||
filter: `primary = "${secret.id}" && type = "discoveredIn"`,
|
|
||||||
});
|
|
||||||
if (rels.items.length > 0) {
|
|
||||||
await pb.collection("relationships").delete(rels.items[0].id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (session) {
|
|
||||||
if (newChecked) {
|
|
||||||
await pb.collection("relationships").create({
|
|
||||||
primary: secret.id,
|
|
||||||
secondary: [session.id],
|
|
||||||
type: "discoveredIn",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveText(text: string) {
|
async function saveText(text: string) {
|
||||||
await pb.collection("documents").update(secret.id, {
|
const updated: Secret = await pb.collection("documents").update(secret.id, {
|
||||||
data: {
|
data: {
|
||||||
...secret.data,
|
...secret.data,
|
||||||
text,
|
text,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
dispatch({ type: "setDocument", doc: updated });
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,20 +1,22 @@
|
|||||||
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
||||||
import { useCache } from "@/context/cache/CacheContext";
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
import { pb } from "@/lib/pocketbase";
|
import { pb } from "@/lib/pocketbase";
|
||||||
import type { Session } from "@/lib/types";
|
import type { Session } from "@/lib/types";
|
||||||
|
|
||||||
export const SessionEditForm = ({ session }: { session: Session }) => {
|
export const SessionEditForm = ({ session }: { session: Session }) => {
|
||||||
const cache = useCache();
|
const { dispatch } = useDocument();
|
||||||
|
|
||||||
async function saveStrongStart(strongStart: string) {
|
async function saveStrongStart(strongStart: string) {
|
||||||
const freshRecord: Session = await pb
|
const doc: Session = await pb.collection("documents").update(session.id, {
|
||||||
.collection("documents")
|
|
||||||
.update(session.id, {
|
|
||||||
data: {
|
data: {
|
||||||
...session.data,
|
...session.data,
|
||||||
strongStart,
|
strongStart,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
cache.set(freshRecord);
|
dispatch({
|
||||||
|
type: "setDocument",
|
||||||
|
doc,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import type { CampaignId, Treasure } from "@/lib/types";
|
|||||||
import { pb } from "@/lib/pocketbase";
|
import { pb } from "@/lib/pocketbase";
|
||||||
import { BaseForm } from "@/components/form/BaseForm";
|
import { BaseForm } from "@/components/form/BaseForm";
|
||||||
import { SingleLineInput } from "@/components/form/SingleLineInput";
|
import { SingleLineInput } from "@/components/form/SingleLineInput";
|
||||||
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders a form to add a new treasure. Calls onCreate with the new treasure document.
|
* Renders a form to add a new treasure. Calls onCreate with the new treasure document.
|
||||||
@@ -16,6 +17,7 @@ export const NewTreasureForm = ({
|
|||||||
campaign: CampaignId;
|
campaign: CampaignId;
|
||||||
onCreate: (treasure: Treasure) => Promise<void>;
|
onCreate: (treasure: Treasure) => Promise<void>;
|
||||||
}) => {
|
}) => {
|
||||||
|
const { dispatch } = useDocument();
|
||||||
const [newTreasure, setNewTreasure] = useState("");
|
const [newTreasure, setNewTreasure] = useState("");
|
||||||
const [adding, setAdding] = useState(false);
|
const [adding, setAdding] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -35,6 +37,10 @@ export const NewTreasureForm = ({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
setNewTreasure("");
|
setNewTreasure("");
|
||||||
|
dispatch({
|
||||||
|
type: "setDocument",
|
||||||
|
doc: treasureDoc,
|
||||||
|
});
|
||||||
await onCreate(treasureDoc);
|
await onCreate(treasureDoc);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(e?.message || "Failed to add treasure.");
|
setError(e?.message || "Failed to add treasure.");
|
||||||
|
|||||||
@@ -1,20 +1,16 @@
|
|||||||
// Displays a single treasure with discovered checkbox and text.
|
// Displays a single treasure with discovered checkbox and text.
|
||||||
import type { Treasure, Session } from "@/lib/types";
|
|
||||||
import { pb } from "@/lib/pocketbase";
|
|
||||||
import { useState } from "react";
|
|
||||||
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
|
||||||
|
import { useDocument } from "@/context/document/DocumentContext";
|
||||||
|
import { pb } from "@/lib/pocketbase";
|
||||||
|
import type { Treasure } from "@/lib/types";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders an editable treasure form.
|
* Renders an editable treasure form.
|
||||||
* Handles updating the discovered state and discoveredIn relationship.
|
* Handles updating the discovered state and discoveredIn relationship.
|
||||||
*/
|
*/
|
||||||
export const TreasureEditForm = ({
|
export const TreasureEditForm = ({ treasure }: { treasure: Treasure }) => {
|
||||||
treasure,
|
const { dispatch } = useDocument();
|
||||||
session,
|
|
||||||
}: {
|
|
||||||
treasure: Treasure;
|
|
||||||
session?: Session;
|
|
||||||
}) => {
|
|
||||||
const [checked, setChecked] = useState(
|
const [checked, setChecked] = useState(
|
||||||
!!(treasure.data as any)?.treasure?.discovered,
|
!!(treasure.data as any)?.treasure?.discovered,
|
||||||
);
|
);
|
||||||
@@ -25,7 +21,9 @@ export const TreasureEditForm = ({
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setChecked(newChecked);
|
setChecked(newChecked);
|
||||||
try {
|
try {
|
||||||
await pb.collection("documents").update(treasure.id, {
|
const updated: Treasure = await pb
|
||||||
|
.collection("documents")
|
||||||
|
.update(treasure.id, {
|
||||||
data: {
|
data: {
|
||||||
...treasure.data,
|
...treasure.data,
|
||||||
treasure: {
|
treasure: {
|
||||||
@@ -34,37 +32,22 @@ export const TreasureEditForm = ({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (session || !newChecked) {
|
dispatch({ type: "setDocument", doc: updated });
|
||||||
// If the session exists or the element is being unchecked, remove any
|
|
||||||
// existing discoveredIn relationship
|
|
||||||
const rels = await pb.collection("relationships").getList(1, 1, {
|
|
||||||
filter: `primary = "${treasure.id}" && type = "discoveredIn"`,
|
|
||||||
});
|
|
||||||
if (rels.items.length > 0) {
|
|
||||||
await pb.collection("relationships").delete(rels.items[0].id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (session) {
|
|
||||||
if (newChecked) {
|
|
||||||
await pb.collection("relationships").create({
|
|
||||||
primary: treasure.id,
|
|
||||||
secondary: [session.id],
|
|
||||||
type: "discoveredIn",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveText(text: string) {
|
async function saveText(text: string) {
|
||||||
await pb.collection("documents").update(treasure.id, {
|
const updated: Treasure = await pb
|
||||||
|
.collection("documents")
|
||||||
|
.update(treasure.id, {
|
||||||
data: {
|
data: {
|
||||||
...treasure.data,
|
...treasure.data,
|
||||||
text,
|
text,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
dispatch({ type: "setDocument", doc: updated });
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
74
src/context/cache/CacheContext.tsx
vendored
74
src/context/cache/CacheContext.tsx
vendored
@@ -1,74 +0,0 @@
|
|||||||
import { createContext, use, useContext, useMemo, useRef } from "react";
|
|
||||||
import type { ReactNode } from "react";
|
|
||||||
import { RecordCache } from "@/lib/recordCache";
|
|
||||||
import { pb } from "@/lib/pocketbase";
|
|
||||||
import { type DocumentId, type AnyDocument, CollectionIds } from "@/lib/types";
|
|
||||||
import { useQueryClient } from "@tanstack/react-query";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Context value for the record cache singleton.
|
|
||||||
*/
|
|
||||||
export type CacheContextValue = RecordCache;
|
|
||||||
|
|
||||||
const CacheContext = createContext<CacheContextValue | undefined>(undefined);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Provider for the record cache context. Provides a singleton RecordCache instance to children.
|
|
||||||
*/
|
|
||||||
export function CacheProvider({ children }: { children: ReactNode }) {
|
|
||||||
const cacheRef = useRef<RecordCache | undefined>(undefined);
|
|
||||||
if (!cacheRef.current) {
|
|
||||||
cacheRef.current = new RecordCache();
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<CacheContext.Provider value={cacheRef.current}>
|
|
||||||
{children}
|
|
||||||
</CacheContext.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hook to access the record cache context. Throws if used outside of CacheProvider.
|
|
||||||
*/
|
|
||||||
export function useCache(): CacheContextValue {
|
|
||||||
const ctx = useContext(CacheContext);
|
|
||||||
if (!ctx) throw new Error("useCache must be used within a CacheProvider");
|
|
||||||
return ctx;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useDocument(documentId: DocumentId): AnyDocument {
|
|
||||||
const cache = useCache();
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
|
|
||||||
async function fetchItems() {
|
|
||||||
const cacheValue = cache.getDocument(documentId);
|
|
||||||
|
|
||||||
if (cacheValue) {
|
|
||||||
console.info(`Serving ${documentId} from cache.`);
|
|
||||||
return cacheValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { doc } = await queryClient.fetchQuery({
|
|
||||||
queryKey: [CollectionIds.Documents, documentId],
|
|
||||||
queryFn: async () => {
|
|
||||||
const doc: AnyDocument = await pb
|
|
||||||
.collection("documents")
|
|
||||||
.getOne(documentId, {
|
|
||||||
expand:
|
|
||||||
"relationships_via_primary,relationships_via_primary.secondary",
|
|
||||||
});
|
|
||||||
|
|
||||||
console.info(`Saving ${documentId} to cache.`);
|
|
||||||
cache.set(doc);
|
|
||||||
|
|
||||||
return { doc };
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return doc;
|
|
||||||
}
|
|
||||||
|
|
||||||
const items = useMemo(fetchItems, [documentId, cache, queryClient]);
|
|
||||||
|
|
||||||
return use(items);
|
|
||||||
}
|
|
||||||
70
src/context/document/DocumentContext.tsx
Normal file
70
src/context/document/DocumentContext.tsx
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
import { pb } from "@/lib/pocketbase";
|
||||||
|
import { type AnyDocument, type DocumentId } from "@/lib/types";
|
||||||
|
import type { RecordModel } from "pocketbase";
|
||||||
|
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";
|
||||||
|
|
||||||
|
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 [state, dispatch] = useReducer(reducer, loading());
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
async function fetchDocumentAndRelations() {
|
||||||
|
const doc: AnyDocument = await 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;
|
||||||
|
}
|
||||||
20
src/context/document/actions.ts
Normal file
20
src/context/document/actions.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import type { AnyDocument, Relationship } from "@/lib/types";
|
||||||
|
|
||||||
|
export type DocumentAction<D extends AnyDocument> =
|
||||||
|
| {
|
||||||
|
type: "loading";
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
type: "ready";
|
||||||
|
doc: D;
|
||||||
|
relationships: Relationship[];
|
||||||
|
relatedDocuments: AnyDocument[];
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
type: "setDocument";
|
||||||
|
doc: AnyDocument;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
type: "setRelationship";
|
||||||
|
relationship: Relationship;
|
||||||
|
};
|
||||||
71
src/context/document/reducer.ts
Normal file
71
src/context/document/reducer.ts
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import _ from "lodash";
|
||||||
|
import type {
|
||||||
|
AnyDocument,
|
||||||
|
DocumentId,
|
||||||
|
Relationship,
|
||||||
|
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 "setDocument":
|
||||||
|
return ifStatus("ready", state, (state) => {
|
||||||
|
if (state.doc.id === action.doc.id) {
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
doc: action.doc as D,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
relatedDocs: {
|
||||||
|
...state.relatedDocs,
|
||||||
|
[action.doc.id]: action.doc,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
case "setRelationship":
|
||||||
|
return ifStatus("ready", state, (state) => ({
|
||||||
|
...state,
|
||||||
|
relationships: {
|
||||||
|
...state.relationships,
|
||||||
|
[action.relationship.type]: action.relationship,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
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",
|
||||||
|
});
|
||||||
@@ -5,42 +5,45 @@ import {
|
|||||||
type Relationship,
|
type Relationship,
|
||||||
type DocumentId,
|
type DocumentId,
|
||||||
type RelationshipId,
|
type RelationshipId,
|
||||||
|
type DbRecord,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
type CacheKey<C extends CollectionId = CollectionId> = `${C}:${string}`;
|
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 DocumentKey = CacheKey<typeof CollectionIds.Documents>;
|
||||||
type RelationshipKey = CacheKey<typeof CollectionIds.Relationships>;
|
type RelationshipKey = CacheKey<typeof CollectionIds.Relationships>;
|
||||||
|
|
||||||
export class RecordCache {
|
export class RecordCache {
|
||||||
private cache: Record<
|
private cache: Record<`${CollectionId}:${string}`, CacheValue> = {};
|
||||||
`${CollectionId}:${string}`,
|
|
||||||
{
|
|
||||||
record: AnyDocument | Relationship;
|
|
||||||
subscriptions: ((record: AnyDocument | Relationship | null) => void)[];
|
|
||||||
}
|
|
||||||
> = {};
|
|
||||||
|
|
||||||
private makeKey<C extends CollectionId>(
|
static makeKey<C extends CollectionId>(
|
||||||
collectionId: C,
|
collectionId: C,
|
||||||
id: string,
|
id: string,
|
||||||
): CacheKey<C> {
|
): CacheKey<C> {
|
||||||
return `${collectionId}:${id}`;
|
return `${collectionId}:${id}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
private docKey = (id: DocumentId): DocumentKey =>
|
static docKey = (id: DocumentId): DocumentKey =>
|
||||||
this.makeKey(CollectionIds.Documents, id);
|
RecordCache.makeKey(CollectionIds.Documents, id);
|
||||||
|
|
||||||
private relationKey = (id: RelationshipId): RelationshipKey =>
|
static relationKey = (id: RelationshipId): RelationshipKey =>
|
||||||
this.makeKey(CollectionIds.Relationships, id);
|
RecordCache.makeKey(CollectionIds.Relationships, id);
|
||||||
|
|
||||||
get = (key: CacheKey): AnyDocument | Relationship | undefined =>
|
get = <C extends CollectionId>(
|
||||||
this.cache[key]?.record;
|
key: CacheKey<C>,
|
||||||
|
): Promise<DbRecord<C>> | undefined =>
|
||||||
|
this.cache[key]?.record as Promise<DbRecord<C>> | undefined;
|
||||||
|
|
||||||
set = (record: AnyDocument | Relationship) => {
|
pending = <C extends CollectionId>(
|
||||||
const key = this.makeKey(record.collectionName, record.id);
|
key: CacheKey<C>,
|
||||||
|
record: Promise<DbRecord<C>>,
|
||||||
|
) => {
|
||||||
if (this.cache[key] === undefined) {
|
if (this.cache[key] === undefined) {
|
||||||
this.cache[key] = {
|
this.cache[key] = {
|
||||||
record,
|
record: record,
|
||||||
subscriptions: [],
|
subscriptions: [],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -48,6 +51,34 @@ export class RecordCache {
|
|||||||
|
|
||||||
entry.record = record;
|
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) {
|
for (const subscription of entry.subscriptions) {
|
||||||
subscription(record);
|
subscription(record);
|
||||||
}
|
}
|
||||||
@@ -69,13 +100,13 @@ export class RecordCache {
|
|||||||
};
|
};
|
||||||
|
|
||||||
getDocument = (id: DocumentId): AnyDocument | undefined =>
|
getDocument = (id: DocumentId): AnyDocument | undefined =>
|
||||||
this.get(this.docKey(id)) as AnyDocument | undefined;
|
this.get(RecordCache.docKey(id)) as AnyDocument | undefined;
|
||||||
|
|
||||||
getRelationship = (id: RelationshipId): Relationship | undefined =>
|
getRelationship = (id: RelationshipId): Relationship | undefined =>
|
||||||
this.get(this.relationKey(id)) as Relationship | undefined;
|
this.get(RecordCache.relationKey(id)) as Relationship | undefined;
|
||||||
|
|
||||||
removeDocument = (id: DocumentId) => this.remove(this.docKey(id));
|
removeDocument = (id: DocumentId) => this.remove(RecordCache.docKey(id));
|
||||||
|
|
||||||
removeRelationship = (id: RelationshipId) =>
|
removeRelationship = (id: RelationshipId) =>
|
||||||
this.remove(this.relationKey(id));
|
this.remove(RecordCache.relationKey(id));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,7 @@
|
|||||||
import type { RecordModel } from "pocketbase";
|
import type { RecordModel } from "pocketbase";
|
||||||
|
|
||||||
export type Id<T extends string> = string & { __type: T };
|
|
||||||
|
|
||||||
export type UserId = Id<"User">;
|
|
||||||
export type CampaignId = Id<"Campaign">;
|
|
||||||
export type DocumentId = Id<"Document">;
|
|
||||||
export type RelationshipId = Id<"Relationship">;
|
|
||||||
|
|
||||||
export type ISO8601Date = string & { __type: "iso8601date" };
|
|
||||||
|
|
||||||
export const CollectionIds = {
|
export const CollectionIds = {
|
||||||
|
Users: "users",
|
||||||
Campaigns: "campaigns",
|
Campaigns: "campaigns",
|
||||||
Documents: "documents",
|
Documents: "documents",
|
||||||
Relationships: "relationships",
|
Relationships: "relationships",
|
||||||
@@ -17,6 +9,26 @@ export const CollectionIds = {
|
|||||||
|
|
||||||
export type CollectionId = (typeof CollectionIds)[keyof typeof CollectionIds];
|
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 & {
|
export type Campaign = RecordModel & {
|
||||||
id: CampaignId;
|
id: CampaignId;
|
||||||
name: string;
|
name: string;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { AuthProvider } from "@/context/auth/AuthContext";
|
import { AuthProvider } from "@/context/auth/AuthContext";
|
||||||
import { CacheProvider } from "@/context/cache/CacheContext";
|
|
||||||
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
|
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
|
||||||
import { Outlet, createRootRoute } from "@tanstack/react-router";
|
import { Outlet, createRootRoute } from "@tanstack/react-router";
|
||||||
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
|
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
|
||||||
@@ -8,9 +7,7 @@ export const Route = createRootRoute({
|
|||||||
component: () => (
|
component: () => (
|
||||||
<>
|
<>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<CacheProvider>
|
|
||||||
<Outlet />
|
<Outlet />
|
||||||
</CacheProvider>
|
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
<TanStackRouterDevtools />
|
<TanStackRouterDevtools />
|
||||||
<ReactQueryDevtools buttonPosition="bottom-right" />
|
<ReactQueryDevtools buttonPosition="bottom-right" />
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
import { RelationshipList } from "@/components/RelationshipList";
|
import { DocumentView } from "@/components/documents/DocumentView";
|
||||||
import { DocumentEditForm } from "@/components/documents/DocumentEditForm";
|
import { DocumentProvider } from "@/context/document/DocumentContext";
|
||||||
import { displayName, relationshipsForDocument } from "@/lib/relationships";
|
|
||||||
import { Tab, TabGroup, TabList, TabPanel, TabPanels } from "@headlessui/react";
|
|
||||||
import { createFileRoute, Link } from "@tanstack/react-router";
|
|
||||||
import { useDocument } from "@/context/cache/CacheContext";
|
|
||||||
import type { DocumentId } from "@/lib/types";
|
import type { DocumentId } from "@/lib/types";
|
||||||
|
import { createFileRoute } from "@tanstack/react-router";
|
||||||
|
|
||||||
export const Route = createFileRoute(
|
export const Route = createFileRoute(
|
||||||
"/_app/_authenticated/document/$documentId",
|
"/_app/_authenticated/document/$documentId",
|
||||||
@@ -14,44 +11,11 @@ export const Route = createFileRoute(
|
|||||||
|
|
||||||
function RouteComponent() {
|
function RouteComponent() {
|
||||||
const { documentId } = Route.useParams();
|
const { documentId } = Route.useParams();
|
||||||
|
console.info("Rendering document route: ", documentId);
|
||||||
const doc = useDocument(documentId as DocumentId);
|
|
||||||
|
|
||||||
const relationshipList = relationshipsForDocument(doc);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={doc.id} className="max-w-xl mx-auto py-2 px-4">
|
<DocumentProvider documentId={documentId as DocumentId}>
|
||||||
<Link
|
<DocumentView />
|
||||||
to="/document/$documentId/print"
|
</DocumentProvider>
|
||||||
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>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user