source: node_modules/immer/src/core/scope.ts@ ba17441

Last change on this file since ba17441 was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

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