Open History to see the last commit
1import { useLocalSearchParams } from "expo-router";
2import { useMemo } from "react";
3import { EnvironmentId, ThreadId } from "@t3tools/contracts";
4
5import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
6import { EnvironmentScopedProjectShell } from "@t3tools/client-runtime";
7import { useRemoteCatalog } from "./use-remote-catalog";
8import { useRemoteEnvironmentState } from "./use-remote-environment-registry";
9
10function firstRouteParam(value: string | string[] | undefined): string | null {
11 if (Array.isArray(value)) {
12 return value[0] ?? null;
13 }
14
15 return value ?? null;
16}
17
18function deriveSelectedThread(
19 selectedThreadRef: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId } | null,
20 threads: ReadonlyArray<EnvironmentScopedThreadShell>,
21): EnvironmentScopedThreadShell | null {
22 if (!selectedThreadRef) {
23 return null;
24 }
25
26 return (
27 threads.find(
28 (thread) =>
29 thread.environmentId === selectedThreadRef.environmentId &&
30 thread.id === selectedThreadRef.threadId,
31 ) ?? null
32 );
33}
34
35function deriveSelectedThreadProject(
36 selectedThread: EnvironmentScopedThreadShell | null,
37 projects: ReadonlyArray<EnvironmentScopedProjectShell>,
38): EnvironmentScopedProjectShell | null {
39 if (!selectedThread) {
40 return null;
41 }
42
43 return (
44 projects.find(
45 (project) =>
46 project.environmentId === selectedThread.environmentId &&
47 project.id === selectedThread.projectId,
48 ) ?? null
49 );
50}
51
52export function useThreadSelection() {
53 const { projects, threads } = useRemoteCatalog();
54 const { environmentStateById, savedConnectionsById } = useRemoteEnvironmentState();
55 const params = useLocalSearchParams<{
56 environmentId?: string | string[];
57 threadId?: string | string[];
58 }>();
59 const selectedThreadRef = useMemo(() => {
60 const environmentId = firstRouteParam(params.environmentId);
61 const threadId = firstRouteParam(params.threadId);
62 if (!environmentId || !threadId) {
63 return null;
64 }
65
66 return {
67 environmentId: EnvironmentId.make(environmentId),
68 threadId: ThreadId.make(threadId),
69 };
70 }, [params.environmentId, params.threadId]);
71 const selectedThread = useMemo(
72 () => deriveSelectedThread(selectedThreadRef, threads),
73 [selectedThreadRef, threads],
74 );
75
76 const selectedThreadProject = useMemo(
77 () => deriveSelectedThreadProject(selectedThread, projects),
78 [projects, selectedThread],
79 );
80
81 const selectedEnvironmentConnection = selectedThread
82 ? (savedConnectionsById[selectedThread.environmentId] ?? null)
83 : null;
84 const selectedEnvironmentRuntime = selectedThread
85 ? (environmentStateById[selectedThread.environmentId] ?? null)
86 : null;
87
88 return {
89 selectedThreadRef,
90 selectedThread,
91 selectedThreadProject,
92 selectedEnvironmentConnection,
93 selectedEnvironmentRuntime,
94 };
95}