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

useThreadVisitedMigration.ts

40 lines1.9 KB

1import { RegistryContext } from "@effect/atom-react";
2import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
3import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4import { useContext, useEffect, useEffectEvent } from "react";
5​
6import { environmentThreadShells, threadEnvironment } from "../state/threads";
7import { useAtomCommand } from "../state/use-atom-command";
8import { useUiStateStore } from "../uiStateStore";
9​
10const migratedThreadKeys = new Set<string>();
11​
12// Subscribe outside render; shell updates must not re-render the layout for this one-time migration.
13export function useThreadVisitedMigration(): void {
14 const registry = useContext(RegistryContext);
15 const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
16 const migrate = useEffectEvent((threads: ReadonlyArray<EnvironmentThreadShell>) => {
17 for (const thread of threads) {
18 // Missing means unsupported; retain the local value until the server upgrades.
19 if (thread.lastVisitedAt === undefined) continue;
20 const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
21 if (migratedThreadKeys.has(threadKey)) continue;
22 migratedThreadKeys.add(threadKey);
23 const local = useUiStateStore.getState().threadLastVisitedAtById[threadKey];
24 if (!local) continue;
25 const localMs = Date.parse(local);
26 if (!Number.isFinite(localMs)) continue;
27 const serverMs = thread.lastVisitedAt === null ? null : Date.parse(thread.lastVisitedAt);
28 if (serverMs !== null && Number.isFinite(serverMs) && serverMs >= localMs) continue;
29 void visitThreadMutation({
30 environmentId: thread.environmentId,
31 input: { threadId: thread.id, visitedAt: local },
32 });
33 }
34 });
35 useEffect(
36 () =>
37 registry.subscribe(environmentThreadShells.threadShellsAtom, migrate, { immediate: true }),
38 [registry],
39 );