diff --git a/src/components/documents/DocumentView.tsx b/src/components/documents/DocumentView.tsx index 224189d..da1ff86 100644 --- a/src/components/documents/DocumentView.tsx +++ b/src/components/documents/DocumentView.tsx @@ -30,6 +30,9 @@ export function DocumentView({ if (v.type === "ready") { return v.value.secondary.length.toString(); } + if (v.type === "empty") { + return "0"; + } return "..."; }); diff --git a/src/context/document/reducer.ts b/src/context/document/reducer.ts index 73f2d32..049eb31 100644 --- a/src/context/document/reducer.ts +++ b/src/context/document/reducer.ts @@ -1,14 +1,15 @@ -import _ from "lodash"; +import { relationshipsForDocument } from "@/lib/relationships"; import type { AnyDocument, DocumentId, Relationship } from "@/lib/types"; +import _ from "lodash"; import type { DocumentAction } from "./actions"; import { - ready, + empty, loading, + mapResult, + ready, unloaded, type DocumentState, - mapResult, } from "./state"; -import { relationshipsForDocument } from "@/lib/relationships"; function setLoadingDocument( docId: DocumentId, @@ -47,6 +48,36 @@ function setDocument(state: DocumentState, doc: AnyDocument): DocumentState { }; } +function setAllRelationshipsEmpty( + docId: DocumentId, + state: DocumentState, +): DocumentState { + const prevDocResult = state.documents[docId]; + if (prevDocResult?.type !== "ready") { + return state; + } + + const prevDoc = prevDocResult.value.doc; + const relationships = prevDocResult.value.relationships; + + return { + ...state, + documents: { + ...state.documents, + [docId]: ready({ + ...prevDocResult.value, + relationships: Object.fromEntries( + relationshipsForDocument(prevDoc).map((relType) => + relationships[relType]?.type === "ready" + ? [relType, relationships[relType]] + : [relType, empty()], + ), + ), + }), + }, + }; +} + function setRelationship( docId: DocumentId, state: DocumentState, @@ -118,7 +149,10 @@ export function reducer( setDocument, action.relationships.reduce( setRelationship.bind(null, action.doc.id), - setDocument(state, action.doc), + setAllRelationshipsEmpty( + action.doc.id, + setDocument(state, action.doc), + ), ), ); case "removeDocument": diff --git a/src/context/document/state.ts b/src/context/document/state.ts index c020e2b..55a3bb5 100644 --- a/src/context/document/state.ts +++ b/src/context/document/state.ts @@ -10,11 +10,13 @@ export type Result = | { type: "unloaded" } | { type: "error"; err: unknown } | { type: "loading" } + | { type: "empty" } | { type: "ready"; value: V }; export const unloaded = (): Result => ({ type: "unloaded" }); export const error = (err: unknown): Result => ({ type: "error", err }); export const loading = (): Result => ({ type: "loading" }); +export const empty = (): Result => ({ type: "empty" }); export const ready = (value: V): Result => ({ type: "ready", value }); export const mapResult = (