Open History to see the last commit
1import { PULL_REQUEST_CHANGE_BATCH_LIMIT } from "@t3tools/contracts";
2
3/** Picks that differ from the host, keyed by candidate. Nothing is sent until the picker closes. */
4export type SelectionDraft<T> = ReadonlyMap<
5 string,
6 { readonly item: T; readonly selected: boolean }
7>;
8
9export function emptySelection<T>(): SelectionDraft<T> {
10 return new Map();
11}
12
13export function isSelected<T>(draft: SelectionDraft<T>, key: string, hostSelected: boolean) {
14 return draft.get(key)?.selected ?? hostSelected;
15}
16
17export function toggleSelection<T>(
18 draft: SelectionDraft<T>,
19 key: string,
20 item: T,
21 hostSelected: boolean,
22): SelectionDraft<T> {
23 const next = new Map(draft);
24 const selected = !isSelected(draft, key, hostSelected);
25 if (selected === hostSelected) next.delete(key);
26 else next.set(key, { item, selected });
27 return next;
28}
29
30/**
31 * What to send on close, diffed against the host's latest state rather than the state when the
32 * pick was made, so a refresh while the picker was open does not resend anything.
33 */
34export function selectionChanges<T>(
35 draft: SelectionDraft<T>,
36 hostSelected: (key: string, item: T) => boolean,
37): { readonly add: ReadonlyArray<T>; readonly remove: ReadonlyArray<T> } {
38 const add: T[] = [];
39 const remove: T[] = [];
40 for (const [key, { item, selected }] of draft) {
41 if (selected === hostSelected(key, item)) continue;
42 (selected ? add : remove).push(item);
43 }
44 return { add, remove };
45}
46
47/** Splits a change into writes the contract accepts. */
48export function changeBatches<T>(items: ReadonlyArray<T>): ReadonlyArray<ReadonlyArray<T>> {
49 const batches: Array<ReadonlyArray<T>> = [];
50 for (let start = 0; start < items.length; start += PULL_REQUEST_CHANGE_BATCH_LIMIT) {
51 batches.push(items.slice(start, start + PULL_REQUEST_CHANGE_BATCH_LIMIT));
52 }
53 return batches;
54}