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

shellReducer.ts

61 lines2.1 KB

1import type {
2 OrchestrationV2ShellSnapshot,
3 OrchestrationV2ShellStreamItem,
4} from "@t3tools/contracts";
5​
6function upsertById<T extends { readonly id: unknown }>(
7 items: ReadonlyArray<T>,
8 item: T,
9): ReadonlyArray<T> {
10 const index = items.findIndex((candidate) => candidate.id === item.id);
11 if (index === -1) return [...items, item];
12 return items.map((candidate, candidateIndex) => (candidateIndex === index ? item : candidate));
14​
15/** Applies one committed V2 shell delta while preserving active/archive exclusivity. */
16export function applyShellStreamEvent(
17 snapshot: OrchestrationV2ShellSnapshot,
18 event: Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>,
19): OrchestrationV2ShellSnapshot {
20 if (event.sequence <= snapshot.snapshotSequence) return snapshot;
21​
22 switch (event.kind) {
23 case "project.updated":
24 return {
25 ...snapshot,
26 projects: upsertById(snapshot.projects, event.project),
27 snapshotSequence: event.sequence,
28 };
29 case "project.removed":
30 return {
31 ...snapshot,
32 projects: snapshot.projects.filter((project) => project.id !== event.projectId),
33 snapshotSequence: event.sequence,
34 };
35 case "thread.updated": {
36 const withoutThread = (threads: OrchestrationV2ShellSnapshot["threads"]) =>
37 threads.filter((thread) => thread.id !== event.thread.id);
38 return {
39 ...snapshot,
40 threads:
41 event.location === "active"
42 ? upsertById(withoutThread(snapshot.threads), event.thread)
43 : withoutThread(snapshot.threads),
44 archivedThreads:
45 event.location === "archive"
46 ? upsertById(withoutThread(snapshot.archivedThreads), event.thread)
47 : withoutThread(snapshot.archivedThreads),
48 snapshotSequence: event.sequence,
49 };
50 }
51 case "thread.removed":
52 return {
53 ...snapshot,
54 threads: snapshot.threads.filter((thread) => thread.id !== event.threadId),
55 archivedThreads: snapshot.archivedThreads.filter((thread) => thread.id !== event.threadId),
56 snapshotSequence: event.sequence,
57 };
58 default:
59 return snapshot;
60 }