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

storeSelectors.ts

68 lines2.1 KB

1import { type ScopedProjectRef, type ScopedThreadRef, type ThreadId } from "@t3tools/contracts";
2import { selectEnvironmentState, type AppState, type EnvironmentState } from "./store";
3import { type Project, 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;
12​
13function createScopedThreadSelector(
14 resolveRef: (state: AppState) => ScopedThreadRef | null | undefined,
15): (state: AppState) => Thread | undefined {
16 let previousEnvironmentState: EnvironmentState | undefined;
17 let previousThreadId: ThreadId | undefined;
18 let previousThread: Thread | undefined;
19​
20 return (state) => {
21 const ref = resolveRef(state);
22 if (!ref) {
23 return undefined;
24 }
25​
26 const environmentState = selectEnvironmentState(state, ref.environmentId);
27 if (
28 previousThread &&
29 previousEnvironmentState === environmentState &&
30 previousThreadId === ref.threadId
31 ) {
32 return previousThread;
33 }
34​
35 previousEnvironmentState = environmentState;
36 previousThreadId = ref.threadId;
37 previousThread = getThreadFromEnvironmentState(environmentState, ref.threadId);
38 return previousThread;
39 };
41​
42export function createThreadSelectorByRef(
43 ref: ScopedThreadRef | null | undefined,
44): (state: AppState) => Thread | undefined {
45 return createScopedThreadSelector(() => ref);
47​
48export function createThreadSelectorAcrossEnvironments(
49 threadId: ThreadId | null | undefined,
50): (state: AppState) => Thread | undefined {
51 return createScopedThreadSelector((state) => {
52 if (!threadId) {
53 return undefined;
54 }
55​
56 for (const [environmentId, environmentState] of Object.entries(
57 state.environmentStateById,
58 ) as Array<[ScopedThreadRef["environmentId"], EnvironmentState]>) {
59 if (environmentState.threadShellById[threadId]) {
60 return {
61 environmentId,
62 threadId,
63 };
64 }
65 }
66 return undefined;
67 });