-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathedgesState.ts
52 lines (47 loc) · 1.35 KB
/
edgesState.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import {
atom,
selector,
} from 'recoil';
import BaseEdgeData from '../types/BaseEdgeData';
import { hasDuplicatedObjects } from '../utils/array';
/**
* Used to know what are the edges currently displayed within the Canvas component.
*/
export const edgesState = atom<BaseEdgeData[] | undefined>({
key: 'edgesState',
default: undefined,
});
/**
* Custom selector for the atom.
*
* Applies custom business logic and sanity check when manipulating the atom.
*/
export const edgesSelector = selector<BaseEdgeData[]>({
key: 'edgesSelector',
get: ({ get }): BaseEdgeData[] => {
const currentEdges: BaseEdgeData[] | undefined = get(edgesState);
if (typeof currentEdges === 'undefined') {
return window.initialCanvasDataset?.edges || [];
} else {
return currentEdges;
}
},
/**
* Ensures we don't update the edges if there are duplicates.
*
* @param set
* @param get
* @param reset
* @param newValue
*/
set: ({ set, get, reset }, newValue): void => {
const hasDuplicateEdges = hasDuplicatedObjects(newValue as BaseEdgeData[], 'id');
if (!hasDuplicateEdges) {
set(edgesState, newValue);
} else {
const message = `Duplicate edge ids found, the edges weren't updated to avoid to corrupt the dataset.`;
console.error(message, newValue);
throw new Error(message);
}
},
});