Open History to see the last commit
1import { create } from "zustand";
2
3import type { ScopedThreadRef } from "@t3tools/contracts";
4
5/**
6 * `scopedThreadKey` joins with `:`, so two distinct refs can collide when an id
7 * itself contains one; drops must never cross threads on that account.
8 */
9export function isSameSidebarThreadRef(a: ScopedThreadRef, b: ScopedThreadRef): boolean {
10 return a.environmentId === b.environmentId && a.threadId === b.threadId;
11}
12
13export interface SidebarPendingFileDrop {
14 id: string;
15 threadRef: ScopedThreadRef;
16 files: File[];
17}
18
19interface SidebarPendingFileDropStoreState {
20 pending: SidebarPendingFileDrop[];
21 queuePendingFileDrop: (entry: Omit<SidebarPendingFileDrop, "id">) => string;
22 clearPendingFileDrop: (id: string) => void;
23 clearPendingFileDropsForThread: (threadRef: ScopedThreadRef) => void;
24 consumePendingFileDrop: (threadRef: ScopedThreadRef) => File[] | null;
25}
26
27let nextPendingFileDropId = 0;
28
29export const useSidebarPendingFileDropStore = create<SidebarPendingFileDropStoreState>()(
30 (set, get) => ({
31 pending: [],
32 queuePendingFileDrop: (entry) => {
33 const id = `sidebar-file-drop-${(nextPendingFileDropId += 1)}`;
34 set((state) => ({ pending: [...state.pending, { ...entry, id }] }));
35 return id;
36 },
37 clearPendingFileDrop: (id) => {
38 set((state) => ({ pending: state.pending.filter((drop) => drop.id !== id) }));
39 },
40 clearPendingFileDropsForThread: (threadRef) => {
41 set((state) => ({
42 pending: state.pending.filter((drop) => !isSameSidebarThreadRef(drop.threadRef, threadRef)),
43 }));
44 },
45 consumePendingFileDrop: (threadRef) => {
46 const matches = get().pending.filter((drop) =>
47 isSameSidebarThreadRef(drop.threadRef, threadRef),
48 );
49 if (matches.length === 0) {
50 return null;
51 }
52 const matchedIds = new Set(matches.map((drop) => drop.id));
53 set((state) => ({ pending: state.pending.filter((drop) => !matchedIds.has(drop.id)) }));
54 return matches.flatMap((drop) => drop.files);
55 },
56 }),
57);