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

thread-repository-pins.ts

50 lines1.7 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 pinThreadRepository,
4 unpinThreadRepository,
5 type PinnedThreadRepository,
6} from "@t3tools/client-runtime/state/thread-repositories";
7import type { ScopedThreadRef } from "@t3tools/contracts";
8import { Atom } from "effect/reactivity";
9​
10import { appAtomRegistry } from "./atom-registry";
11​
12const NO_PINS: ReadonlyArray<PinnedThreadRepository> = Object.freeze([]);
13​
14const pinsKey = (ref: ScopedThreadRef) => `${ref.environmentId}\u0000${ref.threadId}`;
15​
16// Kept for the session only: a relaunch shows the repositories the thread changed.
17const pinsByThreadAtom = Atom.make<Readonly<Record<string, ReadonlyArray<PinnedThreadRepository>>>>(
18 {},
19).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-repository-pins"));
20​
21function updatePins(
22 ref: ScopedThreadRef,
23 change: (pinned: ReadonlyArray<PinnedThreadRepository>) => ReadonlyArray<PinnedThreadRepository>,
24): void {
25 const key = pinsKey(ref);
26 appAtomRegistry.update(pinsByThreadAtom, (current) => {
27 const pinned = current[key] ?? NO_PINS;
28 const next = change(pinned);
29 return next === pinned ? current : { ...current, [key]: next };
30 });
32​
33export function pinRepositoryToThread(
34 ref: ScopedThreadRef,
35 repository: PinnedThreadRepository,
36): void {
37 updatePins(ref, (pinned) => pinThreadRepository(pinned, repository));
39​
40export function unpinRepositoryFromThread(ref: ScopedThreadRef, repositoryPath: string): void {
41 updatePins(ref, (pinned) => unpinThreadRepository(pinned, repositoryPath));
43​
44export function useThreadRepositoryPins(
45 ref: ScopedThreadRef | null,
46): ReadonlyArray<PinnedThreadRepository> {
47 return useAtomValue(pinsByThreadAtom, (current) =>
48 ref === null ? NO_PINS : (current[pinsKey(ref)] ?? NO_PINS),
49 );