Open History to see the last commit
1import { useId, useState } from "react";
2
3interface WorkspaceVisit {
4 readonly threadKey: string | null;
5 readonly visit: number;
6 /** The revision this visit's reads start under. */
7 readonly revision: string;
8 /** Whether this visit's reads cover the mutation id the history will load with. */
9 readonly awaitsBaseline: boolean;
10 /** The mutation id the history loaded with; `undefined` until it loads. */
11 readonly baseline: string | null | undefined;
12}
13
14interface WorkspaceVisitInput {
15 readonly threadKey: string | null;
16 /** A settled server thread whose history is not synchronized yet. */
17 readonly unloaded: boolean;
18 readonly mutationId: string | null;
19}
20
21export interface WorkspaceRevision {
22 /** What workspace queries are read under; changes only when the workspace may have. */
23 readonly revision: string | null;
24 /** The history is not synchronized: the mutation id is unknown, not absent. */
25 readonly pending: boolean;
26}
27
28export function advanceWorkspaceVisit(
29 visit: WorkspaceVisit | null,
30 input: WorkspaceVisitInput,
31 instanceId: string,
32): WorkspaceVisit {
33 if (visit === null || visit.threadKey !== input.threadKey) {
34 const next = (visit?.visit ?? 0) + 1;
35 return {
36 threadKey: input.threadKey,
37 visit: next,
38 revision: `visit:${instanceId}:${next}:${input.threadKey ?? ""}`,
39 awaitsBaseline: input.unloaded,
40 baseline: undefined,
41 };
42 }
43 return visit.awaitsBaseline && visit.baseline === undefined && !input.unloaded
44 ? { ...visit, baseline: input.mutationId }
45 : visit;
46}
47
48export function workspaceRevisionOf(
49 visit: WorkspaceVisit,
50 mutationId: string | null,
51): WorkspaceRevision {
52 if (!visit.awaitsBaseline) return { revision: mutationId, pending: false };
53 if (visit.baseline === undefined) return { revision: visit.revision, pending: true };
54 return { revision: mutationId === visit.baseline ? visit.revision : mutationId, pending: false };
55}
56
57/**
58 * The revision a thread's workspace queries are read under. The mutation id a thread's history
59 * loads with was made before the visit began, so the reads the visit already started cover it:
60 * the visit keeps one revision of its own until an id replaces that one.
61 */
62export function useWorkspaceRevision(input: WorkspaceVisitInput): WorkspaceRevision {
63 const instanceId = useId();
64 const [visit, setVisit] = useState(() => advanceWorkspaceVisit(null, input, instanceId));
65 const current = advanceWorkspaceVisit(visit, input, instanceId);
66 if (current !== visit) setVisit(current);
67 return workspaceRevisionOf(current, input.mutationId);
68}