Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadRoutes.ts

102 lines2.6 KB

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 serverThreadExists: boolean;
26 serverThreadDeleted: boolean;
27 draftThreadExists: boolean;
28}): ThreadRouteRenderState {
29 if (!input.bootstrapComplete) {
30 return "loading";
31 }
32 if (input.draftThreadExists) {
33 return "ready";
34 }
35 if (input.serverThreadDeleted) {
36 return "missing";
37 }
38 return input.serverThreadExists ? "ready" : "missing";
40​
41export function buildThreadRouteParams(ref: ScopedThreadRef): {
42 environmentId: EnvironmentId;
43 threadId: ThreadId;
44} {
45 return {
46 environmentId: ref.environmentId,
47 threadId: ref.threadId,
48 };
50​
51export function buildDraftThreadRouteParams(draftId: DraftId): {
52 draftId: DraftId;
53} {
54 return { draftId };
56​
57export function resolveThreadRouteRef(
58 params: Partial<Record<"environmentId" | "threadId", string | undefined>>,
59): ScopedThreadRef | null {
60 if (!params.environmentId || !params.threadId) {
61 return null;
62 }
63​
64 return scopeThreadRef(params.environmentId as EnvironmentId, params.threadId as ThreadId);
66​
67export function resolveThreadRouteTarget(
68 params: Partial<Record<"environmentId" | "threadId" | "draftId", string | undefined>>,
69): ThreadRouteTarget | null {
70 if (params.environmentId && params.threadId) {
71 return {
72 kind: "server",
73 threadRef: scopeThreadRef(params.environmentId as EnvironmentId, params.threadId as ThreadId),
74 };
75 }
76​
77 if (!params.draftId) {
78 return null;
79 }
80​
81 return {
82 kind: "draft",
83 draftId: params.draftId as DraftId,
84 };
86​
87/**
88 * Resolves the thread represented by either a canonical thread route or a
89 * draft route whose promotion to a server thread has been recorded.
90 */
91export function resolveActiveThreadRouteRef(
92 target: ThreadRouteTarget | null,
93 draftThread: DraftThreadRouteState | null,
94): ScopedThreadRef | null {
95 if (target?.kind === "server") {
96 return target.threadRef;
97 }
98 if (target?.kind !== "draft" || !draftThread?.promotedTo) {
99 return null;
100 }
101 return draftThread.promotedTo;