Mirror of https://github.com/roostorg/coop
github.com/roostorg/coop
1import { ManualReviewJobEnqueuedActionData } from '../webpages/dashboard/mrt/manual_review_job/ManualReviewJobReview';
2
3const areRelatedActionsEqual = (
4 a: ManualReviewJobEnqueuedActionData,
5 b: ManualReviewJobEnqueuedActionData,
6) =>
7 a.action.id === b.action.id &&
8 a.target.identifier.itemTypeId === b.target.identifier.itemTypeId &&
9 a.target.identifier.itemId === b.target.identifier.itemId;
10
11/**
12 * This function recomputes the enqueued related actions based on the most
13 * recently chosen policies for each action. This is more complex than it seems
14 * at first glance because of scenarios such as selecting messages within a
15 * thread, where we might encounter diverse combinations of selected messages
16 * leading to the enqueueing of varied actions. To manage this, we prioritize
17 * the new actions introduced over the existing related actions in the queue.
18 * More specifically, if a new action comes into play, and there's an associated
19 * action already queued for this specific (actionId, itemId, itemTypeId)
20 * triplet, we override the existing action with the new one. This operation
21 * primarily serves to keep our selected policies up-to-date.
22 *
23 * @param newActions The new actions that are being enqueued from a user action
24 * @param selectedRelatedActions The currently enqueued related actions
25 * @param setSelectedRelatedActions Setter passed in from the caller (likely a
26 * state update to refresh the UI)
27 */
28export function recomputeSelectedRelatedActions(
29 newActions: ManualReviewJobEnqueuedActionData[],
30 selectedRelatedActions: ManualReviewJobEnqueuedActionData[],
31) {
32 if (selectedRelatedActions.length === 0) {
33 return newActions;
34 }
35
36 // We concatenate two arrays to recombine our final result before calling
37 // our setter:
38 // 1. We map over the selectedRelatedActions and replace each element with
39 // the corresponding element from newActions if there is one, otherwise
40 // we keep the current related action
41 // 2. We filter out any elements from newActions that had a corresponding
42 // related action in selectedRelatedActions
43 return [
44 ...selectedRelatedActions.map(
45 (relatedAction) =>
46 newActions.find((newAction) =>
47 areRelatedActionsEqual(relatedAction, newAction),
48 ) ?? relatedAction,
49 ),
50 ...newActions.filter(
51 (newAction) =>
52 !selectedRelatedActions.some((it) =>
53 areRelatedActionsEqual(newAction, it),
54 ),
55 ),
56 ];
57}