source: frontend/node_modules/immer/src/core/scope.ts

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 11 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 1.7 KB
Line 
1import {
2 Patch,
3 PatchListener,
4 Drafted,
5 Immer,
6 DRAFT_STATE,
7 ImmerState,
8 ProxyType,
9 getPlugin
10} from "../internal"
11import {die} from "../utils/errors"
12
13/** Each scope represents a `produce` call. */
14
15export interface ImmerScope {
16 patches_?: Patch[]
17 inversePatches_?: Patch[]
18 canAutoFreeze_: boolean
19 drafts_: any[]
20 parent_?: ImmerScope
21 patchListener_?: PatchListener
22 immer_: Immer
23 unfinalizedDrafts_: number
24}
25
26let currentScope: ImmerScope | undefined
27
28export function getCurrentScope() {
29 if (__DEV__ && !currentScope) die(0)
30 return currentScope!
31}
32
33function createScope(
34 parent_: ImmerScope | undefined,
35 immer_: Immer
36): ImmerScope {
37 return {
38 drafts_: [],
39 parent_,
40 immer_,
41 // Whenever the modified draft contains a draft from another scope, we
42 // need to prevent auto-freezing so the unowned draft can be finalized.
43 canAutoFreeze_: true,
44 unfinalizedDrafts_: 0
45 }
46}
47
48export function usePatchesInScope(
49 scope: ImmerScope,
50 patchListener?: PatchListener
51) {
52 if (patchListener) {
53 getPlugin("Patches") // assert we have the plugin
54 scope.patches_ = []
55 scope.inversePatches_ = []
56 scope.patchListener_ = patchListener
57 }
58}
59
60export function revokeScope(scope: ImmerScope) {
61 leaveScope(scope)
62 scope.drafts_.forEach(revokeDraft)
63 // @ts-ignore
64 scope.drafts_ = null
65}
66
67export function leaveScope(scope: ImmerScope) {
68 if (scope === currentScope) {
69 currentScope = scope.parent_
70 }
71}
72
73export function enterScope(immer: Immer) {
74 return (currentScope = createScope(currentScope, immer))
75}
76
77function revokeDraft(draft: Drafted) {
78 const state: ImmerState = draft[DRAFT_STATE]
79 if (
80 state.type_ === ProxyType.ProxyObject ||
81 state.type_ === ProxyType.ProxyArray
82 )
83 state.revoke_()
84 else state.revoked_ = true
85}
Note: See TracBrowser for help on using the repository browser.