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

ArchivedThreadsPanel.tsx

372 lines13.5 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import type { ContextMenuSource } from "@t3tools/contracts";
3import { contextMenuSourceOf } from "../../contextMenuSource";
4import { m as resolveMessage } from "~/i18n/messages";
5import { settingsScopeEnvironmentLabels } from "./settingsScopeAxis";
6import { Spinner } from "~/components/ui/spinner";
7import { ArchiveIcon, ArchiveX, Trash2Icon } from "lucide-react";
8import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
9import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
10import {
11 type AtomCommandResult,
12 isAtomCommandInterrupted,
13 settlePromise,
14 squashAtomCommandFailure,
15} from "@t3tools/client-runtime/state/runtime";
16import { useSettingsScope } from "./SettingsScopeContext";
17import { useThreadActions } from "../../hooks/useThreadActions";
18import { readLocalApi } from "../../localApi";
19import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
20import { RelativeTime } from "../RelativeTime";
21import { Button } from "../ui/button";
22import { stackedThreadToast, toastManager } from "../ui/toast";
23import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
24import { useSearchableSetting } from "./settingsSearch";
25import { ProjectFavicon } from "../ProjectFavicon";
26​
27import { msg, T, useGT, useMessages } from "gt-react";
28import { type ReactNode, useRef, useState } from "react";
29import { observeIntersection } from "~/lib/observeIntersection";
30import { SharedTooltipTrigger } from "../ui/shared-tooltip";
31​
32const ARCHIVE_ACTIONS = [
33 {
34 action: "unarchive",
35 label: msg("Unarchive"),
36 threadLabel: msg("Unarchive {title}"),
37 failureTitle: msg("Failed to unarchive thread"),
38 Icon: ArchiveX,
39 },
40 {
41 action: "delete",
42 label: msg("Delete", { $context: "verb, deletes a thread" }),
43 threadLabel: msg("Delete {title}"),
44 failureTitle: msg("Failed to delete thread"),
45 Icon: Trash2Icon,
46 },
47] as const;
48type ArchiveAction = (typeof ARCHIVE_ACTIONS)[number]["action"];
49​
50const ARCHIVED_ROW_CHUNK_SIZE = 50;
51const ESTIMATED_ARCHIVED_ROW_PX = 67;
52​
53// Thousands of archived threads would mount at once, so each chunk of rows mounts only near the
54// visible part of the settings scroller and otherwise keeps its last measured height.
55function ArchivedThreadChunk(props: {
56 readonly rowCount: number;
57 readonly initiallyMounted: boolean;
58 readonly renderRows: () => ReactNode;
59}) {
60 const { rowCount } = props;
61 const [view, setView] = useState({
62 near: props.initiallyMounted,
63 rowHeight: ESTIMATED_ARCHIVED_ROW_PX,
64 });
65 return (
66 <div
67 ref={(node) => {
68 if (!node) return;
69 return observeIntersection(
70 node,
71 (entry) =>
72 setView({
73 near: entry.isIntersecting,
74 rowHeight: entry.boundingClientRect.height / rowCount,
75 }),
76 { root: node.closest("[data-settings-page-scroll]"), rootMargin: "1200px 0px" },
77 );
78 }}
79 className="*:not-first:border-t *:not-first:border-border/50"
80 style={view.near ? undefined : { height: view.rowHeight * rowCount }}
81 >
82 {view.near ? props.renderRows() : null}
83 </div>
84 );
86​
87export function ArchivedThreadsPanel() {
88 const searchableSetting = useSearchableSetting();
89 const gt = useGT();
90 const m = useMessages();
91 const { scope, groups: projectGroups, environments } = useSettingsScope();
92 const { unarchiveThread, confirmAndDeleteThread } = useThreadActions();
93 const pendingActionsRef = useRef(new Set<string>());
94 const [pendingKeys, setPendingKeys] = useState<ReadonlySet<string>>(() => new Set());
95 const {
96 snapshots: archivedSnapshots,
97 error: archiveError,
98 isLoading: isLoadingArchive,
99 refresh: refreshArchivedThreads,
100 } = useArchivedThreadSnapshots(scope.environmentIds);
101​
102 const { groups: archivedGroups, hasMultipleEnvironments } = (() => {
103 const selectedProjectKeys =
104 scope.kind === "project" || scope.kind === "checkout"
105 ? new Set(scope.members.map((member) => `${member.environmentId}:${member.id}`))
106 : null;
107 const projectsByEnvironmentAndId = new Map(
108 archivedSnapshots.flatMap(({ environmentId, snapshot }) =>
109 snapshot.projects
110 .filter(
111 (project) =>
112 selectedProjectKeys === null ||
113 selectedProjectKeys.has(`${environmentId}:${project.id}`),
114 )
115 .map(
116 (project) => [`${environmentId}:${project.id}`, { ...project, environmentId }] as const,
117 ),
118 ),
119 );
120 const environmentLabels = new Map(
121 environments.map((environment) => {
122 const { primary, secondary } = settingsScopeEnvironmentLabels(environment, environments);
123 return [environment.environmentId, secondary ? `${primary} (${secondary})` : primary];
124 }),
125 );
126 const threads = archivedSnapshots.flatMap(({ environmentId, snapshot }) =>
127 snapshot.threads.map((thread) => ({
128 ...presentThreadShell(environmentId, thread),
129 environmentLabel: environmentLabels.get(environmentId) ?? environmentId,
130 })),
131 );
132 const hasMultipleEnvironments =
133 new Set(
134 threads
135 .filter((thread) =>
136 projectsByEnvironmentAndId.has(`${thread.environmentId}:${thread.projectId}`),
137 )
138 .map((thread) => thread.environmentId),
139 ).size > 1;
140 const logicalGroupsByProjectKey = new Map(
141 projectGroups.flatMap((group) =>
142 group.memberProjectRefs.map(
143 (member) => [`${member.environmentId}:${member.projectId}`, group] as const,
144 ),
145 ),
146 );
147​
148 const archivedProjects = Array.from(projectsByEnvironmentAndId.values());
149 const groups = new Map<
150 string,
151 {
152 readonly project: (typeof archivedProjects)[number];
153 readonly title: string;
154 readonly threads: Array<(typeof threads)[number]>;
155 }
156 >();
157 for (const project of archivedProjects) {
158 const projectThreads: Array<(typeof threads)[number]> = [];
159 for (const thread of threads) {
160 if (thread.projectId === project.id && thread.environmentId === project.environmentId) {
161 projectThreads.push(thread);
162 }
163 }
164 if (projectThreads.length > 0) {
165 const physicalProjectKey = `${project.environmentId}:${project.id}` as const;
166 const logicalGroup = hasMultipleEnvironments
167 ? logicalGroupsByProjectKey.get(physicalProjectKey)
168 : undefined;
169 const groupKey = logicalGroup?.projectKey ?? physicalProjectKey;
170 const group = groups.get(groupKey);
171 if (group) {
172 group.threads.push(...projectThreads);
173 } else {
174 groups.set(groupKey, {
175 project,
176 title: logicalGroup?.displayName ?? project.title,
177 threads: projectThreads,
178 });
179 }
180 }
181 }
182 const sortedGroups = [];
183 let firstRow = 0;
184 for (const [key, group] of groups) {
185 sortedGroups.push({
186 ...group,
187 key,
188 firstRow,
189 threads: group.threads.toSorted((left, right) => {
190 const leftKey = left.archivedAt ?? left.createdAt;
191 const rightKey = right.archivedAt ?? right.createdAt;
192 return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id);
193 }),
194 });
195 firstRow += group.threads.length;
196 }
197 return { groups: sortedGroups, hasMultipleEnvironments };
198 })();
199​
200 type ArchivedThread = (typeof archivedGroups)[number]["threads"][number];
201​
202 const reportFailure = (result: AtomCommandResult<unknown, unknown> | null, title: string) => {
203 if (result?._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
204 const error = squashAtomCommandFailure(result);
205 toastManager.add(
206 stackedThreadToast({
207 type: "error",
208 title,
209 description:
210 error instanceof Error
211 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
212 : gt("An error occurred."),
213 }),
214 );
215 };
216​
217 const handleThreadAction = async (action: ArchiveAction, thread: ArchivedThread) => {
218 const target = scopeThreadRef(thread.environmentId, thread.id);
219 const key = scopedThreadKey(target);
220 // Context menus can outlive their render, so checks and cleanup use the live set.
221 const pending = pendingActionsRef.current;
222 if (pending.has(key)) return;
223 pending.add(key);
224 setPendingKeys(new Set(pending));
225 const result = await settlePromise(async () => {
226 const result = await (action === "unarchive"
227 ? unarchiveThread(target)
228 : confirmAndDeleteThread(target, thread.title));
229 if (result._tag === "Success") refreshArchivedThreads();
230 return result;
231 }).finally(() => {
232 pending.delete(key);
233 setPendingKeys(new Set(pending));
234 });
235 reportFailure(
236 result._tag === "Failure" ? result : result.value,
237 m(ARCHIVE_ACTIONS.find((entry) => entry.action === action)!.failureTitle),
238 );
239 };
240​
241 const handleContextMenu = async (
242 thread: ArchivedThread,
243 position: { x: number; y: number },
244 source: ContextMenuSource,
245 ) => {
246 const pending = pendingActionsRef.current;
247 if (pending.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)))) return;
248 const result = await settlePromise(async () => {
249 const clicked = await readLocalApi()?.contextMenu.show(
250 ARCHIVE_ACTIONS.map(({ action, label }) => ({
251 id: action,
252 label: m(label),
253 destructive: action === "delete",
254 })),
255 position,
256 source,
257 );
258 if (clicked === "unarchive" || clicked === "delete")
259 await handleThreadAction(clicked, thread);
260 });
261 reportFailure(result, gt("Archived thread action failed"));
262 };
263​
264 const renderRow = (thread: ArchivedThread) => {
265 const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
266 return (
267 <SettingsRow
268 key={`${thread.environmentId}:${thread.id}`}
269 className="rounded-none"
270 onContextMenu={(event) => {
271 event.preventDefault();
272 void handleContextMenu(
273 thread,
274 { x: event.clientX, y: event.clientY },
275 contextMenuSourceOf(event),
276 );
277 }}
278 title={thread.title}
279 description={
280 <span className={hasMultipleEnvironments ? "block truncate" : undefined}>
281 {hasMultipleEnvironments ? `${thread.environmentLabel} · ` : null}
282 <T>
283 Archived <RelativeTime timestamp={thread.archivedAt ?? thread.createdAt} />
284 {" \u00b7 Created "}
285 <RelativeTime timestamp={thread.createdAt} />
286 </T>
287 </span>
288 }
289 control={
290 <div className="flex shrink-0 items-center gap-2">
291 {ARCHIVE_ACTIONS.map(({ action, label, threadLabel, Icon }) => (
292 <SharedTooltipTrigger
293 key={action}
294 render={
295 <Button
296 type="button"
297 variant={action === "delete" ? "destructive-outline" : "outline"}
298 size="icon-sm"
299 aria-label={m(threadLabel, { title: thread.title })}
300 disabled={pendingKeys.has(threadKey)}
301 onClick={() => void handleThreadAction(action, thread)}
302 />
303 }
304 label={m(label)}
305 >
306 <Icon className="size-3.5" />
307 </SharedTooltipTrigger>
308 ))}
309 </div>
310 }
311 />
312 );
313 };
314​
315 return (
316 <SettingsPageContainer>
317 {archivedGroups.length === 0 ? (
318 <SettingsSection
319 id={isLoadingArchive ? undefined : searchableSetting("archive").id}
320 title={searchableSetting("archive").title}
321 >
322 <SettingsRow
323 title={
324 <span className="inline-flex items-center gap-2">
325 {isLoadingArchive ? (
326 <Spinner size="sm" tone="muted" />
327 ) : (
328 <ArchiveIcon className="size-3.5 text-muted-foreground" />
329 )}
330 {isLoadingArchive
331 ? gt("Loading archived threads")
332 : archiveError
333 ? gt("Could not load archived threads")
334 : gt("No archived threads")}
335 </span>
336 }
337 description={
338 isLoadingArchive
339 ? gt("Checking connected environments.")
340 : (archiveError ?? gt("Archived threads will appear here."))
341 }
342 />
343 </SettingsSection>
344 ) : (
345 archivedGroups.map(({ key, project, title, firstRow, threads: projectThreads }, index) => (
346 <SettingsSection
347 key={key}
348 id={index === 0 ? searchableSetting("archive").id : undefined}
349 title={title}
350 icon={<ProjectFavicon project={project} />}
351 >
352 {Array.from(
353 { length: Math.ceil(projectThreads.length / ARCHIVED_ROW_CHUNK_SIZE) },
354 (_, chunkIndex) => {
355 const start = chunkIndex * ARCHIVED_ROW_CHUNK_SIZE;
356 const rows = projectThreads.slice(start, start + ARCHIVED_ROW_CHUNK_SIZE);
357 return (
358 <ArchivedThreadChunk
359 key={chunkIndex}
360 rowCount={rows.length}
361 initiallyMounted={firstRow + start < ARCHIVED_ROW_CHUNK_SIZE}
362 renderRows={() => rows.map(renderRow)}
363 />
364 );
365 },
366 )}
367 </SettingsSection>
368 ))
369 )}
370 </SettingsPageContainer>
371 );