UNPKG

1.12 kBPlain TextView Raw
1import {
2 die,
3 isDraft,
4 shallowCopy,
5 each,
6 DRAFT_STATE,
7 set,
8 ImmerState,
9 isDraftable,
10 isFrozen
11} from "../internal"
12
13/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */
14export function current<T>(value: T): T
15export function current(value: any): any {
16 if (!isDraft(value)) die(10, value)
17 return currentImpl(value)
18}
19
20function currentImpl(value: any): any {
21 if (!isDraftable(value) || isFrozen(value)) return value
22 const state: ImmerState | undefined = value[DRAFT_STATE]
23 let copy: any
24 if (state) {
25 if (!state.modified_) return state.base_
26 // Optimization: avoid generating new drafts during copying
27 state.finalized_ = true
28 copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_)
29 } else {
30 copy = shallowCopy(value, true)
31 }
32 // recurse
33 each(copy, (key, childValue) => {
34 set(copy, key, currentImpl(childValue))
35 })
36 if (state) {
37 state.finalized_ = false
38 }
39 return copy
40}