| 1 | import { scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 2 | import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; |
| 3 | import { useMemo } from "react"; |
| 4 | |
| 5 | /** |
| 6 | * The scoped ref of the thread a view shows, stable for as long as it shows that thread. |
| 7 | * Takes the thread object but keys on its ids: the shell changes identity on every update |
| 8 | * during a run, and effects keyed on this ref must not re-run for that. |
| 9 | */ |
| 10 | export function useActiveThreadRef( |
| 11 | thread: { readonly environmentId: EnvironmentId; readonly id: ThreadId } | null | undefined, |
| 12 | ): ScopedThreadRef | null { |
| 13 | const environmentId = thread?.environmentId ?? null; |
| 14 | const threadId = thread?.id ?? null; |
| 15 | return useMemo( |
| 16 | () => |
| 17 | environmentId !== null && threadId !== null ? scopeThreadRef(environmentId, threadId) : null, |
| 18 | [environmentId, threadId], |
| 19 | ); |
| 20 | } |