Open History to see the last commit
1import { type ScopedProjectRef, type ScopedThreadRef, type ThreadId } from "@t3tools/contracts";
2import { selectEnvironmentState, type AppState, type EnvironmentState } from "./store";
3import { type Project, type SidebarThreadSummary, type Thread } from "./types";
4import { getThreadFromEnvironmentState } from "./threadDerivation";
5
6export function createProjectSelectorByRef(
7 ref: ScopedProjectRef | null | undefined,
8): (state: AppState) => Project | undefined {
9 return (state) =>
10 ref ? selectEnvironmentState(state, ref.environmentId).projectById[ref.projectId] : undefined;
11}
12
13export function createSidebarThreadSummarySelectorByRef(
14 ref: ScopedThreadRef | null | undefined,
15): (state: AppState) => SidebarThreadSummary | undefined {
16 return (state) =>
17 ref
18 ? selectEnvironmentState(state, ref.environmentId).sidebarThreadSummaryById[ref.threadId]
19 : undefined;
20}
21
22function createScopedThreadSelector(
23 resolveRef: (state: AppState) => ScopedThreadRef | null | undefined,
24): (state: AppState) => Thread | undefined {
25 let previousEnvironmentState: EnvironmentState | undefined;
26 let previousThreadId: ThreadId | undefined;
27 let previousThread: Thread | undefined;
28
29 return (state) => {
30 const ref = resolveRef(state);
31 if (!ref) {
32 return undefined;
33 }
34
35 const environmentState = selectEnvironmentState(state, ref.environmentId);
36 if (
37 previousThread &&
38 previousEnvironmentState === environmentState &&
39 previousThreadId === ref.threadId
40 ) {
41 return previousThread;
42 }
43
44 previousEnvironmentState = environmentState;
45 previousThreadId = ref.threadId;
46 previousThread = getThreadFromEnvironmentState(environmentState, ref.threadId);
47 return previousThread;
48 };
49}
50
51export function createThreadSelectorByRef(
52 ref: ScopedThreadRef | null | undefined,
53): (state: AppState) => Thread | undefined {
54 return createScopedThreadSelector(() => ref);
55}
56
57export function createThreadSelectorAcrossEnvironments(
58 threadId: ThreadId | null | undefined,
59): (state: AppState) => Thread | undefined {
60 return createScopedThreadSelector((state) => {
61 if (!threadId) {
62 return undefined;
63 }
64
65 for (const [environmentId, environmentState] of Object.entries(
66 state.environmentStateById,
67 ) as Array<[ScopedThreadRef["environmentId"], EnvironmentState]>) {
68 if (environmentState.threadShellById[threadId]) {
69 return {
70 environmentId,
71 threadId,
72 };
73 }
74 }
75 return undefined;
76 });
77}