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

threadRepositoryPinsStore.ts

42 lines1.7 KB

1import {
2 pinThreadRepository,
3 unpinThreadRepository,
4 type PinnedThreadRepository,
5} from "@t3tools/client-runtime/state/thread-repositories";
6import type { ScopedThreadRef } from "@t3tools/contracts";
7import { create } from "zustand";
8​
9const NO_PINS: ReadonlyArray<PinnedThreadRepository> = Object.freeze([]);
10​
11const pinsKey = (ref: ScopedThreadRef) => `${ref.environmentId}\u0000${ref.threadId}`;
12​
13interface ThreadRepositoryPinsStore {
14 /** Kept for the session only: a reload shows the repositories the thread changed. */
15 readonly pinsByThread: Readonly<Record<string, ReadonlyArray<PinnedThreadRepository>>>;
16 readonly pin: (ref: ScopedThreadRef, repository: PinnedThreadRepository) => void;
17 readonly unpin: (ref: ScopedThreadRef, repositoryPath: string) => void;
19​
20export const useThreadRepositoryPinsStore = create<ThreadRepositoryPinsStore>((set) => ({
21 pinsByThread: {},
22 pin: (ref, repository) =>
23 set((state) => {
24 const key = pinsKey(ref);
25 const current = state.pinsByThread[key] ?? NO_PINS;
26 const next = pinThreadRepository(current, repository);
27 return next === current ? state : { pinsByThread: { ...state.pinsByThread, [key]: next } };
28 }),
29 unpin: (ref, repositoryPath) =>
30 set((state) => {
31 const key = pinsKey(ref);
32 const current = state.pinsByThread[key] ?? NO_PINS;
33 const next = unpinThreadRepository(current, repositoryPath);
34 return next === current ? state : { pinsByThread: { ...state.pinsByThread, [key]: next } };
35 }),
36}));
37​
38export function useThreadRepositoryPins(
39 ref: ScopedThreadRef,
40): ReadonlyArray<PinnedThreadRepository> {
41 return useThreadRepositoryPinsStore((state) => state.pinsByThread[pinsKey(ref)] ?? NO_PINS);