Open History to see the last commit
1import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
3import type { DraftId } from "./composerDraftStore";
4
5export type ThreadRouteTarget =
6 | {
7 kind: "server";
8 threadRef: ScopedThreadRef;
9 }
10 | {
11 kind: "draft";
12 draftId: DraftId;
13 };
14
15type DraftThreadRouteState = {
16 environmentId: EnvironmentId;
17 threadId: ThreadId;
18 promotedTo?: ScopedThreadRef | null;
19};
20
21export type ThreadRouteRenderState = "loading" | "ready" | "missing";
22
23export function resolveThreadRouteRenderState(input: {
24 bootstrapComplete: boolean;
25 serverThreadShellExists: boolean;
26 serverThreadDetailExists: boolean;
27 serverThreadDetailDeleted: boolean;
28 draftThreadExists: boolean;
29}): ThreadRouteRenderState {
30 if (!input.bootstrapComplete) {
31 return "loading";
32 }
33 if (input.serverThreadDetailExists || input.draftThreadExists) {
34 return "ready";
35 }
36 if (input.serverThreadDetailDeleted) {
37 return "missing";
38 }
39 return input.serverThreadShellExists ? "loading" : "missing";
40}
41
42export function buildThreadRouteParams(ref: ScopedThreadRef): {
43 environmentId: EnvironmentId;
44 threadId: ThreadId;
45} {
46 return {
47 environmentId: ref.environmentId,
48 threadId: ref.threadId,
49 };
50}
51
52export function buildDraftThreadRouteParams(draftId: DraftId): {
53 draftId: DraftId;
54} {
55 return { draftId };
56}
57
58export function resolveThreadRouteRef(
59 params: Partial<Record<"environmentId" | "threadId", string | undefined>>,
60): ScopedThreadRef | null {
61 if (!params.environmentId || !params.threadId) {
62 return null;
63 }
64
65 return scopeThreadRef(params.environmentId as EnvironmentId, params.threadId as ThreadId);
66}
67
68export function resolveThreadRouteTarget(
69 params: Partial<Record<"environmentId" | "threadId" | "draftId", string | undefined>>,
70): ThreadRouteTarget | null {
71 if (params.environmentId && params.threadId) {
72 return {
73 kind: "server",
74 threadRef: scopeThreadRef(params.environmentId as EnvironmentId, params.threadId as ThreadId),
75 };
76 }
77
78 if (!params.draftId) {
79 return null;
80 }
81
82 return {
83 kind: "draft",
84 draftId: params.draftId as DraftId,
85 };
86}
87
88/**
89 * Resolves the thread represented by either a canonical thread route or a
90 * draft route whose promotion to a server thread has been recorded.
91 */
92export function resolveActiveThreadRouteRef(
93 target: ThreadRouteTarget | null,
94 draftThread: DraftThreadRouteState | null,
95): ScopedThreadRef | null {
96 if (target?.kind === "server") {
97 return target.threadRef;
98 }
99 if (target?.kind !== "draft" || !draftThread?.promotedTo) {
100 return null;
101 }
102 return draftThread.promotedTo;
103}