Open History to see the last commit
1import type { OlderSettledScope } from "@t3tools/client-runtime/state/threads";
2import type { EnvironmentId } from "@t3tools/contracts";
3import { useMemo, useSyncExternalStore } from "react";
4
5import { scopedProjectKey } from "../../lib/scopedEntities";
6import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../../state/olderSettledShelf";
7import type { PendingNewTask } from "../../state/use-pending-new-tasks";
8import {
9 buildThreadListV2Items,
10 buildThreadListV2ListItems,
11 getThreadListV2OrderedSection,
12 threadListInboxReturns,
13} from "./threadListV2";
14import { computeThreadMoveAvailability } from "./threadOrder";
15
16/**
17 * Screens' select handlers read the content-only key set; a fresh one per list rebuild gave
18 * every row a new handler whenever any thread shell changed. Keyed by a string, the set keeps
19 * its identity until its keys change.
20 */
21function useKeySet(newlineSeparatedKeys: string): ReadonlySet<string> {
22 return useMemo(
23 () => new Set(newlineSeparatedKeys.length === 0 ? [] : newlineSeparatedKeys.split("\n")),
24 [newlineSeparatedKeys],
25 );
26}
27
28type LayoutInput = Parameters<typeof buildThreadListV2Items>[0];
29
30/**
31 * Home's and the thread sidebar's thread list. Its result is one value a screen only reads:
32 * built inline, the list's inputs stayed open to mutation across the screen's other hooks, so
33 * the React Compiler cached none of it and every render of the screen re-rendered every row.
34 */
35export function useThreadListV2(input: {
36 readonly threads: LayoutInput["threads"];
37 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
38 readonly environmentId: EnvironmentId | null;
39 readonly projectRefs: LayoutInput["projectRefs"];
40 readonly searchQuery: string;
41 /** Threads that match the search by content, keyed like `threadSearchMatchKey`. */
42 readonly searchMatches: ReadonlyMap<string, unknown>;
43 readonly settlementEnvironmentIds: ReadonlySet<EnvironmentId>;
44 readonly snoozeEnvironmentIds: ReadonlySet<EnvironmentId>;
45 readonly pinReorderEnvironmentIds: ReadonlySet<EnvironmentId>;
46 readonly activeReorderEnvironmentIds: ReadonlySet<EnvironmentId>;
47 readonly queuedThreadKeys: ReadonlySet<string>;
48 readonly settledLimit: number;
49 readonly now: string;
50 readonly pendingOrder: LayoutInput["pendingOrder"];
51 readonly shelfPreferencesLoaded: boolean;
52 readonly workingShelfEnabled: boolean;
53 readonly workingShelfExpanded: boolean;
54 readonly snoozedShelfExpanded: boolean;
55 readonly settledShelfExpanded: boolean;
56 readonly selectedThreadKey: string | null;
57}) {
58 const { threads, workingShelfEnabled } = input;
59 // A thread can stop working when the threads change, or when its exit grace expires.
60 const inboxVersion = useSyncExternalStore(
61 threadListInboxReturns.subscribe,
62 threadListInboxReturns.getSnapshot,
63 );
64 const inbox = useMemo(
65 () => threadListInboxReturns.observe(workingShelfEnabled ? threads : null),
66 // oxlint-disable-next-line react/memo-dependencies -- the version signals an expired grace
67 [threads, workingShelfEnabled, inboxVersion],
68 );
69 // Up/down menu availability for every card, computed once per section per
70 // rebuild (see computeThreadMoveAvailability): per-thread planner calls made
71 // list construction quadratic, and this list rebuilds on every minute tick.
72 const sectionAvailability = (section: "pinned" | "active") =>
73 computeThreadMoveAvailability({
74 allThreads: threads,
75 section,
76 pendingOrder: input.pendingOrder,
77 reorderableEnvironmentIds:
78 section === "pinned" ? input.pinReorderEnvironmentIds : input.activeReorderEnvironmentIds,
79 ordered: getThreadListV2OrderedSection({
80 threads,
81 section,
82 pendingOrder: input.pendingOrder,
83 now: input.now,
84 settlementEnvironmentIds: input.settlementEnvironmentIds,
85 snoozeEnvironmentIds: input.snoozeEnvironmentIds,
86 queuedThreadKeys: input.queuedThreadKeys,
87 }),
88 });
89 const moveAvailability = new Map([
90 ...sectionAvailability("pinned"),
91 ...(workingShelfEnabled ? [] : sectionAvailability("active")),
92 ]);
93 // Older settled threads load in pages; the shelf lists them only as far as they are loaded.
94 const scopes = olderSettledScopes(input);
95 const olderSettledShelf = useOlderSettledShelf({
96 scopes,
97 expanded: input.settledShelfExpanded,
98 // A search lists only matches, so the shelf would page forever; loaded pages stay.
99 visibleCount: input.searchQuery.trim().length === 0 ? input.settledLimit : 0,
100 });
101 const layout = buildThreadListV2Items({
102 pendingOrder: input.pendingOrder,
103 threads: threads.filter((thread) => thread.archivedAt === null),
104 environmentId: input.environmentId,
105 projectRefs: input.projectRefs,
106 searchQuery: input.searchQuery,
107 matchedThreadKeys: new Set(input.searchMatches.keys()),
108 settlementEnvironmentIds: input.settlementEnvironmentIds,
109 snoozeEnvironmentIds: input.snoozeEnvironmentIds,
110 queuedThreadKeys: input.queuedThreadKeys,
111 settledLimit: input.settledLimit,
112 now: input.now,
113 workingShelfEnabled,
114 workingShelfExpanded: input.workingShelfExpanded,
115 inboxReturnAt: inbox.returnedAt,
116 isWorking: inbox.isWorking,
117 snoozedShelfExpanded: input.snoozedShelfExpanded,
118 settledShelfExpanded: input.settledShelfExpanded,
119 selectedThreadKey: input.selectedThreadKey,
120 isListedSettled: olderSettledShelf.isListed,
121 unloadedSettledCount: olderSettledShelf.unloadedCount(
122 threads.filter(
123 (thread) =>
124 thread.archivedAt === null &&
125 scopes.some(
126 (scope) =>
127 scope.environmentId === thread.environmentId &&
128 (scope.projectIds === null || scope.projectIds.includes(thread.projectId)),
129 ),
130 ),
131 ),
132 });
133 useOlderSettledShelfGrowth(olderSettledShelf, layout.listedSettledThreads);
134 const contentOnlyThreadKeys = useKeySet([...layout.contentOnlyThreadKeys].sort().join("\n"));
135 const scopedProjectKeys =
136 input.projectRefs == null
137 ? null
138 : new Set(input.projectRefs.map((ref) => scopedProjectKey(ref.environmentId, ref.projectId)));
139 const searchQuery = input.searchQuery.trim().toLocaleLowerCase();
140 const pendingTasks = input.pendingTasks.filter(
141 (pendingTask) =>
142 (input.environmentId === null || pendingTask.environmentId === input.environmentId) &&
143 (scopedProjectKeys === null ||
144 scopedProjectKeys.has(
145 scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
146 )) &&
147 (searchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(searchQuery)),
148 );
149 const items = buildThreadListV2ListItems({
150 items: layout.items,
151 pendingTasks,
152 workingCount: layout.workingCount,
153 workingShelfExpanded: input.workingShelfExpanded,
154 workingShelfHeaderIndex: layout.workingShelfHeaderIndex,
155 snoozedCount: layout.snoozedCount,
156 snoozedShelfExpanded: input.snoozedShelfExpanded,
157 snoozedShelfHeaderIndex: layout.snoozedShelfHeaderIndex,
158 settledCount: layout.settledCount,
159 settledShelfExpanded: input.settledShelfExpanded,
160 settledShelfHeaderIndex: layout.settledShelfHeaderIndex,
161 snoozeLabelNow: `${input.now.slice(0, 16)}:00.000Z`,
162 snoozeEnvironmentIds: input.snoozeEnvironmentIds,
163 queuedThreadKeys: input.queuedThreadKeys,
164 moveAvailability,
165 shelfPreferencesLoading: !input.shelfPreferencesLoaded,
166 });
167 return { layout, items, contentOnlyThreadKeys, olderSettledShelf };
168}
169
170/** The list's scope per environment: its projects there, or every project. */
171function olderSettledScopes(input: {
172 readonly environmentId: EnvironmentId | null;
173 readonly projectRefs: LayoutInput["projectRefs"];
174 readonly settlementEnvironmentIds: ReadonlySet<EnvironmentId>;
175}): ReadonlyArray<OlderSettledScope> {
176 const environmentIds =
177 input.environmentId === null ? [...input.settlementEnvironmentIds] : [input.environmentId];
178 return environmentIds.flatMap((environmentId): ReadonlyArray<OlderSettledScope> => {
179 if (input.projectRefs == null) return [{ environmentId, projectIds: null }];
180 const projectIds = input.projectRefs.flatMap((ref) =>
181 ref.environmentId === environmentId ? [ref.projectId] : [],
182 );
183 return projectIds.length === 0 ? [] : [{ environmentId, projectIds }];
184 });
185}