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

composerDraftOperations.ts

39 lines1.4 KB

1const operationsByDraftKey = new Map<string, Set<AbortController>>();
2​
3/**
4 * Async work that writes into one draft (a context import, a picker) starts
5 * here. Whoever discards that draft or moves the composer off it aborts the
6 * work, so a late result never lands in a draft the user has left.
7 */
8export function startComposerDraftOperation(draftKey: string): {
9 readonly signal: AbortSignal;
10 readonly finish: () => void;
11} {
12 const controller = new AbortController();
13 const operations = operationsByDraftKey.get(draftKey) ?? new Set();
14 operations.add(controller);
15 operationsByDraftKey.set(draftKey, operations);
16 return {
17 signal: controller.signal,
18 finish: () => {
19 operations.delete(controller);
20 if (operations.size === 0 && operationsByDraftKey.get(draftKey) === operations) {
21 operationsByDraftKey.delete(draftKey);
22 }
23 },
24 };
26​
27export function abortComposerDraftOperations(draftKey: string): void {
28 const operations = operationsByDraftKey.get(draftKey);
29 if (!operations) return;
30 operationsByDraftKey.delete(draftKey);
31 for (const controller of operations) controller.abort();
33​
34export function abortComposerDraftOperationsWhere(matches: (draftKey: string) => boolean): void {
35 // Deleting the current entry while iterating a Map is safe.
36 for (const draftKey of operationsByDraftKey.keys()) {
37 if (matches(draftKey)) abortComposerDraftOperations(draftKey);
38 }