-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathdraftify.ts
60 lines (59 loc) · 1.43 KB
/
draftify.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
53
54
55
56
57
58
59
60
import {
Finalities,
Options,
Patches,
PatchesOptions,
Result,
} from './interface';
import { createDraft, finalizeDraft } from './draft';
import { isDraftable } from './utils';
import { dataTypes } from './constant';
export function draftify<
T extends object,
O extends PatchesOptions = false,
F extends boolean = false
>(
baseState: T,
options: Options<O, F>
): [T, (returnedValue: [T] | []) => Result<T, O, F>] {
const finalities: Finalities = {
draft: [],
revoke: [],
handledSet: new WeakSet<any>(),
};
let patches: Patches | undefined;
let inversePatches: Patches | undefined;
if (options.enablePatches) {
patches = [];
inversePatches = [];
}
const isMutable =
options.mark?.(baseState, dataTypes) === dataTypes.mutable ||
!isDraftable(baseState, options);
const draft = isMutable
? baseState
: createDraft({
original: baseState,
parentDraft: null,
finalities,
options,
});
return [
draft,
(returnedValue: [T] | [] = []) => {
const [finalizedState, finalizedPatches, finalizedInversePatches] =
finalizeDraft(
draft,
returnedValue,
patches,
inversePatches,
options.enableAutoFreeze
);
return (
options.enablePatches
? [finalizedState, finalizedPatches, finalizedInversePatches]
: finalizedState
) as Result<T, O, F>;
},
];
}